Ultrasonic Distance Sensor
ultrasonic_distance_sensor.ino
/*
Project: Smart Home
Circuit: Arduino Ek R4
Project Description:
This is the code to detect distance using an ultrasonic sensor.
Author: STEMVentor Educonsulting
This code is copyrighted. Please do not reuse or share for any purpose other than for learning with subscribed STEMVentor programs.
This code is for educational purposes only and is not for production use.
*/
// LIBRARIES
#include <Wire.h> //used for communicating with I2C devices
//https://www.arduino.cc/reference/en/libraries/liquidcrystal-i2c/
// Install the LiquidCrystal I2C by Frank de Brabander from the IDE library manager.
#include <LiquidCrystal_I2C.h>
// PIN DEFINITIONS
#define TRIGGER_PIN 13
#define ECHO_PIN 12
// GLOBAL CONSTANTS
// Conversion value from speed of sound to distance in cm.
const float sound_speed = 0.034;
// GLOBAL VARIABLES
// INITIALIZE OBJECTS
/* Libraries usually follow an object-oriented approach that requires
* an instance of the class to call its methods.
*/
/* LOCAL FUNCTIONS */
void ultrasonicSensorSetup() // function to LCD setup
{
//Define the pinmode
pinMode(TRIGGER_PIN, OUTPUT); // Sets the trigger pin as Output
pinMode(ECHO_PIN, INPUT); // Sets the echo pin as Input
// This delay is to allow init to complete.
delay(1000);
Serial.println("The Ultrasonic sensor is ready!");
}
// Read sensor values
uint8_t readUltrasonicSensorValue() //read HCSR-04 sensor value
{
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Reads the echo pin and returns the ultrasonic sensor wave travel time in microseconds.
long pulse_duration = pulseIn(ECHO_PIN, HIGH);
Serial.println(pulse_duration);
// Calculate the distance in cm and display on the LCD
long distance = (pulse_duration/2) * sound_speed;
if(distance <= 40){
printToLCDByRow(3, "Distance: " + String(distance) + " cm", false);
}else{
printToLCDByRow(3, "Distance: Nothing in range", false);
}
// Light up the RGB LED as a visual indicator
if(distance <= 20){
powerRGBLED(255, 0, 0); // Red
}else if(distance > 20 && distance <= 40){
powerRGBLED(5, 215, 255); // Orange
}else if(distance > 40){
switchOffRGBLED(); // Switch off
}
return distance;
}