Search code examples
c#stringloopsserial-portgrasshopper

New Line for each line and not for each character?


The data received from the serial port in the variable myReceivedLines (code below) displays new line for every character as opposed to line by line for every "sentence".

Is there a way to get "sentences" to appear on separate lines as opposed to character?

   //Fields
    string myReceivedLines;

    //subscriber method for the port.DataReceived Event
    private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        myReceivedLines = sp.ReadExisting();
    }


    protected override void SolveInstance(IGH_DataAccess DA)
    {

        List<string> gcode = new List<string>();
        DA.GetDataList(0, gcode);
        string selectedportname = default(string);
        DA.GetData(1, ref selectedportname);
        int selectedbaudrate = default(int);
        DA.GetData(2, ref selectedbaudrate);
        bool connecttodevice = default(bool);
        DA.GetData(3, ref connecttodevice);

        SerialPort port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One); //Create the serial port
        port.DtrEnable = true;   //enables the Data Terminal Ready (DTR) signal during serial communication (Handshaking)

        port.Open();             //Open the port

        if ((port.IsOpen) && (connecttodevice == true))
        {
            port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            DA.SetDataList(0, myReceivedLines);
        }

Solution

  • Assuming you input contains new line characters, use ReadLine to achieve this. Be mindful that it is a blocking call if you do not setup the proper ReadTimeout. I would set ReceivedBytesThreshold to what an average line length is expected to be and also store my lines in whatever collection fits my needs.

    //Fields
    List<string> myReceivedLines;
    
    //subscriber method for the port.DataReceived Event
    private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        while(sp.BytesToRead > 0)
        {
            try 
            {
                myReceivedLines.Add(sp.ReadLine());
            }
            catch(TimeOutException) 
            {
                break;
            }
        }
    }