在unity3d中使用C#语言串口通信接收数据经常缺失第一位且第一次按按钮总是超时
using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Text;
public class SerialPortReciever : MonoBehaviour
{
private SerialPort sp;
private Queue<string> queueDataPool;
private Thread tPort;
private Thread tPortDeal;
private string strOutPool = string.Empty;
string finalstring = string.Empty;
// Use this for initialization
void Start()
{
queueDataPool = new Queue<string>();
sp = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
if (!sp.IsOpen)
{
sp.Open();
}
tPort = new Thread(DealData);
tPort.Start();
tPortDeal = new Thread(ReceiveData);
tPortDeal.Start();
}
// Update is called once per frame
void Update()
{/*if(time>=0)
time -= Time.deltaTime;
if (time > 4) num = "5";
else if (time > 3) num = "4";
else if (time > 2) num = "3";
else if (time > 1) num = "2";
else num = "1"; */
if (!tPortDeal.IsAlive)
{
tPortDeal = new Thread(ReceiveData);
tPortDeal.Start();
}
if (!tPort.IsAlive)
{
tPort = new Thread(DealData);
tPort.Start();
}
}
private void ReceiveData()
{
try
{
Byte[] buf = new Byte[1];
string sbReadline2str = string.Empty;
if (sp.IsOpen) sp.Read(buf, 0, 1);
if (buf.Length == 0)
{
return;
}
if (buf != null)
{
for (int i = 0; i < buf.Length; i++)
{
sbReadline2str += buf[i].ToString("x2");
queueDataPool.Enqueue(sbReadline2str);
}
}
}
catch (Exception ex)
{
Debug.Log(ex);
}
}
private void DealData()
{
while (queueDataPool.Count != 0)
{
for (int i = 0; i < queueDataPool.Count; i++)
{
strOutPool+= queueDataPool.Dequeue();
if(strOutPool.Length==16)
{
Debug.Log(strOutPool);
strOutPool=string.Empty;
}
}
}
}
void OnGUI()
{
if(GUILayout.Button("write into sp",GUILayout.Height(50)))
{
string data = "11223";
SendSerialPortData(data);
}
}
private void SendSerialPortData(string data)
{
if(sp.IsOpen)
{
sp.WriteLine(data);
}
}
void OnApplicationQuit()
{
sp.Close();
}
}
我在unity上运行第一次按下按钮总是报超时
System.TimeoutException: The operation has timed-out.
at System.IO.Ports.WinSerialStream.Read (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
at System.IO.Ports.SerialPort.Read (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:Read (byte[],int,int)
at SerialPortReciever.ReceiveData () [0x0001d] in D:\u3dproject\u3dchuankou\Assets\SerialPortReciever.cs:62
之后几次按下按钮总是如下
313232330d0a0031
3232330d0a003132
32330d0a00313232
330d0a0031323233
0d0a31313232330d
0a00313232330d0a unity C# 串口通信
补充:.NET技术 , C#