arduino-touchless-projects/touchless_power_switch/touchless_power_switch.ino

49 lines
1.2 KiB
Arduino
Raw Normal View History

2020-06-02 19:47:34 +02:00
const int US_sensorPin = 7;
const int relayPin = 10;
const int range = 8; //Range of detection from the sensor in cm
int valRelay = 0; // variable to store the read value
long relayAction;
bool newAction;
2020-06-02 19:47:34 +02:00
void setup() {
Serial.begin (9600); //Allows serial output to serial monitor
2020-06-02 19:47:34 +02:00
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, HIGH); // 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) {
2020-06-02 19:47:34 +02:00
if (newAction) {
valRelay = digitalRead(relayPin); // read the status of input pin
if (valRelay) {
relayAction = LOW;
} else {
relayAction = HIGH;
}
2020-06-02 19:47:34 +02:00
digitalWrite(relayPin, relayAction); // Switch Ralay ON or OFF
newAction = false;
2020-06-02 19:47:34 +02:00
}
delay(1000); // Miliseconds which it waits before does any action again
} else {
newAction = true;
2020-06-02 19:47:34 +02:00
}
}
2020-06-02 19:47:34 +02:00
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}