我正在尝试制作一个从串行端口读取值的统一程序,我的程序由于 serial.ReadLine() 而卡住,如果我将其更改为 serial.ReadByte() 它读取字节,现在唯一的选择是我想知道如何将这些字节转换为字符串。 我的代码如下:
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Threading;
using UnityEngine.UI;
public class leti3 : MonoBehaviour {
public SerialPort serial = new SerialPort("COM5", 115200);
public GameObject personaje;
// Use this for initialization
void Start()
{
serial.Open();
//serial.ReadTimeout = 1;
}
// Update is called once per frame
void Update()
{
if (serial.IsOpen)
{
try
{
print(serial.ReadByte()); //reads bytes
}
catch (System.Exception)
{
Debug.Log("Error!");
}
}
}
}
请您参考如下方法:
ReadLine 正在阻塞。它将阻止执行,直到它到达一行的末尾。你想改用 DataRecieved事件。
在处理程序中,您可以使用 ReadExisting获取当前在缓冲区中的字符串。您将不得不管理该字符串可能只是您收到的消息的一部分。
或者您可以将字节读入数组,然后使用 Encoding.GetString使用适当的编码。
如果您不能使用 DataRecieved 并且必须使用阻塞 ReadByte,那么您仍然应该能够在更新中执行类似这样的操作:
var toRead = serial.BytesToRead(); // make sure there actually are bytes to read first
for (int i=0; i < toRead; i++)
{
// where msgArray is an array for storing the incoming bytes
// and idx is the current idx in that array
msgArray[idx] = serial.ReadByte(); // this should be quick, because it's already
// in the buffer
if (msgArray[idx] = newLineChar) // whatever newLineChar you are using
{
// Read your string
var msg = Encoding.ASCII.GetString(msgArray,0,idx); // or whatever encoding you
// are using
idx = 0;
}
else
{
idx++;
}
}
