#include <ESP32Servo.h>
// Define pins for the ultrasonic sensor
const int trigPin = 5;
const int echoPin = 18;
// Define pins for the LEDs
const int led1 = 13;
const int led2 = 12;
const int led3 = 14;
const int led4 = 27;
const int led5 = 26;
const int led6 = 25;
const int led7 = 33;
// Define pin for the servo motor
const int servoPin = 19;
// Variables
long duration;
int distance;
Servo servo;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
servo.attach(servoPin);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(led5, OUTPUT);
pinMode(led6, OUTPUT);
pinMode(led7, OUTPUT);
Serial.begin(9600);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin high for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Turn all LEDs off
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
digitalWrite(led5, LOW);
digitalWrite(led6, LOW);
digitalWrite(led7, LOW);
// Conditions to control LEDs and Servo
if (distance <= 50) {
digitalWrite(led7, HIGH);
servo.write(180);
} else if (distance <= 100) {
digitalWrite(led6, HIGH);
} else if (distance <= 150) {
digitalWrite(led5, HIGH);
servo.write(135);
} else if (distance <= 200) {
digitalWrite(led4, HIGH);
} else if (distance <= 250) {
digitalWrite(led3, HIGH);
servo.write(90);
} else if (distance <= 300) {
digitalWrite(led2, HIGH);
} else if (distance <= 350) {
digitalWrite(led1, HIGH);
servo.write(45);
}
delay(100); // Delay a little bit to improve simulation
}
//MUHAMMAD ASYWAD BIN A MAJID
//10DDT22F2023
//LAB EXERCISE 27/5/2024
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
servo1:GND
servo1:V+
servo1:PWM
ultrasonic1:VCC
ultrasonic1:TRIG
ultrasonic1:ECHO
ultrasonic1:GND
led1:A
led1:C
led2:A
led2:C
led3:A
led3:C
led4:A
led4:C
led5:A
led5:C
led6:A
led6:C
led7:A
led7:C