【问题标题】:C# Serial Port Recieved Data EventC# 串口接收数据事件
【发布时间】:2018-04-17 10:03:40
【问题描述】:

我正在使用 Arduino 在 Unity 中开发智能家居系统。我正在使用端口和网络将数据从 pc 发送到 arduino 和 android。函数SerialPort.ReadLine() 让每个人都非常迟钝。它使应用程序以 1 fps 的速度移动。 代码如下:

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());

    }

它有什么问题?为什么没有调用函数DataReceivedHandler?

【问题讨论】:

  • 在另一个线程中使用SerialPort.ReadLine 阅读。

标签: c# android unity3d serial-port port


【解决方案1】:

您应该只注册一次事件处理程序,而不是在 Update() 期间注册多次。每帧调用一次更新,通常为每秒 30 次。

它慢的原因是现在每帧有很多调用从串行端口读取而不是一次,因此帧速率低。

如果您要使用硬件协议,请使用异步读取而不是阻塞读取。阻止读取有点违背了目的。异步读取也更适合帧速率。

【讨论】:

  • 谢谢。如何使用它异步?有功能吗?
  • @user193464 查看stackoverflow.com/a/32436104/585968 并使用ReadAsync 或BeginRead。上次我检查 Unity 不支持 async/await 所以你可能不得不使用 BeginRead
猜你喜欢
  • 2013-12-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多