如何从串口获取数据?

时间:2014-09-03 07:38:52

标签: c# windows-services serial-port listener

我有这段代码,但我不知道如何获取数据并将其放在一个变量中:

 protected override void OnStart(string[] args)
        {
            /* This WaitHandle will allow us to shutdown the thread when
               the OnStop method is called. */
            _shutdownEvent = new ManualResetEvent(false);

            /* Create the thread.  Note that it will do its work in the
               appropriately named DoWork method below. */
            _thread = new Thread(DoWork);

            /* Start the thread. */
            _thread.Start();
        }

然后在DoWork中我有以下内容:

private void DoWork()
        {

//opening serial port 
            SerialPort objSerialPort;
            objSerialPort = new SerialPort();

            objSerialPort.PortName = "COM2";
            objSerialPort.BaudRate = 11500;
            objSerialPort.Parity = Parity.None;
            objSerialPort.DataBits = 16;
            objSerialPort.StopBits = StopBits.One;
            objSerialPort.Open();

所以,我打开端口但是从哪里开始获取数据???如何初始化变量?收到的消息的格式为52 45 41 44 45 52 30 31,其中41 44 45 53 30是十六进制的消息,而52 45是标题和31 CRC。

请让我知道怎么做。

谢谢....

2 个答案:

答案 0 :(得分:1)

使用串口就像使用文件或套接字一样:

while ((bytesRead = objSerialPort.Read(buffer, 0, buffer.Length)) > 0)
{
    var checksum = buffer[bytesRead - 1];

    if (VerifyChecksum(checksum, buffer, bytesRead))  // Check the checksum
    {
        DoSomethinWithData(buffer, bytesRead);  // Do something with this bytes
    }
}

答案 1 :(得分:1)

byte[] buffer = new byte[1];
String message = "";

While (true)
{
  if(objSerialPort.Read(buffer,0,1)>0)
  {
  message+= System.Text.Encoding.UTF8.GetChars(buffer).ToString();
  //Or you could call another function here that will DoSomething with each byte coming in!
  }

}

应该做的伎俩!