Skip to content

Instantly share code, notes, and snippets.

@pfeerick
Created October 17, 2016 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfeerick/318383bc45b7d1af7cea350123c308a1 to your computer and use it in GitHub Desktop.
Save pfeerick/318383bc45b7d1af7cea350123c308a1 to your computer and use it in GitHub Desktop.
Simple example for the Oak that monitors a reed switch, and publishes an event on Particle when the state changes.
/*
Door Monitor
Monitors a reed switch for an open door, and posts to particle.
Created 2 June 2016
Updated 17th October
by Peter Feerick
*/
const int LED_PIN = 1; //The LED is connected to P1 on the Oak
const int REED_SW_PIN = 5; // Reed switch is conneted to P5 and GND
volatile boolean doorCurrentlyOpen = false;
boolean doorLastState = false;
boolean firstRun = true;
//1 when mag away, 0 when close...
void handle_reed_sw()
{
doorCurrentlyOpen = digitalRead(REED_SW_PIN);
digitalWrite(LED_PIN,doorCurrentlyOpen);
}
void setup()
{
Particle.publish("oak/userrom/startup", "Door Monitor v0.3", PRIVATE);
//initialise I/O pins - reed is pulled up so high when switch open
pinMode(LED_PIN, OUTPUT);
pinMode(REED_SW_PIN, INPUT_PULLUP);
//initialise inital values
doorCurrentlyOpen = digitalRead(REED_SW_PIN);
doorLastState = doorCurrentlyOpen;
digitalWrite(LED_PIN,doorCurrentlyOpen);
//attach interrupt to monitor reed switch
attachInterrupt(digitalPinToInterrupt(REED_SW_PIN), handle_reed_sw, CHANGE);
}
void loop()
{
//check if the door state has changed, or if this is the first check
if (doorCurrentlyOpen != doorLastState || firstRun)
{
//don't run this code again unless the door state has changed
firstRun = false;
//if the door is open, say so, else, say it's closed
if (doorCurrentlyOpen)
{
Particle.publish("door/middle-room", "open", PRIVATE);
}
else
{
Particle.publish("door/middle-room", "closed", PRIVATE);
}
//keep track of the last door state published
doorLastState = doorCurrentlyOpen;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment