Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Unity <---> Arduino (Serial Communication)
- - Send Multiple sensor values to Unity
- Tested Unity version 2019.1.6f
- For 2019 ITP CAMP Workshop "Make your own controller in Unity"
- By Hayeon Hwang. 2019.06.13
- */
- const int ledPin = LED_BUILTIN;
- const int potPin = A0; // Analog input pin that the potentiometer is attached to
- const int windSensorPin = A1; // Analog input pin that the potentiometer is attached to
- int sensorValue = 0;
- int lastSensorValue = 0;
- int windValue = 0;
- int lastWindValue = 0;
- int ledState = 0;
- int counter = 0; // ref - 'StateChangeDetection' example
- void setup() {
- Serial.begin(9600); // ***important to match with Unity
- pinMode(LED_BUILTIN, OUTPUT);
- }
- void loop() {
- // ARDUINO ---> UNITY
- sensorValue = analogRead(potPin);
- windValue = analogRead(windSensorPin);
- if (sensorValue != lastSensorValue || windValue != lastWindValue) {
- Serial.print(sensorValue);
- Serial.print(',');
- Serial.println(windValue);
- delay(20);
- }
- lastSensorValue = sensorValue;
- lastWindValue = windValue;
- // UNITY ---> ARDUINO
- readDatafromUnity();
- }
- void readDatafromUnity() {
- ledState = recvSerial();
- // Make a toggle switch style
- if (ledState == HIGH) {
- counter++;
- }
- if (counter % 2 == 0) {
- digitalWrite(LED_BUILTIN, LOW);
- } else {
- digitalWrite(LED_BUILTIN, HIGH);
- }
- }
- int recvSerial() {
- if (Serial.available()) {
- int serialData = Serial.read();
- switch (serialData) {
- case '1':
- return 1;
- break;
- case '0':
- return 0;
- break;
- default:
- return -1;
- }
- }
- delay(20);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement