Is there a library for switches?

I have a very simple set up.

Hardware: I have a wire from GND going into a SPST switch and then into D0.

int ao_switch = D0;

void setup() {

void loop() {

void checkSwitch() {
  //Check the switch position
  bool previous = include_obs;
  if(digitalRead(ao_switch) == HIGH) {
      include_obs = true;
  } else {
      include_obs = false;
  if (previous != include_obs) {
        Particle.publish("switch_mode", include_obs?"true":"false");

The problem is that I get a bunch of false-positive switch changes. I have checked the connections and they are all good. Is there any library that can be used to dampen these changes?

Also, is this the best way to monitor for switch changes?

You need to debounce switch inputs to ensure that you filter out spurious signals. I have a simple I/O scanner library that I have used for years and recently ported to the Particle environment that you may find useful.

You need to call the scan function in your loop, but with a delay of at least 10mS (could be longer depending on how bouncy your contacts are.) Here is a short example:

// Define the Pins and the inputs/outputs

int                 door_sensor_pin         = D2;
int                 bag_sensor_pin          = D3;
int                 door_opened_pin         = D4;
int                 bag_sensed_pin          = D5;

DigitalInput        door_sensor(door_sensor_pin, INPUT_PULLUP, false);
DigitalInput        bag_sensor(bag_sensor_pin, INPUT_PULLUP, false);
DigitalOutput       door_opened(door_opened_pin, false);
DigitalOutput       bag_sensed(bag_sensed_pin, false);

// Determine the scanning rate for debounce.

IntervalTimer       scan_timer(10);

void setup() 

void loop() {

    // Delay I/O scanning for debounce.
    if (scan_timer.Expired())
        // Reflect the input sensors to the outputs.
        // Process the door sensor activity.
        if (true == door_sensor.FallingEdge())        // Door Closed
        else if (true == door_sensor.RisingEdge())    // Door Opened

The IntervalTimer class I use is a simple one that relies in millis(), which you can do yourself directly with the millis() function.

I hope this helps.

cool. I will try that. How do you include that library using build?

Do you know if there is a library that generates events or interrupts or callbacks or something when the switch changes?

In build, create new .cpp and .hpp files and then copy/paste the source from the respective files from github.

While you can use an interrupt with the input

it becomes problematic when the input is a bouncy switch. See this: