Happy Arduino Day 2016 + Testing a Power Relay

Happy Arduino/Genuino Day 2016!

arduino uno pic

Take some time today to do a little project with your Arduino!

Testing a Power Relay

My tech savvy grandma recently got me a very nice IoT power relay! I spent a while testing it out by making a simple system to automatically turn my desk light and my Pi monitor on or off. I hooked an SR-04 ultrasonic sensor to my Arduino Uno and wrote a sketch to have it detect when my hulking mass is close to my desk and send a signal to turn the relay on or off.

power relay hooked up
This is my power relay setup connected to an Arduino and ultrasonic sensor. I taped the ultrasonic sensor down to keep it from wiggling about. The Arduino is being powered by a USB port on my Pi 2.

The most challenging part of creating this little system was getting accurate readings from the ultrasonic sensor. They can read inaccurately if objects are moving around in front of the sensor, and the light would flicker annoyingly if I moved too quickly. I figured out how to smooth the value by reading from the sensor 30 times in 1.5 seconds, and then taking the average of all 30 values.

The power relay works great. It required no setup out of box, and it’s simple to connect your controller. Its only disadvantage is that it doesn’t have an ‘always-on’ power source, which requires you to have an external power source for the device controlling the relay.

iot power relay
This is the power relay I tested.

Check out the sketch I wrote for this project below, or click here to download.

/* 

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 whether
  someone is near, we read the ultrasonic sensor
  30 times and take the average. That way, if the
  ultrasonic sensor reads sporadically as it 
  occasionally 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);
  }
}