Arduino Switches

Part of the Exuro project includes the setup for a momentary contact switch that can be used to trigger the poofer. This way the system can either be run as a donation machine with the bill reader being used to trip the poofer or it can be manually controlled via a momentary contact switch.

My first attempt at connecting a switch was done by just connecting one switch terminal to ground and the other to the Arduino pin 2. The code was pretty straight forward:

int relay_state = LOW;
void toggle_relay()
  relay_state = !relay_state;
void setup() {
    attachInterrupt(0, toggle_relay, CHANGE); 

This had an number of unfortunate problems. The biggest one was that every once in a while the interrupt would be triggered all by itself . Without doing anything, the poofer relay would trigger. That wasn’t good. (The code for the poofer relay isn’t shown here.) It turns out that the problem was the electrical circuit. Since the switch was just connected between ground and pin 2, the wire running to the switch would act as an antenna and cause the hardware to think that the interrupt should be triggered. To resolve this problem, a 1k resistor was placed between pin 2 and ground. This ensured that the electrical signal traveling over the switch wire was stable.

The second annoying problem was that every once in a while an interrupt would be missed and the relay_state would be wrong. The toggle_relay code merely sets the relay_state to the inverse of what it was. That is if it’s a 1 then it becomes a 0 and if it’s a 0 then it becomes a 1. So if an interrupt is missed then the relay_state would be wrong and the poofer relay would be be the inverse of what it was supposed to be.

To resolve that, the toggle_relay code was changed to:

void toggle_relay()
  int val = digitalRead(2);
  if (val == LOW) {
    relay_state = LOW;
  } else {
    relay_state = HIGH;

This way the relay_state is always set to the state of the switch as read off pin 2. With these two changes, adding a 1k resistor and directly reading the pin, the system is much more stable and works as needed. Yea!

Many thanks to CTP for the pointer to using a resister to stabilize the switch.

Tags : ,