Page 65 - Ai Robogenius
P. 65
Here’s an explanation of the code you created:
int Distance = 0: Declares a variable to store the calculated distance from the ultrasonic
sensor, initially set to 0.
long readUltrasonicDistance(int triggerPin, int echoPin): A custom function that reads the
ultrasonic sensor's echo time to calculate the distance.
pinMode(triggerPin, OUTPUT): Sets the trigger pin to OUTPUT to send a pulse.
digitalWrite(triggerPin, LOW): Clears the trigger pin to ensure a clean start.
delayMicroseconds(2): Waits for 2 microseconds to ensure proper timing.
digitalWrite(triggerPin, HIGH): Sends a pulse to trigger the ultrasonic sensor.
delayMicroseconds(10): Waits for 10 microseconds before turning off the trigger.
digitalWrite(triggerPin, LOW): Turns off the trigger pin.
pinMode(echoPin, INPUT): Sets the echo pin to INPUT to listen for the reflected sound.
return pulseIn(echoPin, HIGH): Measures the time it takes for the sound to travel back and
returns the pulse duration in microseconds.
void setup(): A built-in function that runs once at the start to initialise the serial communication
and pin modes.
Serial.begin(9600): Starts serial communication at a baud rate of 9600 for debugging.
pinMode(4, OUTPUT): Sets pin 4 as an output to control the Piezo buzzer.
void loop(): Continuously runs after setup() to measure distance and control the Piezo buzzer.
Distance = 0.01723 * readUltrasonicDistance(2, 3): Calculates the distance using the time it
took for the pulse to travel and converts it to centimeters.
if (Distance < 60): If the distance is less than 60 cm, the object is too close.
Ÿ Serial.println("The object is too close!"): Prints a message to the serial monitor indicating
the object is too close.
Ÿ digitalWrite(4, HIGH): Turns ON the Piezo buzzer to alert the user.
Getting Started with Arduino in Tinkercad
63

