简体   繁体   English

如何从串口获取数据?

[英]How to get data from serial port?

I have this code but I don't know how to get the data and put it in one variable : 我有这段代码,但我不知道如何获取数据并将其放在一个变量中:

 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();
        }

and then in the DoWork I have the following : 然后在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();

So, I open the port but where to start getting the data ??? 所以,我打开了端口,但是从哪里开始获取数据呢? How to initialize the variable ? 如何初始化变量? The received message will be of the form 52 45 41 44 45 52 30 31 where 41 44 45 53 30 is the message in hexadecimal while 52 45 is the header and 31 CRC. 收到的消息的格式为52 45 41 44 45 52 30 31,其中41 44 45 53 30是十六进制的消息,而52 45是标头和31 CRC。

Please let me know how to do it. 请让我知道该怎么做。

Thank you .... 谢谢 ....

Working with serial port is just like working with files or sockets: 使用串行端口就像使用文件或套接字一样:

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
    }
}
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!
  }

}

Should do the trick! 应该做的把戏!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM