Last active
April 2, 2016 20:41
-
-
Save mandyRae/b1e8136db87507d8fe6e1cbdbbec8757 to your computer and use it in GitHub Desktop.
ultrasonic sensor and power relay to control desk lighting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Using an Arduino with a Power Relay | |
Parts used: | |
--ultrasonic sensor | |
--desk lamp | |
--Arduino Uno | |
--120v relay | |
This sketch uses an ultrasonic sensor to detect whether | |
a person in near or sitting at a desk, and sends a | |
signal to a power relay to turn desk lighting on or off. | |
*/ | |
#include <NewPing.h> | |
const int LIGHT = 10; | |
const int TRIGGER = 12; | |
const int ECHO = 11; | |
NewPing sonar(TRIGGER, ECHO); | |
void setup(){ | |
pinMode(LIGHT, OUTPUT); | |
} | |
/* The main loop iterates every 2.5 seconds. */ | |
void loop(){ | |
/*In order to get a accurate measure of wether | |
someone is near, we read the ultrasonic sensor | |
30 times and take the average. That way, if the | |
ultrasonic sensor reads sporadically as it | |
occasionaly does, those values will be averaged out. | |
This takes 0.05 * 30 = 1.5 seconds to get a value | |
from the sensor. */ | |
while (int i, i < 30, i++){ | |
sum = sum + sonar.ping_cm(); | |
delay(50); | |
} | |
int average_distance = sum/30; | |
/* Using the value, we send a signal to the relay | |
depending on whether someone is detected less than | |
130 cm away. We also pause for a second for good | |
measure. */ | |
if (average_distance < 130){ | |
digitalWrite(LIGHT, HIGH); | |
delay(1000); | |
} | |
else{ | |
digitalWrite(LIGHT, LOW); | |
delay(1000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment