翻墙看到的一个帖子。只要是代码,分享给大家
首先需要一个客户端就是Arduino的程序
void setup()
{
Serial.begin(9600);
}
void loop() {
// int val = 2;
int incomingByte=0;
//Sending value
// Serial.write(val);
// delay(1000);
//Receiving value
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
用arduino编译器新建一个程序,直接复制进去就可以了,简单解释一下:setup是启动函数,相当于unity的start函数,而loop函数相当于Update函数,setup函数中的
Serial.begin(9600);
我们将通过监听9600端口进行unity和arduino的通信
下面是unity的代码:
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Threading;
public class SerialPortTest : MonoBehaviour
{
//Setup parameters to connect to Arduino
public static SerialPort sp = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
public static string strIn;
public string message;
float ww=0;
// Use this for initialization
void Start ()
{
OpenConnection();
InvokeRepeating("kk",1,2);
}
void kk(){
sp.Write(ww.ToString());
ww+=0.01f;
}
void Update()
{
//Read incoming data
// strIn = sp.ReadLine();
// print(strIn);
//You can also send data like this
// sp.Write("2");
}
//Function connecting to Arduino
public void OpenConnection()
{
if (sp != null)
{
if (sp.IsOpen)
{
sp.Close();
message = "Closing port, because it was already open!";
}
else
{
sp.Open(); // opens the connection
sp.ReadTimeout = 50; // sets the timeout value before reporting error
message = "Port Opened!";
}
}
else
{
if (sp.IsOpen)
{
print("Port is already open");
}
else
{
print("Port == null");
}
}
}
void OnApplicationQuit()
{
sp.Close();
}
}
为了测试,我使用了
InvokeRepeating("kk",1,2);函数,就是说,每个2秒调用一次kk()函数,这里面每次调用豆浆想端口里面写一条数据,并且数据是递增的,所以灯会一闪一闪越来越亮。
还有就是,buildsetting里面,API Compatibility level要修改为。NET2.0,不然会找不到端口