Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question SerialPort.ReadLine() not working properly

Discussion in 'Editor & General Support' started by Melveron, Jun 22, 2020.

  1. Melveron

    Melveron

    Joined:
    Feb 2, 2020
    Posts:
    2
    I recently started programming Arduino and wanted to send the Arduinos data to Unity.
    However, everytime I try to use SerialPort.ReadLine() it doesn't seem to read the whole Serial Line and instead ignores the first numbers.

    This happens most of the time but there is a chance every bit of data is actually recognized by Unity.

    Here is my Arduino-code:

    float a = 0;
    float b = 0;
    float c = 0;

    void setup() {
    // put your setup code here, to run once:
    Serial.begin(38400);
    a = 0;
    b = 0;
    c = 0;
    }

    void loop() {
    // put your main code here, to run repeatedly:
    Serial.print(a);
    Serial.print(",");
    Serial.print(b);
    Serial.print(",");
    Serial.println(c);

    a += 0.1;
    b += 0.2;
    c += 0.3;

    delay(2000);
    }

    And that is my Unity Script:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System.IO.Ports;
    using System.Text.RegularExpressions;

    public class MPU_To_Unity : MonoBehaviour
    {
    SerialPort sp = new SerialPort("COM3", 38400);
    public string dataInput;
    public string[] dataInputSubstrings = new string[3];
    float roll, pitch, yaw;

    // Start is called before the first frame update
    void Start()
    {
    sp.Open();
    sp.ReadTimeout = 1;
    }

    // Update is called once per frame
    void Update()
    {
    try
    {
    dataInput = sp.ReadLine();
    sp.BaseStream.Flush();
    }
    catch (System.Exception)
    {

    }
    }
    }

    I already tried using different baud-rates, experimented with the delay and tried some example projects but none worked for me.
    Does anyone have an idea how I can fix this?

    Thanks everyone in advance :)
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,933
    What exactly is the data that your C# code is receiving?
     
  3. Melveron

    Melveron

    Joined:
    Feb 2, 2020
    Posts:
    2
    This are the first few ticks:

    .20,0.30
    0.20,0.40,0.60 // However at the second try I got 0 as a string
    60, 0.90
    .40,0.80,1.20
    50

    I also noticed that after pausing and continuing the scene preview the values are pretty much always the complete string. (F.e. 3.00,6.00,9.00)