110,566
社区成员
发帖
与我相关
我的任务
分享
public Form1()
{
InitializeComponent();
}
SerialPort MyCom = new SerialPort();
public void OpenMyCom()
{
if (MyCom.IsOpen == true)
{
MyCom.Close();
}
MyCom.BaudRate = 9600;//波特率
MyCom.PortName = "COM7";//端口号
MyCom.DataBits = 8;//数据位
MyCom.Parity = Parity.None;
MyCom.StopBits = StopBits.One;
MyCom.ReceivedBytesThreshold = 1;
MyCom.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
MyCom.Open();
}
this.label1.Text += s;
来查看和调试累积收到的内容,而不是想当然地以为 s 中就是一个完整的消息。 public void WriteUtr()
{
byte[] SendCom = { 0x01, 0x03, 0x05, 0x20, 0x00, 0x02, 0xC5, 0x0D };//报文
while (true)
{
if (MyCom.BytesToRead == 0)//加判断,只有在缓冲区没有数据才发报文
{
MyCom.Write(SendCom, 0, 8);
System.Threading.Thread.Sleep(30);
}
else
{
return;
}
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
int len = MyCom.BytesToRead;
byte[] buff = new byte[len];
MyCom.Read(buff, 0, len);
string str = "";
for (int i = 0; i < len - 1; i++)
{
str = str + " " + buff[i].ToString();
}
if (this.label1.InvokeRequired)
{
this.label1.Invoke(new Action<string>(s => { this.label1.Text = s; }), str);
}
MyCom.DiscardInBuffer();//清输入缓冲区
}
private void button2_Click(object sender, EventArgs e)
{
Thread th1 = new Thread(WriteUtr);
th1.Start();
th1.IsBackground = true;
}
public void WriteUtr()
{
byte[] SendCom = { 0x01, 0x03, 0x05, 0x20, 0x00, 0x02, 0xC5, 0x0D };//报文
while (tr