Arduino ultrasonic sensor: how to measure distances
With the Arduino, you can easily measure distances using an ultrasonic sensor. In this practical tip, we'll show you how.
Arduino ultrasonic sensor: how to measure distances
In order to measure distances, you need a breadboard with some jumper cables as well as an HC-SR04 ultrasonic measuring module in addition to the Arduino.
- Connect the "Trigger" pin of the module to Pin 13 and the "Echo" pin to Pin 12 of the Arduino. Also connect the HC-SR04 ultrasonic measuring module to 5V and ground.
- Define "trigger" as output and "echo" as input. You also need the long variables "duration" and "distance".
- First switch off the trigger (»digitalWrite (trigger, LOW);«) and wait 2 microseconds (»delayMicroseconds (2);«). Then switch the trigger on (»digitalWrite (trigger, HIGH);«), wait 10 microseconds (»delayMicroseconds (10);«) and switch it off again (»digitalWrite (trigger, LOW);«). Use this to calculate the duration (»duration = pulseIn (echo, HIGH);«) and finally the actual distance (»distance = (duration / 2) / 29.1;«).
- With this variable you can continue to calculate as you wish.
Arduino: Sample code for the ultrasonic sensor
In the picture you see the code that you can use if you want to use the HC-SR04 professionally. You are also welcome to copy the code here:
- #include #define trigger 13 #define echo 12 #define led_1 11 #define led_2 10 int value_tone; long duration, distance; LiquidCrystal lcd (7, 6, 5, 4, 3, 2); void setup () {Serial.begin (9600); pinMode (trigger, OUTPUT); // Pin of HC-SR04 pinMode (echo, INPUT); // Pin of HC-SR04 pinMode (led_1, OUTPUT); // LED pinMode (led_2, OUTPUT); // LED pinMode (9, OUTPUT); // buzzer lcd.begin (16, 2); } void loop () {digitalWrite (trigger, LOW); delayMicroseconds (2); digitalWrite (trigger, HIGH); delayMicroseconds (10); digitalWrite (trigger, LOW); duration = pulseIn (echo, HIGH); distance = (duration / 2) / 29.1; if (distance = 200 || distance <= 0) {Serial.println ("Out of range"); } else {Serial.print (distance); Serial.println ("cm"); } lcd.clear (); lcd.setCursor (1, 0); lcd.print ("Distance:"); lcd.print (distance); lcd.print ("cm"); if (distance 0) {value_tone = map (distance, 0, 200, 0, 5000); tone (9, value_tone); } else {} delay (500); }
In the next practical tip, we will show you how to set up a GSM module on the Arduino.