Beslinda N.
Beslinda N.

Reputation: 5326

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 ....

Upvotes: 0

Views: 974

Answers (2)

jbutler483
jbutler483

Reputation: 24559

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!

Upvotes: 1

rufanov
rufanov

Reputation: 3276

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

Upvotes: 1

Related Questions