程序和一个串口设备通讯,发出指令,然后读取设备响应数据,
但是读取的值总是不对。用SerialPortMonitor和串口助手检查过,不是设备出错,可以肯定是C#读取出错。但是不知道什么原因,波特率,数据位,停止位,校验位也都设置的没有错。例子1:
发送数据:01 01 00 00 00 04 3D C9
实际接收:01 3F 04 41 3F
正确数据:01 81 04 41 93例子2:
发送数据:01 11 C0 2C
实际接收:01 11 03 10 02 00 3F 28
正确数据:01 11 03 10 02 00 FD 28帮我看看吧:byte[] data = new byte[] { 0x01, 0x01, 0x00, 0x00, 0x00, 0x04, 0x3D, 0xC9 };
SerialPort com = new SerialPort("COM1");
com.BaudRate = 38400;
com.DataBits = 8;
com.StopBits = StopBits.One;
com.Parity = Parity.Even;
com.Open();
com.Write(data, 0, data.Length);
System.Threading.Thread.Sleep(100);string msg = "";
string s = com.ReadExisting();
com.Close();
foreach (char c in s)
{
int n = (int)c;
msg += n.ToString("X2") + " ";
}
MessageBox.Show(msg);
但是读取的值总是不对。用SerialPortMonitor和串口助手检查过,不是设备出错,可以肯定是C#读取出错。但是不知道什么原因,波特率,数据位,停止位,校验位也都设置的没有错。例子1:
发送数据:01 01 00 00 00 04 3D C9
实际接收:01 3F 04 41 3F
正确数据:01 81 04 41 93例子2:
发送数据:01 11 C0 2C
实际接收:01 11 03 10 02 00 3F 28
正确数据:01 11 03 10 02 00 FD 28帮我看看吧:byte[] data = new byte[] { 0x01, 0x01, 0x00, 0x00, 0x00, 0x04, 0x3D, 0xC9 };
SerialPort com = new SerialPort("COM1");
com.BaudRate = 38400;
com.DataBits = 8;
com.StopBits = StopBits.One;
com.Parity = Parity.Even;
com.Open();
com.Write(data, 0, data.Length);
System.Threading.Thread.Sleep(100);string msg = "";
string s = com.ReadExisting();
com.Close();
foreach (char c in s)
{
int n = (int)c;
msg += n.ToString("X2") + " ";
}
MessageBox.Show(msg);
整死了,结贴!