Tutorial
Materials:
1. Arduino board
2. HC-SR04 Ultrasonic Sensor
3. LED
4. resistors
5. jumper wires
It was a little confusing for me, but I managed to complete the circuit and get it to work. I added the battery so that it'll give more power to the circuit. Watch the video below to see how mine functioned.
There is a part 2 to the experiment but I couldn't get it to work on my set up (it works on PCs though), you might want to try it! . Before that, you'll need to download the program: Processing. I'd problem with a few lines of the code in the part 2 experiment. When I open up the sketch from Processing, I'd to change the code to: myPort = new Serial(this, "/dev/cu.usbmodem1451", 9600); in order to get it connected. However, even when it's connected, I think there was something wrong with my set up and so I didn't successfully complete the second part of the experiment.
/*
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 10
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
}
void loop() {
long duration, distance;
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 < 4) { // 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);
}
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}