
The HC-SR04 ultrasonic sensor that we have in hackSpace, uses sonar to determine distance to an object like bats or dolphins do. Sensor uses non-contact range detection from 2cm to 4m, with a high accuracy up to 3mm. However, there are better ultrasonic sensors, which can be accurate even up to 1mm. In action is not affected by sunlight or black material like sharp rangefinders are (although acoustically soft materials like cloth can be difficult to detect). A good example of the sensor could be a car-park counter, which detects if the car has parked at the space.
Ultrasonic Sensor & LEDs |
Arduino Pins |
TRIG |
PIN D7 |
ECHO |
PIN D6 |
Red LED longer lead |
PIN D11 |
Yellow LED longer lead |
PIN D12 |
Green LED longer lead |
PIN D13 |
VCC |
5V |
GND |
GND |
This is a 4-pin sensor VCC and is connected to +5V. Then in the middle we have two signal pins TRIG and ECHO, one of them transmit the signal and the other one collects the data. The both can be connected to any digital pin on the Arduino. Lastly we have GND that will be connected to the negative side of our circuit (GND) on the Arduino.
#define trigPin 7 // Set output pin for the reciver#define echoPin 6 // Set input pin for the transmiter #define led 13 // Set output pin for the green LED#define led2 12 // Set output pin for the yellow LED#define led3 11 // Set output pin for the red LEDvoid setup() { Serial.begin (9600); // Begin Serial Monitor to see the distance values pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(led, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT);}void loop() {// This part of the sketch will be continually sending the signal to measure the distance long duration, distance; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/2) / 29.1; if (distance <= 60) { digitalWrite(led, HIGH);} // If the distance is less or equal to 60cm green LED will turn on else { digitalWrite(led,LOW); } // Otherwise off if (distance < 40) { digitalWrite(led2, HIGH);} // If the distance is less or equal to 40cm yellow LED will turn on else { digitalWrite(led2, LOW); } // Otherwise ‘OFF’ if (distance < 20) { digitalWrite(led3, HIGH);} // If the distance is less or equal to 20cm red LED will turn on else { Serial.print(distance); //Continually display the distance on Serial Monitor Serial.println(“ cm”); //Value given in centimetres } delay(1000); //Display the new value every second}
to borrow the proximity sensor, click here