gpt4 book ai didi

C#串口接收数据事件

转载 作者:行者123 更新时间:2023-11-30 00:16:46 26 4
gpt4 key购买 nike

我正在使用 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 没有被调用?

最佳答案

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

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

如果你打算使用硬件协议(protocol),那么使用异步读取而不是阻塞读取。阻塞读取有点违背了目的。异步读取对于帧速率也更好。

关于C#串口接收数据事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47116669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com