We can use an ultrasonic distance sensor and an Arduino board to build a distance sensing device. I have built one set to a 2m distance for use as a social distancing meter but you can set it to whatever distance you wish by altering the correct part of the program.
For this project you will need:
1 or more HC-SR04 Ultrasonic sensor modules.LEDs of your choice and associated fixed resistors (I have used 220R).1 (or more if you add more than one sensor) prototype board (breadboard) and connection wires.
The circuit shown in Fig 1 uses a single distance sensor but you can add more sensors in parallel to increase the efficiency of the system. The limitation of using one sensor is that the angle range of the sensor is quite low which means that if you approach it from the side or at a strange angle, the sensor may not trigger.
Set up your prototype board as seen in Fig 1 and use the program shown below to get it to work. Look at the explanations at the side of the code for hints:
// constants won't changeconst int TRIG_PIN = 6; // Arduino pin connected to Ultrasonic Sensor's TRIG pinconst int ECHO_PIN = 7; // Arduino pin connected to Ultrasonic Sensor's ECHO pinconst int LED_PIN = 3; // Arduino pin connected to LED's pinconst int LED_PIN1 = 2; // Arduino pin connected to LED's pinconst int DISTANCE_THRESHOLD = 200; // This sets the distance for sensing - 200cm or 2m
// variables will change:float duration_us, distance_cm;
void setup() { Serial.begin (9600); // initialize serial port - sets the serial port so that you can see the distance on your screen pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode pinMode(ECHO_PIN, INPUT); // set arduino pin to input mode pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode LED 1 pinMode(LED_PIN1, OUTPUT); // set arduino pin to output mode LED 2}
void loop() { // generate 10-microsecond pulse to TRIG pin digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW);
// measure duration of pulse from ECHO pin duration_us = pulseIn(ECHO_PIN, HIGH); // calculate the distance distance_cm = 0.017 * duration_us;
if(distance_cm < DISTANCE_THRESHOLD) digitalWrite(LED_PIN, HIGH); // turn on Red LED else digitalWrite(LED_PIN, LOW); // turn off Red LED
if(distance_cm > DISTANCE_THRESHOLD) digitalWrite(LED_PIN1, HIGH); // turn on Green LED else digitalWrite(LED_PIN1, LOW); // turn off Green LED
// print the value to Serial Monitor Serial.print("distance: "); Serial.print(distance_cm); Serial.println(" cm");
delay(500);}
This is just an example program - I have tweaked it around to do different things as I've needed. For example, you can set more LED's or different outputs quite easily or change the parameters and see what it does!
Remember the basics of Arduino use and set your output port and type of Arduino board before programming.