C#通过SerialPort读取电子天平数据时,连接串口成功后,通过发送命令方式第一次操作无法获取数据,无任何数据返回,必须进行第二次操作才能获取当前数据。并且更新电子天平负载后,单击读取数据按钮,通过串口获得的数据为上一次读数,必须再单击一次才能获取更新的数据。一直卡到这里,不知道怎么解决,求大神帮忙看看!暂无积分,抱歉!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text.RegularExpressions;
namespace 读天平
{
public partial class Form1 : Form
{
SerialPort mySerialPort = null;
string receiveing;
string read_data;
int count_read;
int row_no;
int column_no;
DataGridView dgv;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
mySerialPort = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);
mySerialPort.Handshake = Handshake.None; // 四种都可以使用
mySerialPort.Open();
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceivedHandler);
mySerialPort.DtrEnable = true; // 加上此属性接收事件可被触发
mySerialPort.ReceivedBytesThreshold = 1;
if (mySerialPort.IsOpen == true)
{
MessageBox.Show("串口打开成功", "提示", MessageBoxButtons.OK);
}
else
{
MessageBox.Show("串口打开失败", "提示", MessageBoxButtons.OK);
}
}
private void mySerialPort_DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) // SerialPort.DataReceived事件运行比较特殊,其运行在辅线程,不能与主线程中的显示数据控件直接进行数据传输,必须用间接的方式实现
{//接收数据
SerialPort sp = (SerialPort)sender;
read_data = sp.ReadExisting();
this.Invoke((EventHandler)(delegate { receiveing = read_data.Trim().TrimStart('+').TrimStart('-').TrimEnd('g').Trim(); }));
mySerialPort.DiscardInBuffer(); // 清除接收缓存
}
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
byte[] send = { 0x1B, 0x70 }; // 十六进制ASCII码
mySerialPort.Write(send, 0, send.Length);
row_no = e.RowIndex;
column_no = e.ColumnIndex;
dgv = dataGridView1;
dgv.Rows[row_no].Cells[column_no].Value = receiveing;
}
private void dataGridView2_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
byte[] send = { 0x1B, 0x70 }; // 十六进制ASCII码
mySerialPort.Write(send, 0, send.Length);
row_no = e.RowIndex;
column_no = e.ColumnIndex;
dgv = dataGridView2;
dgv.Rows[row_no].Cells[column_no].Value = receiveing;
}
}
}