Button Controlled Relay

Do you ever get tired of getting up to turn the light off? Is that fan running when it doesn’t always need to be? A relay is a simple switch controlled by a small input signal, and when paired with an Arduino board, it can be told through code to turn on under specified conditions. This gives more control than a manual switch, and more convenience.

Button Controlled Relay

I am using an Arduino Uno and a TinkerKit relay module in this example. The red wire coming from the relay is 5v, the black wire is GND, and the center orange wire is the signal input wire to activate the relay. I put a button in to control the relay, and that required more code.

I ran into debouncing problems, and had to do some research. With push buttons, the button could be slightly pressed and send multiple short signals. As you can imagine, your lights flickering on and off like that would be an annoyance, and it would be hard to stop the flickering in the desired position, on or off. After reading, I found that some had suggested a 10ms delay in the loop would solve that problem. Here is the code I used after some edits.

const int BUTTON_PIN = 7; // set button pin
const int RELAY_PIN  = 3; // set relay pin

int button_state = 0; //variable for button's state
int button_state_old = 0; //variable to store old button state
int relay_state = 0; //variable to store relay state


void setup() {
  Serial.begin(9600);
  pinMode(BUTTON_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
  pinMode(RELAY_PIN, OUTPUT);        // set arduino pin to output mode
}

void loop() {
  button_state = digitalRead(BUTTON_PIN); //read button input value and store

  if ((button_state == HIGH) && (button_state_old == LOW)) {
    relay_state = 1 - relay_state;
    delay(10); //10ms delay
  }

  button_state_old = button_state; //set old button state

    if (relay_state == 1) {
    digitalWrite(RELAY_PIN, LOW); //switch relay on
  } else {
    digitalWrite(RELAY_PIN, HIGH); //switch relay off
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *