简体   繁体   中英

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 :

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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