Arduino向Unity传数据
Arduino程序int x=0;int y=0;
int b=0;
bool l=false;//按钮状态
void setup() {
pinMode(2, INPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
}
// the loop function runs over and over again forever
void loop() {
l=digitalRead(2);
if(l){digitalWrite(13,LOW);b=0;}
else{digitalWrite(13,HIGH);b=1;}
x=analogRead(1);
y=analogRead(2);
Serial.print("*");
Serial.print(x);
Serial.print(",");
Serial.print(y);
Serial.print(",");
Serial.print(b);
Serial.print("#");
delay(2);
}
Unity C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System.IO;
using System.Threading;
using System.Text;
using System;
public class arduino : MonoBehaviour {
private SerialPort port;
private Thread t;
bool TheadEnd = false;
bool KeepReceived = true;
public int sensorX = 0;
public int sensorY = 0;
public float steerInput = 0;
public float forwardInput = 0;
public bool isopen = false;
public int isjump = 0;
public string portstring = "COM4";
public char CharStart = '*';
public char CharEnd = '#';
void Start () {
port = new SerialPort(portstring, 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
port.ReadTimeout = 100000;
port.Open();
t = new Thread(new ThreadStart(Cal));
t.Start();
}
// Update is called once per frame
void Update () {
}
void FixedUpdate() {
steerInput = sensorX / 512.0f - 1.0f;
forwardInput = 1.0f-sensorY / 512.0f;
isopen = port.IsOpen;
}
public void DataResolve(string Data) {
string[] sArray = Data.Split(',');
sensorX = int.Parse(sArray);
sensorY = int.Parse(sArray);
isjump = int.Parse(sArray);
}
public int CharToASCII(char a) {
int b = 0;
b = Convert.ToInt32(a);
return b;
}
public string ASCIIToChar(int a) {
string b = "";
b = Convert.ToChar(a).ToString();
return b;
}
void OnDestroy() { port.Close(); }
void Cal()
{
TheadEnd = false;
if (port.IsOpen)
{
List<byte> _byteData = new List<byte>();
bool start = false;
while (KeepReceived) {
try {
byte[] readBuffer = new byte;
int count = port.Read(readBuffer, 0, port.ReadBufferSize);
for (int i = 0; i < count; i++)
{
if (start) _byteData.Add(readBuffer);
if (readBuffer == CharToASCII(CharStart)) { start = true; }
else if (readBuffer == CharToASCII(CharEnd)) {
if (start)
{
string temp = Encoding.ASCII.GetString(_byteData.ToArray(), 0, _byteData.Count - 1);
_byteData.Clear();
DataResolve(temp);
temp = "";
start = false;
}
}
}
}
catch (TimeoutException) { }
}
}
TheadEnd = true;
}
}
此版本不易死机。 你好,想问一下有Arduino与unity交互,通讯的教程网站或资料嘛 Dreams 发表于 2019-11-9 21:30
你好,想问一下有Arduino与unity交互,通讯的教程网站或资料嘛
ardunio 和 unity交互实际上就是互传字符串,可以分别学下字符串处理的例子。使用的时候要考虑ardunio的速度限制,字符串不能太长。
页:
[1]