基于串口的读取电子秤数值
#region 读取电子秤数值
private SerialPort com;
private void getWeightfromCOM()
{
string COM ="COM1";
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); //接受数据线程
}
/// <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
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/15982148.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。