Oh ok I see what your saying.
// Copyright © 2013 Electric Imp
// This file is licensed under the MIT License
// http://opensource.org/licenses/MIT
//
// Description: Debounced button press with callbacks
class Button{
static NORMALLY_HIGH = 1;
static NORMALLY_LOW = 0;
_pin = null;
_pull = null;
_polarity = null;
_pressCallback = null;
_releaseCallback = null;
constructor(pin, pull, polarity, pressCallback, releaseCallback){
_pin = pin; //Unconfigured IO pin, eg hardware.pin2
_pull = pull; //DIGITAL_IN_PULLDOWN, DIGITAL_IN or DIGITAL_IN_PULLUP
_polarity = polarity; //Normal button state, ie 1 if button is pulled up and the button shorts to GND
_pressCallback = pressCallback; //Function to call on a button press (may be null)
_releaseCallback = releaseCallback; //Function to call on a button release (may be null)
_pin.configure(_pull, debounce.bindenv(this));
}
function debounce(){
_pin.configure(_pull);
imp.wakeup(0.050, getState.bindenv(this)); //Based on googling, bounce times are usually limited to 10ms
}
function getState(){
if( _polarity == _pin.read() ){
if(_releaseCallback != null){
_releaseCallback();
}
}else{
if(_pressCallback != null){
_pressCallback();
}
}
_pin.configure(_pull, debounce.bindenv(this));
}
}
//Example Instantiation
b1 <- Button(hardware.pin2, DIGITAL_IN_PULLUP, Button.NORMALLY_HIGH,
function(){
//server.log(“Button 1 Pressed”)
// create table and send to agent
local data = { “button1”: “CLOSED”, “mykey”: “23123faa5ba5ceee” }
agent.send(“senddata”, data);
},
function(){
//server.log(“Button 1 Released”)
// create table and send to agent
local data = { “button1”: “OPENED”, “mykey”: “23123faa5ba5ceee” }
agent.send(“senddata”, data);
}
);
function hardwareWakeup() {
agent.send(“pin1wakeup”, null);
}
// if we woke up because of PIN1, notify agent
if(hardware.wakereason() == WAKEREASON_PIN1) {
hardwareWakeup()
}
// we can only go to deepsleep if hardware.pin1 is low
function TrySleep() {
if (hardware.pin1.read() == 0) {
// if pin1 is low, we can sleep
server.log(“Going to sleep”);
imp.onidle(function() { imp.deepsleepfor(3600.0); });
} else {
// if we can’t go to sleep yet, wait a while, them try again
server.log(“Can’t sleep.”);
imp.sleep(5.0);
imp.onidle(TrySleep);
}
}
hardware.pin1.configure(DIGITAL_IN_WAKEUP);
// go to sleep
TrySleep();