Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. /*
  2. Unity <---> Arduino (Serial Communication)
  3. - Send Multiple sensor values to Unity
  4. Tested Unity version 2019.1.6f
  5. For 2019 ITP CAMP Workshop "Make your own controller in Unity"
  6. By Hayeon Hwang. 2019.06.13
  7. */
  8.  
  9. const int ledPin = LED_BUILTIN;
  10. const int potPin = A0; // Analog input pin that the potentiometer is attached to
  11. const int windSensorPin = A1; // Analog input pin that the potentiometer is attached to
  12.  
  13. int sensorValue = 0;
  14. int lastSensorValue = 0;
  15.  
  16. int windValue = 0;
  17. int lastWindValue = 0;
  18.  
  19. int ledState = 0;
  20. int counter = 0; // ref - 'StateChangeDetection' example
  21.  
  22. void setup() {
  23. Serial.begin(9600); // ***important to match with Unity
  24. pinMode(LED_BUILTIN, OUTPUT);
  25. }
  26.  
  27. void loop() {
  28.  
  29. // ARDUINO ---> UNITY
  30. sensorValue = analogRead(potPin);
  31. windValue = analogRead(windSensorPin);
  32.  
  33. if (sensorValue != lastSensorValue || windValue != lastWindValue) {
  34. Serial.print(sensorValue);
  35. Serial.print(',');
  36. Serial.println(windValue);
  37. delay(20);
  38. }
  39.  
  40. lastSensorValue = sensorValue;
  41. lastWindValue = windValue;
  42.  
  43.  
  44. // UNITY ---> ARDUINO
  45. readDatafromUnity();
  46. }
  47.  
  48.  
  49. void readDatafromUnity() {
  50. ledState = recvSerial();
  51.  
  52. // Make a toggle switch style
  53. if (ledState == HIGH) {
  54. counter++;
  55. }
  56.  
  57. if (counter % 2 == 0) {
  58. digitalWrite(LED_BUILTIN, LOW);
  59. } else {
  60. digitalWrite(LED_BUILTIN, HIGH);
  61. }
  62.  
  63. }
  64.  
  65. int recvSerial() {
  66. if (Serial.available()) {
  67.  
  68. int serialData = Serial.read();
  69. switch (serialData) {
  70. case '1':
  71. return 1;
  72. break;
  73. case '0':
  74. return 0;
  75. break;
  76. default:
  77. return -1;
  78. }
  79. }
  80. delay(20);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement