Created
May 31, 2016 22:26
-
-
Save netmaniac/e4b25d108c9b58d9025ee83a598b4d6d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SPI.h> | |
#include "Battery.h" | |
#include <Radio.h> | |
#include "PinChangeInterrupt.h" | |
//#include <TinyDebugSerial.h> | |
//TinyDebugSerial debug = TinyDebugSerial(); | |
#define BUTTON 10 | |
#define PHOTOCELL_PWR 9 | |
#define PHOTOCELL A2 | |
#define MAX_DELAY_AFTER_FAILED_SENT 20 | |
#define LIGHT_THRESHOLD 200 | |
void tick() { | |
}; | |
struct SensorData | |
{ | |
byte id; | |
long battery; | |
byte status; | |
float payload; | |
byte seq; | |
byte retry; | |
} data; | |
//************************************************************** | |
bool radioWrite(struct SensorData &data, byte retry = 0) | |
{ | |
byte addressRemote[3] = { 0, 0, 3}; | |
if (retry == 5) { | |
//we have failed transmit.. | |
data.seq ++; | |
return false; | |
} | |
data.retry = retry; | |
Radio.write(addressRemote, data); | |
while (true) { | |
switch (Radio.flush()) { | |
case RADIO_SENT: | |
data.seq++; | |
return true; | |
case RADIO_LOST: | |
return radioWrite(data, retry + 1); | |
} | |
} | |
} | |
//******************************************** | |
void setup() { | |
byte address[5] = {3, 4, 5}; | |
Radio.begin(address, 100); | |
data.id = 20; | |
Radio.off(); | |
pinMode(BUTTON, INPUT_PULLUP); | |
attachPcInterrupt(BUTTON, tick, CHANGE); | |
} | |
//******************************************** | |
float readLight() { | |
pinMode(PHOTOCELL_PWR, OUTPUT); | |
digitalWrite(PHOTOCELL_PWR, HIGH); | |
delay(2); | |
data.payload = analogRead(PHOTOCELL); | |
digitalWrite(PHOTOCELL_PWR, LOW); | |
pinMode(PHOTOCELL_PWR, INPUT); | |
} | |
//******************************************** | |
bool doorClosed() { | |
return data.status == 1; | |
} | |
//******************************************** | |
void sendData() { | |
bool sentPacket = false; | |
byte cnt = 0; | |
while (!sentPacket) { | |
if (radioWrite(data)) { | |
sentPacket = true; | |
cnt = 0; | |
} else { | |
sleep(cnt * 5000); | |
if (cnt < MAX_DELAY_AFTER_FAILED_SENT) | |
cnt++; | |
} | |
} | |
} | |
//******************************************** | |
bool lightIsOn() { | |
return data.payload > LIGHT_THRESHOLD; | |
} | |
//******************************************** | |
void loop() { | |
readLight(); | |
data.status = digitalRead(BUTTON); | |
data.battery = batteryRead(); | |
sendData(); | |
Radio.off(); | |
deepSleep(); | |
delay(100); //debounce | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment