Unityからシリアル通信でArduino側に繋がったサーボを制御(角度送るだけだけど)してみました。とりあえず動作確認レベルなのでひどいコードです。
デフォルトだとSystem.IO.Portで怒られるので下記を参考に.Net 2.0にビルド設定を変えておいてください。
error CS0234: The type or namespace name `Ports' does not exist in the namespace `System.IO'
Unity
using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class SerialReceiver : MonoBehaviour {
private static SerialPort sp = new SerialPort("COM3", 9600);
void Start () {
OpenConnection();
}
void Update () {
if(Input.GetKeyDown(KeyCode.A)) {
Debug.Log("Send message " + Input.mousePosition.x);
sp.Write(Input.mousePosition.x.ToString() + "\0");
}
}
void OnApplicationQuit()
{
sp.Close();
}
void OpenConnection() {
if(sp != null) {
if(sp.IsOpen) {
sp.Close();
Debug.LogError("Failed to open Serial Port, already open!");
} else {
sp.Open();
sp.ReadTimeout = 50;
Debug.Log("Open Serial port");
}
}
}
}
#include <Servo.h>
Servo servo;
char buffer[5];
void setup(){
Serial.begin(9600);
servo.attach(3);
}
void loop(){
int i = 0;
while(1) {
if(Serial.available()) {
buffer[i] = Serial.read();
if(buffer[i] == '\0') {
servo.write(atoi(buffer));
break;
}
i++;
}
}
}