Input Devices¶
Measuring HC-SR04 Ultrasonic sensor (infos from Components 101)¶
This sensor is a very popular sensor used in many applications where measuring distance or sensing objects are required.
The module has two eyes like projects in the front which forms the Ultrasonic transmitter and Receiver.
It is a 4 pin module, whose pin names are Vcc, Trigger, Echo and Ground respectively.
Applications¶
- Used to avoid and detect obstacles with robots like biped robot, obstacle avoider robot, path finding robot etc.
- Used to measure the distance within a wide range of 2cm to 400cm
- Can be used to map the objects surrounding the sensor by rotating it
- Depth of certain places like wells, pits etc can be measured since the waves can penetrate through water
Test with the Ultrasonic Sensor (from Project Hub Arduino)¶
/*
* HC-SR04 example sketch
*
* https://create.arduino.cc/projecthub/Isaac100/getting-started-with-the-hc-sr04-ultrasonic-sensor-036380
*
* by Isaac100
*/
//define the pins that Trig and Echo are connected to
const int trigPin = 2;
const int echoPin = 1;
//declare 2 floats, duration and distance, which will hold the length of the sound wave and how far away the object is
float duration, distance;
void setup() {
pinMode(trigPin, OUTPUT); //declare the Trig pin as an output
pinMode(echoPin, INPUT); //declare the Echo pin as an input
Serial.begin(9600); //start Serial communications
}
void loop() {
digitalWrite(trigPin, LOW); //set the trigPin low for 2 microseconds just to make sure
delayMicroseconds(2); //that the pin in low first
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration*.0343)/2;
Serial.print("Pulse: ");
Serial.print(duration);
Serial.println("micro seconds");
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
Serial.println(" ");
delay(1000);
}