Ultrasonic sensor, Arduino and Unity

Today I did a quick test to see how well I could get an Arduino to talk to Unity. The video is the result of the experiment.

The video cannot be shown at the moment. Please try again later.

aurduinoTest – Zip File of my Unity Project

The Ultrasonic code has largely been taken from http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/ and the Unity example was largely taken from http://arduino.cc/forum/index.php?action=printpage;topic=73425.0 I just stuck the two together.

My altered code for the Arduino is below.

/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
Red POS to Arduino pin 11
Green POS to Arduino pin 10
560 ohm resistor to both LED NEG and GRD power rail
More info at: http://goo.gl/kJ8Gl
Original code improvements to the Ping sketch sourced from Trollmaker.com
Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
*/

#define trigPin 13
#define echoPin 12
#define led 11
#define led2 9

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
}

void loop() {
int distance;
long duration;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
// delayMicroseconds(1000); – Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 30.0) { // This is where the LED On/Off happens
digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off
digitalWrite(led2,LOW);
}
else {
digitalWrite(led,LOW);
digitalWrite(led2,HIGH);
}
int val = 2;

// Serial.println(distance);
if (distance >= 150 || distance <= 0){
Serial.write(150);
}else{
Serial.write(distance);
}
delay(200);
}

This entry was posted in Arduino, Unity. Bookmark the permalink.