|
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", 115200, 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=float.Parse(ss[0]);
y=float.Parse(ss[1]);
z=float.Parse(ss[2]);
}
}
}
}
}
catch (Exception ex)
{
Debug.Log(ex);
}
}
private void SendSerialPortData(string data)
{
if(sp.IsOpen)
{
sp.WriteLine(data);
}
}
void OnApplicationQuit()
{
sp.Close();
}
}
这是我在网上找的一个关于串口通信代码修改后的,都是接受ARDUNIO板子发送的数据(一个手柄的XYZ的模拟电压值),我要就收的是由感叹号开头,#隔开的三个数据一组的模拟电压值,每个值都在0~1023之间。为什么我在UNITY运行的时候总在控制台总是显示0&&0&&0 |
|