anthraxa
anthraxa

Reputation: 35

reading values from serialport

i am trying to make a program in unity that reads values from serialport and my program freezes beacuse of serial.ReadLine() and if i change it to serial.ReadByte() it reads bytes, and now only option is i want to know how to convert these bytes to string. My code is as following:

using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Threading;
using UnityEngine.UI;

public class leti3 : MonoBehaviour {

    public SerialPort serial = new SerialPort("COM5", 115200);
    public GameObject personaje;

    // Use this for initialization
    void Start()
    {
        serial.Open();
        //serial.ReadTimeout = 1;
    }

    // Update is called once per frame
    void Update()
    {
        if (serial.IsOpen)
        {
            try
            {
            print(serial.ReadByte()); //reads bytes
            }
            catch (System.Exception)
            {
                Debug.Log("Error!");
            }
        }
    }
}

Upvotes: 1

Views: 2344

Answers (1)

Matt Burland
Matt Burland

Reputation: 45155

ReadLine is blocking. It will block execution until it reaches the end of a line. You want to instead use the DataRecieved event.

In the handler you can use ReadExisting to get the string currently in the buffer. You will have to manage that the string may only be part of the message you received.

Or you can read bytes into an array and then use Encoding.GetString with the appropriate encoding.

If you can't use DataRecieved and have to use the blocking ReadByte, then you ought to still be able to do something like this in your update:

var toRead = serial.BytesToRead();    // make sure there actually are bytes to read first
for (int i=0; i < toRead; i++)
{
    // where msgArray is an array for storing the incoming bytes
    // and idx is the current idx in that array
    msgArray[idx] = serial.ReadByte();  // this should be quick, because it's already 
                                        // in the buffer
    if (msgArray[idx] = newLineChar)    // whatever newLineChar you are using
    {
        // Read your string
        var msg = Encoding.ASCII.GetString(msgArray,0,idx);   // or whatever encoding you 
                                                              // are using
        idx = 0;
    }
    else
    {
       idx++;
    }
}

Upvotes: 4

Related Questions