/* The circuit: * +V connection of the HC-SR04 attached to +5V * GND connection of the HC-SR04 attached to ground * Trig connection of the HC-SR04 attached to digital pin 7 * Echo connection of the HC-SR04 attached to digital pin 8 * Relay + to digital pin 2 * Relay minus to GND * Motors 1st terminal to relay's normally closed pin. * Motors 2nd terminal to relay's common pin. */ // this constant won't change. It's the pin number // of the sensor's output: const int Trig = 7; const int Echo = 8; const int Echo = 4; void setup() { // initialize serial communication: Serial.begin(9600); } void loop() { // establish variables for duration of the ping, // and the distance result in inches and centimeters: long duration, inches, cm; // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: pinMode(Trig, OUTPUT); digitalWrite(Trig, LOW); delayMicroseconds(2); digitalWrite(Trig, HIGH); delayMicroseconds(5); digitalWrite(Trig, LOW); pinMode(Echo, INPUT); duration = pulseIn(Echo, HIGH); // convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); if(cm<25){ digitalWrite(relay,HIGH); delay(1000) } else{ digitalWrite(relay,LOW); } } long microsecondsToInches(long microseconds) { return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { return microseconds / 29 / 2; }