当前位置: 移动技术网 > IT编程>开发语言>.net > C#串口数据互通小程序

C#串口数据互通小程序

2019年01月09日  | 移动技术网IT编程  | 我要评论

爱你在心口难开伴奏,招玉芳老公,赵韵希

主要功能:

所编写的程序需将串口1、串口2数据互通,即:串口1接收到数据的同时将数据通过串口2发出,串口2接收到数据的同时将数据通过串口1发出。

并根据需要由指定串口发送或获取数据。

代码如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.threading.tasks;
using system.windows.forms;
using system.io.ports;

namespace 串口互通
{
    public partial class form1 : form
    {
        private serialport comm4 = new serialport("com4", 115200, parity.none, 8, stopbits.one);//因为我测试设备采用的是com4和com5两个串口,所以就直接在上面定义了
        private serialport comm5 = new serialport("com5", 115200, parity.none, 8, stopbits.one);
        private stringbuilder builder = new stringbuilder();//避免在事件处理方法中反复的创建,定义到外面
        byte[] buf1 = new byte[9] {90, 165, 6, 131, 0, 0, 1, 0, 2};//向串口下发的指令,在实际情况中是设备启动报文
        byte[] buf2 = new byte[9] {90, 165, 6, 131, 0, 0, 1, 0, 1};//设备停止报文
        public form1()
        {
            initializecomponent();
        }
        //打开串口按钮
        private void button1_click(object sender, eventargs e)
        {

            comm4.open();
            comm5.open();
button1.enabled=false;
button2.enabled=true; } //绑定方法到数据接收事件 private void form1_load(object sender, eventargs e) { comm4.datareceived+=comm4_datareceived; comm5.datareceived+=comm5_datareceived; } //com5口接收到的数据从com4口发出 private void comm5_datareceived(object sender, serialdatareceivedeventargs e) { int n = comm5.bytestoread; byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据 comm5.read(buf, 0, n);//读取缓冲数据 builder.clear();//清除字符串构造器的内容 comm4.write(buf, 0, buf.length);//数据从com4口发出 } //com4接收到的数据从com5口发出 private void comm4_datareceived(object sender, serialdatareceivedeventargs e) { int n = comm4.bytestoread; byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据 comm4.read(buf, 0, n);//读取缓冲数据 builder.clear();//清除字符串构造器的内容 comm5.write(buf, 0, buf.length);//数据从com5口发出 } //关闭串口按钮 private void button2_click(object sender, eventargs e) { comm4.close(); comm5.close();
button2.enabled=false;
button1.enabled=true; } //设备启动 private void button3_click(object sender, eventargs e) { comm5.write(buf1, 0, buf1.length); } //设备停止 private void button4_click(object sender, eventargs e) { comm5.write(buf2, 0, buf2.length); } } }

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网