#define TRIG_PIN 5
#define ECHO_PIN 4
#define DISTANCE_THRESHOLD 30
#define RELAY_CONTROL_PIN 6
#define POTENT_PIN 9
volatile bool fired = false;
volatile bool inter = false;
volatile int duration = 0;
volatile bool newDistance = false;
volatile bool relayOn = true;
volatile int threshold = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(RELAY_CONTROL_PIN, OUTPUT);
pinMode(POTENT_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(ECHO_PIN), distanceInterrupt, CHANGE);
threshold = analogRead(POTENT_PIN) / 40;
Serial.println("Threshold: ");
Serial.println(threshold);
enableRelay();
}
void loop() {
// Start a new measurement:
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
delay(250);
}
void distanceInterrupt() {
if (digitalRead(ECHO_PIN) == HIGH) {
duration = micros();
}
else {
duration = micros() - duration;
newDistance = true;
}
if (newDistance == true) {
int distance = duration/58;
Serial.println("\n\n Distance in interrupt: ");
Serial.println(distance);
newDistance = false;
if (distance < threshold && relayOn == true) {
disableRelay();
relayOn = false;
}
else if (distance > threshold && relayOn == false) {
enableRelay();
relayOn = true;
}
}
}
void enableRelay() {
digitalWrite(RELAY_CONTROL_PIN, HIGH);
Serial.println("Relay Enabled");
}
void disableRelay() {
digitalWrite(RELAY_CONTROL_PIN, LOW);
Serial.println("Relay Disabled");
}Loading
esp32-s3-devkitc-1
esp32-s3-devkitc-1