110,535
社区成员
发帖
与我相关
我的任务
分享
byte[] buf = new byte[20];
serialPort1.Read(buf, 0, 20);//收到的数据为byte
if (buf != null)
{
for (int ib = 0; ib < buf.Length; ib++)
{
datarecstr += buf[ib].ToString("X2");//将数据转为十六进制string显示
}
}
//已设置ReceivedBytesThreshold=20,使用事件回应接收
private void serialPort1_Datareceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
data = this.serialPort1.ReadExisting();//收到的数据为string
this.Invoke(new EventHandler(DisplayText));
}
private void DisplayText(object sender, EventArgs e)
{
byte[] byteArray = System.Text.Encoding.Default.GetBytes(data);//string转为byte
if (byteArray != null)
{
for (int ib = 0; (ib < byteArray.Length) & (ib < 20); ib++)
{
richTextBox1.Text += byteArray[ib].ToString("X2");//将数据转为十六进制string显示
}
}
}