C#实现连接电子秤串口自动称
2022/2/18 20:20:21
本文主要是介绍C#实现连接电子秤串口自动称,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、界面设计
二、核心代码
private SerialPort com; private void FormCheck_Load(object sender, EventArgs e) { //初始化COMList initCOMList(); } #region private void initCOMList() { ManageCOM com = new ManageCOM(); List<string> s = com.AutoGetCOM(); string[] comNames = s.ToArray(); comboxCOM.Items.Clear(); comboxCOM.Items.Add("请选择COM"); comboxCOM.SelectedIndex = 0; foreach (string portName in comNames) { //添加COM口到界面下拉框 comboxCOM.Items.Add(portName); } } #endregion private void btnStart_Click(object sender, EventArgs e) { getWeightfromCOM(); } #region private void getWeightfromCOM() { int selectIndex= comboxCOM.SelectedIndex; if (selectIndex!=0) { string COM = comboxCOM.Items[selectIndex].ToString(); com = new SerialPort(COM); //实例化SerialPort并设置COM口 com.BaudRate = 9600;//波特率 com.Parity = Parity.None;//无奇偶校验位 com.StopBits = StopBits.Two;//两个停止位 com.Handshake = Handshake.RequestToSend;//控制协议 com.ReceivedBytesThreshold = 13;//设置 DataReceived 事件发生前内部输入缓冲区中的字节数,我这里是13字节为一组 com.Open(); //打开串口 com.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived); //接受数据线程 } else { MessageBox.Show("请选择COM"); } } /// <summary> /// 监听串口数据线程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e) { Thread.Sleep(500);//线程休眠500毫秒,方便接收串口的全部数据 try { if (com.IsOpen) { byte[] readBuffer = new byte[com.ReadBufferSize + 1]; try { int count = com.Read(readBuffer, 0, com.ReadBufferSize); //读取串口数据(监听) String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer, 0, count);//将字节数组解码为字符串 if (count != 0) { //这里强调一下,线程里不可以直接对UI进行赋值,只能使用委托操作控件 this.BeginInvoke(new System.Threading.ThreadStart(delegate () { rbResult.Text = SerialIn; })); } } catch (TimeoutException) { } } else { TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50); Thread.Sleep(waitTime); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } #endregion
这篇关于C#实现连接电子秤串口自动称的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID