You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
1.1 KiB
C++
45 lines
1.1 KiB
C++
const int US_sensorPin = 7;
|
|
const int relayPin = 10;
|
|
const int range = 8; //Range of detection from the sensor in cm
|
|
|
|
bool newAction;
|
|
|
|
|
|
void setup() {
|
|
Serial.begin (9600); //Allows serial output to serial monitor
|
|
pinMode(relayPin, OUTPUT);
|
|
digitalWrite(relayPin, LOW); // Default relay should be OFF!
|
|
}
|
|
|
|
void loop() {
|
|
long duration, cm;
|
|
pinMode(US_sensorPin, OUTPUT);
|
|
digitalWrite(US_sensorPin, LOW);
|
|
delayMicroseconds(2);
|
|
digitalWrite(US_sensorPin, HIGH);
|
|
delayMicroseconds(5);
|
|
digitalWrite(US_sensorPin, LOW);
|
|
pinMode(US_sensorPin, INPUT);
|
|
duration = pulseIn(US_sensorPin, HIGH);
|
|
|
|
cm = microsecondsToCentimeters(duration);
|
|
|
|
if (cm < range && cm > 1) {
|
|
|
|
if (newAction) {
|
|
digitalWrite(relayPin, HIGH); // Turn Ralay ON
|
|
delay(50); // Miliseconds which it waits before turn off again
|
|
digitalWrite(relayPin,LOW); // Trun Ralay OFF
|
|
newAction = false;
|
|
}
|
|
delay(1000); // Miliseconds which it waits before does any action again
|
|
|
|
} else {
|
|
newAction = true;
|
|
}
|
|
}
|
|
|
|
long microsecondsToCentimeters(long microseconds) {
|
|
return microseconds / 29 / 2;
|
|
}
|