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 com : MonoBehaviour
{
public GameObject target;
private SerialPort sp;
private Thread recvThread;
float x,y,z;
// Use this for initialization
void Start()
{
//Debug.Log("start");
sp = new SerialPort("COM6", 9600, Parity.None, 8, StopBits.One);
if (!sp.IsOpen)
{
sp.Open();
}
recvThread = new Thread(ReceiveData);
recvThread.Start();
}
// Update is called once per frame
void Update()
{
Debug.Log(x+"&&"+y+"&&"+z);
//target.transform.eulerAngles=new Vector3(x,y,z);
}
private void ReceiveData()
{
char[] spil="#".ToCharArray();
char[] sbuf = new char[1024];
try
{
Byte[] buf = new Byte[1];
string sbReadline2str = string.Empty;
if (sp.IsOpen) sp.Read(buf, 0, 1);
if (buf.Length == 0)
{
return;
}
else if(buf[0]==33){
int i=0;
while(true){
sp.Read(buf, 0, 1);
if(buf[0]!=33)
{
sbuf[0]=(char)buf[0];
i++;
}else{
String s=new String(sbuf,0,i);
String []ss=s.Split(spil);
i=0;
if(ss.Length==3)
{
x=int.Parse(ss[0]);
y=int.Parse(ss[1]);
z=int.Parse(ss[2]);
}
}
}
}
}
catch (Exception ex)
{
Debug.Log(ex);
}
}
private void SendSerialPortData(string data)
{
if(sp.IsOpen)
{
sp.WriteLine(data);
}
}
void OnApplicationQuit()
{
sp.Close();
}
}
这个代码运行时没有问题,但是为什么接收这样“!123#342#423!234#172#1021#后边还有”的数据时一直显示为“0&&0&&0 ”? 为啥会这样,是代码不对么?
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 com : MonoBehaviour
{
public GameObject target;
private SerialPort sp;
private Thread recvThread;
float x,y,z;
// Use this for initialization
void Start()
{
//Debug.Log("start");
sp = new SerialPort("COM6", 9600, Parity.None, 8, StopBits.One);
if (!sp.IsOpen)
{
sp.Open();
}
recvThread = new Thread(ReceiveData);
recvThread.Start();
}
// Update is called once per frame
void Update()
{
Debug.Log(x+"&&"+y+"&&"+z);
//target.transform.eulerAngles=new Vector3(x,y,z);
}
private void ReceiveData()
{
char[] spil="#".ToCharArray();
char[] sbuf = new char[1024];
try
{
Byte[] buf = new Byte[1];
string sbReadline2str = string.Empty;
if (sp.IsOpen) sp.Read(buf, 0, 1);
if (buf.Length == 0)
{
return;
}
else if(buf[0]==33){
int i=0;
while(true){
sp.Read(buf, 0, 1);
if(buf[0]!=33)
{
sbuf[0]=(char)buf[0];
i++;
}else{
String s=new String(sbuf,0,i);
String []ss=s.Split(spil);
i=0;
if(ss.Length==3)
{
x=int.Parse(ss[0]);
y=int.Parse(ss[1]);
z=int.Parse(ss[2]);
}
}
}
}
}
catch (Exception ex)
{
Debug.Log(ex);
}
}
private void SendSerialPortData(string data)
{
if(sp.IsOpen)
{
sp.WriteLine(data);
}
}
void OnApplicationQuit()
{
sp.Close();
}
}
这个代码运行时没有问题,但是为什么接收这样“!123#342#423!234#172#1021#后边还有”的数据时一直显示为“0&&0&&0 ”? 为啥会这样,是代码不对么?