0

I am working on a smarthome system in Unity using Arduino. I am working woth ports and network to send the data from pc to arduino and android. The function SerialPort.ReadLine() make everythong very laggy. It makes the app move with 1 fps. Here is the code:

using UnityEngine;
using System;
using System.IO.Ports;

public class Motorase : MonoBehaviour {

    public SerialPort sp;

    bool deschis1, deschis2, deschis3, deschis4;

    public int temp, umid, gazv;

    // Use this for initialization
    void Start () {

        deschis1 = false;
        deschis2 = false;
        deschis3 = false;
        deschis4 = false;


        foreach (string port in SerialPort.GetPortNames())
            sp = new SerialPort(port, 9600);

        if(!sp.IsOpen)
            sp.Open();

        sp.DtrEnable = true;    // Data-terminal-ready
        sp.RtsEnable = true;    // Request-to-send
    }

    void Update()
    {
        sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
    }

    void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        Debug.Log("Da");
        temp = Convert.ToInt32(sp.ReadLine());
        umid = Convert.ToInt32(sp.ReadLine());
        gazv = Convert.ToInt32(sp.ReadLine());
        int apro = Convert.ToInt32(sp.ReadLine());

    }

What is wrong with it? Why the function DataReceivedHandler is not called?

user193464
  • 380
  • 1
  • 6
  • 25

1 Answers1

1

You should only register the event handler once, not many times during Update(). Update is called once per frame which typically is 30 times per second.

The reason it is slow is that now you have many calls per frame to read from the serial port instead of just once, hence the low frame rate.

If you are going to use hardware protocol, then use asynchronous reads rather than blocking reads. Blocking reads kinda defeats the purpose. Asynchronous reads is better for frame rates too.

  • Thank you. How to use it async? Is there a function? – user193464 Nov 05 '17 at 00:08
  • @user193464 Check out https://stackoverflow.com/a/32436104/585968 and use `ReadAsync` or `BeginRead`. Last time I checked Unity didn't support `async/await` so you might have to use `BeginRead` –  Nov 05 '17 at 03:38