串口与工业手机通信,用超级终端连接发送都正常,但用C#中的SerialPort类来进行端口读写,连接正常,
发送也应该发送出去了,但没有任何接收,无限郁闷
串口配置如下:
serialPort.PortName = "COM3";
serialPort.BaudRate = 115200;
serialPort.DataBits = 8;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One ;
serialPort.ReadTimeout = 1000;
写操作:
serialPort.Write (msg);
读操作
注册DataReceived 事件:serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
读方法:
void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] readBuffer = new byte[serialPort.ReadBufferSize];
serialPort.Read(readBuffer, 0, readBuffer.Length);
string s = Encoding.Unicode.GetString(readBuffer);
textBox2.Text=s;
}
你试一下把serialPort.Parity = Parity.None;
改成serialPort.Parity = Parity.Space;
我之前遇到过这样的问题,改了就好了,应该都是端口参数设置的问题。
datareceived事情是辅助线程,无法直接调用主线程中的textbox控件,需要用控件的invoke方法.
程序应该会报错。既然你没有报错,所以串口根本没接受到数据,无法触发事情。首先串口参数要设置正确,这跟你的外设有关,然后用open方法打开。还有这样来读比较科学:
byte[] readBuffer = new byte[serialPort.BytesToRead];
serialPort.Read(readBuffer, 0, serialPort.BytesToRead);