Professional Documents
Culture Documents
Worksheet 4
• If the distance X< 90 cm, then turn on the buzzer and all the lights will remain OFF.
Coding:
#define trig 3 // defines pins numbers By Marcos
#define echo 2
#define buzzerPin 4 // defines Buzzer & LED Pins numbers By Marcos
#define yellowPin 5 #define greenPin 6
long duration; // defines variables
int distance;
void setup(){
pinMode(trig, OUTPUT); // Sets the trigPin as an Output
pinMode(echo, INPUT); // Sets the echoPin as an Input
pinMode(greenPin, OUTPUT); // Sets the greenLightPin as an Output
pinMode(yellowPin, OUTPUT); // Sets the yellowLightPin as an Output
pinMode(buzzerPin, OUTPUT); // Sets the buzzerPin as an Output
Serial.begin(9600); // Starts the serial communication
} void
loop(){
digitalWrite(trig, LOW); // Clears the trigPin
delayMicroseconds(2);
digitalWrite(trig, HIGH); // Sets the trigPin on HIGH state for 10 microseconds
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
distance = duration * 0.034 / 2; // Calculating the distance
Serial.print("Distance: ");
Serial.println(distance);
if (distance > 250) { // Cases based on distance
digitalWrite(greenPin, HIGH);
digitalWrite(yellowPin,
LOW); digitalWrite(buzzerPin,
LOW);
} else if (distance > 90 && distance <= 250) {
digitalWrite(greenPin, LOW); digitalWrite(yellowPin,
HIGH); digitalWrite(buzzerPin, LOW);
} else if (distance <= 90) { digitalWrite(greenPin,
LOW); digitalWrite(yellowPin, LOW);
digitalWrite(buzzerPin, HIGH);
}
delay(500); // Add a delay for stability
}
Learning outcomes (What I have learnt):
1. Able to understand and explain Ultrasonic Sensor and its working.
2. Able to understand and explain how to connect Arduino, Ultrasonic Sensor, and use of it.
3. Able to understand and explain the concept of audible and inaudible range, pulseIn function and how
does sensor calculates the distance between object and it.