/*
1. Connect LED anode to digital pin (pin 13) on the Arduino board.
2. Connect LED catode to resiston (200-ohm) and the to the ground (GND) of the Arduino board.
3. Connect one leg of the push button to the digital pin (pin 2).
4. Connect the other leg of the push button to the ground (GND) of the Arduino board.
*/
// Define variables
int buttonPin = 2; // Digital pin where the button is connected.
int ledPin = 13; // Digital pin where the LED is connected.
#define TRIG_PIN 6 // ESP32 pin GIOP23 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 7 // ESP32 pin GIOP22 connected to Ultrasonic Sensor's ECHO pin
bool buttonState = false;
float duration_us, distance_cm;
void setup() {
pinMode(ledPin, OUTPUT); // LED pin as an output.
pinMode(buttonPin, INPUT); // Button pin as an input.
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Read the state of the button
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;
// Check if the button is pressed
if(distance_cm<30){
buttonState = true;
//digitalWrite(ledPin, HIGH);
}
else{
buttonState = false;
//digitalWrite(ledPin, LOW);
}
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH){
digitalWrite(ledPin, HIGH); // Turn LED on.
} else {
digitalWrite(ledPin, LOW); // Turn LED off.
}
}