#include <NewPing.h>
#define relayPin 3
#define TRIGGER_PIN 5 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 4 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
int distance;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(115200);
pinMode(relayPin, OUTPUT);
// put your setup code here, to run once:
}
void loop() {
readDist();
Serial.println(distance);// put your main code here, to run repeatedly:
if (distance < 50){
digitalWrite(relayPin, HIGH);
}else{
digitalWrite(relayPin, LOW);
}
}
void readDist(){
delay(50);
distance = sonar.ping_cm();
if(distance == 0){
distance = 200;
}
}