#define trigger 3 // trigger attached to pin 3 #define echo 2 // echo attached to pin 2 int relayPin = 6; float time; // sets up time as a variable with decimals float dist1 = 0; // sets up distance as a variable with decimals void setup() { pinMode(trigger,OUTPUT); // sets up the trigger on ultrasonic pinMode(echo,INPUT); // sets up the echo on ultrasonic sensor as input pinMode(relayPin, OUTPUT); // sets up relay as an output } void loop() { digitalWrite(trigger,LOW); // make sure nothing is emitted on trigger yet delayMicroseconds(2); // delays for 2 microseconds digitalWrite(trigger,HIGH); // sends ultrasound wave on trigger delayMicroseconds(10); // sends for 10 microseconds digitalWrite(trigger,LOW); // ends wave delayMicroseconds(2); // delays for 2 microseconds time=pulseIn(echo,HIGH); // echo receives ultrasonic wave, time in microseconds dist1=time*340/20000; // calculates distance in cm delay(0.001); // delays for .001 microseconds if (dist1 < 50){ // if car is 50 cm or less from wall, relay activated digitalWrite(relayPin, HIGH); } else { digitalWrite(relayPin, LOW); // if car is not, relay deactivated or not activated at all } }