Hey-ho,
ich sitze schon seid vielen Stunden daran: Von Unity aus Daten an Arduino zu schicken. Arduino erkennt auch, dass da was kommt, kann die Zeichen aber nicht unterscheiden.
Board: ESP32
Unity:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class Controller : MonoBehaviour {
bool b = true;
public static SerialPort sp = new SerialPort("COM4", 9600);
void Start() {
OpenConnection();
}
private void Update() {
Vector3 pos = this.transform.position;
print(pos);
if(pos.x>0.8 && pos.x < 1.3) {
print("1");
sp.Write("1");
}
else {
print("2");
sp.Write("2");
}
}
public SteamVR_Controller.Device controller
{
get
{
return SteamVR_Controller.Input((int)GetComponent<SteamVR_TrackedObject>().index);
}
}
public void OpenConnection() {
if (sp != null) {
if (sp.IsOpen) {
sp.Close();
print("COM-Port schliessen, weil er bereits geoeffnet war!");
} else {
sp.Open(); // COM-Port Verbindung öffnen
sp.ReadTimeout = 1;
print("COM-Port geoeffnet!");
}
} else {
if (sp.IsOpen)
print("COM-Port ist bereits geoeffnet!");
else
print("Port == null");
}
}
}
Arduino:
#include <ESP32_Servo.h>
int fromUnity = 0;
static const int servoPin = 23;
Servo myservo;
void setup() {
Serial.begin(9600);
myservo.attach(servoPin);
}
void loop() {
fromUnity = Serial.read();
if (Serial.available() > 0){
switch (fromUnity){
case 1:
myservo.write(180);
delay(500);
break;
case 2:
myservo.write(10);
delay(500);
break;
}
}
}
Hat jemand eine Idee, wie das funktionieren könnte?