Reading a switch closure on the Imp

Just got my Imp and April board. Established the connection and successfully ran the LED blink demo.

My Imp goal is to Tweet activity from my cat door using my account. The trick (for me anyway) is how do I get the Imp to recognize a switch closure or Hall effect sensor?

Can someone page slap me with a link to get me moving down the right path?


We have examples on devwiki, but they may be a bit over-complex for a single switch.

Here’s my code for a simple on/off switch, connected between pin 1 and ground:

`// Single switch
server.log(“Switch booted”);

local out1 = OutputPort(“Switch”, “ImpScalar”);
imp.configure(“Switch”, [], [out1]);

local laststate = -1;

// Debounce code: ignore transitions for 50ms after event
local ignore = false;
function debounce() {
// We can take notice of transitions from now onward
ignore = false;

// Ensure state is in sync


function switched() {
if (!ignore) {
local s =;

    if (s != laststate) {
        laststate = s;
    // Ignore bounces
    ignore = true;
    imp.wakeup(0.05, debounce);


hardware.pin1.configure(DIGITAL_IN_PULLUP, switched);


Thanks for the wicked fast reply! I will test the code soon as soon as I can, hopefully today. Not completely certain on the next steps to using the Imp to trigger my Sen.ce Twitter application, but I sort through that next.

The Imp is an extremely cool piece of kit. Maybe it is me, but I am having some issues finding good documentation. I am glad to find the support forum so useful.

I will post up here with results to try and add my two cents to the forum knowledge base.

Thanks again.

Quick update:
I admit that I don’t fully understand the code, but the code works prefectly. (I know you knew it would. ;))

When PIN1 to GND is open the log shows “ON”; when closed is shows “OFF”. Good enough.

Now I’ll figure out how to have my account understand the Imp. And then… World Domination (insert evil laugh here).

Thanks again,

Ok, world domination will have to wait. The switch program is solid, but I have other issues, I have continued the discussion on the Imp/Twitter thread (

Thanks again for the coaching.

No problem, we do have to get more examples up there…

Hugo, Thanks, Any comments from my post on the Imp/Twitter thread (

Thanks for the awesome code example Hugo!

@IJLabs - using 3rd party APIs through translation code isn’t really my speciality… but (and I realize this is becoming a common refrain) agents make this easy. Can’t wait until they’re out and I can stop saying that :wink:

btw, I’ve added a page on the wiki with various code examples - not worked examples, but examples with some comments. We’ll keep adding more there over time.

How would you add separate switch sensors into the code? e.g. switch 1, switch 2, switch 3


This example on the dev wiki is even simpler, using the pinchanged callback:


Great example. Very basic and fundamental.

Has anyone integrated to tweeter which an application other than “”. The “” twitter app is often down and I would like to find another way.

For some extra info, my build page is at:

can someone please help me update this code to the new IDE standard?

I am the OP.

Note: I am not using for tweeting anymore. I tweet using a .PHP that triggers a Maker Channel I created at Probably a better way to do it would be to leave out and tweet straight from the .PHP, but I already have several IFTTT uses and they have proved to be very reliable/useful.

This is my current build using AGENT and DEVICE:

Tweeting Cat Door

*** Many Many thanks to the Electric Imp forum! ***
Special thanks to brendandawes, Hugo, odb, beardedinventor

Read switch on PIN7 and GND
Normally Open or Normally Closed can be adjusted in swEvent function
Blue LED PIN9 to V3V is ON if the code in running
Blinks off when door switch detected

hardware.pin9.write(0); // LED ON, active LOW
local channelOutput = [ OutputPort(“Ch 1”, “string”)]; // String var that gets sent to PHP script

//Watchdog code below send Ping to Imp server every xx secs
//I added this because the Imp was not Tweeting all switch closures and
//power up/down seems to correct it. Assuming lost connection with Imp server?
function watchdog() {
imp.wakeup(600,watchdog); //xxx is seconds between pings
//server.log(“WatchDog ping…”); // this will echo “text” to debug window

//End of my watchdog code experiment

local stringForAgent;
local d = date(); // Date info not sent to twitter. Used only for planner debug
local min = d[“min”];
local hour = d[“hour”];
hour = hour -6; //adjust for central time
local sec = d[“sec”];
local state =; // put condition on the switch in var ‘state’
state = 0;

// function swEvent handles looking for action on the door switch
function swEvent() {
d = date(); // Date info not sent to twitter. Used only for planner debug
min = d[“min”];
hour = d[“hour”];
hour = hour -6; //adjust for central time
sec = d[“sec”];
state =
//server.log("State is "+state);

    imp.sleep(5.0); // switch settle time of x.x seconds (long due you door swing back and forth)
    // for some reason having settle time in the 'if' block below resulted in two executions
    if (state == 1) {   // "1" Tweets when switch opens (for a NC swtich).  "0" Tweets when switch closes (for a NO swtich).
        // Blink the LED Off to show a door swing detected
        hardware.pin9.write(1);  // LED OFF
        //imp.sleep(0.5)          // 500mS delay  ((this line and next line)
        //hardware.pin9.write(0);  //  LED back ON ((replaced with line below.  Suggestion from Hugo May 5, 2013)
        imp.wakeup(0.5, function() { hardware.pin9.write(0); } ); // turn LED on again after 500ms (Hugo's line)
        server.log("       ---");  // just a space for formatting
        server.log("0/FLAP DOWN. 1/FLAP UP: "+state+", Door Active at "+hour+":"+min+":"+sec);  //echo to the debug planner window the generated RANDOM# and time.  Used for debug.
        //  echo switch state (O or 1) and time to planner window for debug pane
        // start new code from 'opd' in Imp forum
        // this agent.send call, with the name "catFlap" will trigger the corresponding "device.on"
        // call in the agent code. We send it a simple table with our string we created.
        agent.send("catFlap", { "dateString" : stringForAgent });
        imp.sleep(10.0);  // switch settle time of x.x seconds (long due you door swing back and forth) 
        // End new code from odp...

} // End function swEvent

// Configure pin 9 as an open drain output with internal pull up
// Configure pin 7 as switch
hardware.pin7.configure(DIGITAL_IN_PULLUP, swEvent);
server.log(“"); // just a space for formatting
server.log(“0/FLAP DOWN. 1/FLAP UP: “+state+”, Program run started at:”+hour+":"+min+":"+sec);
”); // just a space for formatting


  • AGENT CODE for @OurCatDoor tweeting cat door
  • *** Many Many thanks to the Electric Imp forum! ***
  • Special thanks to brendandawes, Hugo, odb, beardedinventor


// call .PHP for Tweeting
pi_url <- “”;

// function to send a table of keys and values as POST data
function pi_post(post_table)
local headers = {};
local req =, headers, http.urlencode(post_table));
local resp = req.sendsync();
if(resp.statuscode == 200)
server.log(“xxxxxx.php request = 200/OK/Successful”);
return true;
server.log("xxxxxx.php request error, status code = "+resp.statuscode);
return false;


// This is called on the agent when the device sends the “catFlap” event

device.on(“catFlap”, function(tableSentByDevice){
pi_post({“postVarName”: tableSentByDevice.dateString});
//pi_post({“postVarName”: tableSentByDevice.stringForAgent});