请教(Money酬谢)---C#读取电子称串口数据,及时显示在TextBox控件
公司要求将电子称串口数据与电脑串口相连接,实现数据的即时通讯,其主要用来称产品,然后计算出相应个数。以下是我写的代码,基本都是参照网上高人写的。但是就是不能实现这个自动读取电脑称仪表数据的功能,以下是程序核心代码。
哪位高人能指点一下,本人感激万分。如果有朋友愿意协助下,定以适当Money作为酬谢。QQ:526284639
private void Form2_Load(object sender, EventArgs e)
{
InitPort();
}
private void InitPort()
{
com.BaudRate = 9600;
com.PortName = "COM4";
com.DataBits = 8;
com.Parity = Parity.None;
com.StopBits = StopBits.One;
com.WriteTimeout = 3000;
com.ReadTimeout = 3000;
com.ReceivedBytesThreshold = 1;
com.DtrEnable = true;
com.RtsEnable = true;
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);
if (!com.IsOpen)
{
com.Open();
}
else
{
MessageBox.Show("Please open relative port");
return;
}
}
private void com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (!com.IsOpen)
{
com.Open();
}
com.ReadTimeout = 500;
Thread.Sleep(500);
string res = "";
byte[] buffer = new byte[com.BytesToRead];
// MessageBox.Show(buffer.Length.ToString());
com.Read(buffer, 0, buffer.Length);
res = System.Text.Encoding.ASCII.GetString(buffer);
if (res == "")
{
MessageBox.Show("串口读取数据为空,参数设置是否正确!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void sendDataRequest()
{
byte[] arrByte = new byte[2];
//发送命令 1BH+70H 与电子称通讯,读取电子称数据,16进制
arrByte[0] = Convert.ToByte(0x1B);
arrByte[1] = 0x70;
com.Write(arrByte, 0, 2);
byte[] buffer = new byte[com.BytesToRead];
}