2025年4月12日 星期六 乙巳(蛇)年 正月十三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > .net

Winform 串口通讯之读卡器

时间:04-11来源:作者:点击数:36

老板给我的第一个硬件就是一个读卡器,

说让我做一下试试,于是从网上查了查就写了出来,相当的简单。

但是后来还有一个地磅的串口通讯,我整整搞了一天。

在窗体类的构造函数中写入

Form.CheckForIllegalCrossThreadCalls = false;

可以在线程外更新窗体,这样就可以一直接收数据,一直更新ui了。

打开串口按钮:

  • 1 //实例化
  • 2 SerialPort Myport = new SerialPort();
  • 3 //设置串口端口
  • 4 Myport.PortName = cbxPortName.Text;
  • 5 //设置比特率
  • 6 Myport.BaudRate = Convert.ToInt32(cmbbaud.Text);
  • 7 //设置数据位
  • 8 Myport.DataBits = Convert.ToInt32(cmbBits.Text);
  • 9 //根据选择的数据,设置停止位
  • 10 //if (cmbStop.SelectedIndex == 0)
  • 11 // Myport.StopBits = StopBits.None;
  • 12 if (cmbStop.SelectedIndex == 1)
  • 13 Myport.StopBits = StopBits.One;
  • 14 if (cmbStop.SelectedIndex == 2)
  • 15 Myport.StopBits = StopBits.OnePointFive;
  • 16 if (cmbStop.SelectedIndex == 3)
  • 17 Myport.StopBits = StopBits.Two;
  • 18
  • 19 //根据选择的数据,设置奇偶校验位
  • 20 if (cmbParity.SelectedIndex == 0)
  • 21 Myport.Parity = Parity.Even;
  • 22 if (cmbParity.SelectedIndex == 1)
  • 23 Myport.Parity = Parity.Mark;
  • 24 if (cmbParity.SelectedIndex == 2)
  • 25 Myport.Parity = Parity.None;
  • 26 if (cmbParity.SelectedIndex == 3)
  • 27 Myport.Parity = Parity.Odd;
  • 28 if (cmbParity.SelectedIndex == 4)
  • 29 Myport.Parity = Parity.Space;
  • 30
  • 31 //此委托应该是异步获取数据的触发事件,即是:当有串口有数据传过来时触发
  • 32 Myport.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);//DataReceived事件委托
  • 33 //打开串口的方法
  • 34 try
  • 35 {
  • 36 Myport.Open();
  • 37 if (Myport.IsOpen)
  • 38 {
  • 39 MessageBox.Show("串口已打开");
  • 40 }
  • 41 else
  • 42 {
  • 43 MessageBox.Show("串口未能打开");
  • 44 }
  • 45 }
  • 46 catch (Exception ex)
  • 47 {
  • 48 MessageBox.Show("串口未能打开"+ex.ToString());
  • 49 }

关闭就使用 Myport.Close(); 在读卡器的串口通讯中是不会有问题的

DataReceived事件委托的方法

  • 1 private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  • 2 {
  • 3 try
  • 4 {
  • 5 string currentline = "";
  • 6 //循环接收串口中的数据
  • 7 while (Myport.BytesToRead > 0)
  • 8 {
  • 9 char ch = (char)Myport.ReadByte();
  • 10 currentline += ch.ToString();
  • 11 }
  • 12 //在这里对接收到的数据进行显示
  • 13 //如果不在窗体加载的事件里写上:Form.CheckForIllegalCrossThreadCalls = false; 就会报错)
  • 14 this.txtReceive.Text = currentline;
  • 15 }
  • 16 catch (Exception ex)
  • 17 {
  • 18 Console.WriteLine(ex.Message.ToString());
  • 19 }
  • 20 }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门