SerialPort port = new SerialPort("COM3");
port.Open();
byte[] b = new byte[10];
port.Read(b, 0, 1);
port.Close();
请帮帮我
答案 0 :(得分:1)
这是因为SerialPort同步读取数据并阻塞当前线程,直到数据可用。
您可以使用单独的线程:
public class SerialPort : IDisposable
{
public SerialPort(byte comNum, int baudRate)
{
this.comNum = comNum;
serialPort = new System.IO.Ports.SerialPort("COM" + comNum.ToString(), baudRate);
serialPort.Open();
thread = new System.Threading.Thread(ThreadFn);
thread.Start();
}
public void Dispose()
{
if (thread != null)
thread.Abort();
if (serialPort != null)
serialPort.Dispose();
}
private void OnReceiveByte(byte b)
{
//handle received byte
}
private void ThreadFn(object obj)
{
Byte[] inputBuffer = new Byte[inputBufferSize];
while (true)
{
try
{
int availibleBytes = serialPort.BytesToRead;
if (availibleBytes > 0)
{
int bytesToRead = availibleBytes < inputBufferSize ? availibleBytes : inputBufferSize;
int readedBytes = serialPort.Read(inputBuffer, 0, bytesToRead);
for (int i = 0; i < readedBytes; i++)
OnReceiveByte(inputBuffer[i]);
}
System.Threading.Thread.Sleep(1);
}
catch (System.Threading.ThreadAbortException)
{
break;
}
catch (Exception e)
{
System.Diagnostics.Debug.Assert(false, e.Message);
}
}
}
private Byte comNum;
private System.IO.Ports.SerialPort serialPort;
private System.Threading.Thread thread;
private const int inputBufferSize = 1024;
}
答案 1 :(得分:0)
是否有任何数据通过串口发送?对Read的调用可能只是在返回之前等待接收一些数据。确保已为ReadTimeout属性设置了值。如果没有从端口读取数据,这将调用Read throw a TimeoutException。
参考: http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readtimeout.aspx
答案 2 :(得分:0)
还要确保你设置正确的串行速度(如果你读得太快,你会错过一些数据等)