This example will guide you through the process of connecting a button to your imp, and doing something whenever the state of the button changes.
This example assumes you have a basic familiarity with Electric Imp’s impCentral™. We suggest working through our Getting Started Guide before trying this example.
Note The following instructions were written with the imp001 in mind, but they can be readily adapted to any other imp and breakout board.
For this example you are going to need the following:
In impCentral, create a new Product called “Examples” (if you have not tried another of these basic hardware examples) and a new Development Device Group called “button”. Assign your device to the new Device Group, then copy and paste the following code into the code editor’s ‘Device Code’ pane and hit ‘Build and Force Restart’.
The first thing we do is assign hardware.pin1 to a global variable called button, this will make it easier to reference throughout the rest of our code:
button <- hardware.pin1;
Next, we create a function called buttonPress(). This function reads the current state of the button using pin.read(), this logs whether the button was pressed or released:
function buttonPress() {
local state = button.read();
if (state == 1) {
server.log("release");
} else {
server.log("press");
}
}
Finally, we configure the button to be DIGITAL_IN_PULLUP pin using pin.configure():
button.configure(DIGITAL_IN_PULLUP, buttonPress);
When we configure digital inputs, we can supply a callback (with no parameters) as an optional second parameter. If we do supply a callback function, it will be called whenever the state of the pin changes, either from LOW to HIGH, or HIGH to LOW.
Since the imp uses a callback function that automatically executes each time the state of the pin changes, there is no need to poll the state of the pin.
There are multiple ways to configure a digital input, but we’ve selected DIGITAL_IN_PULLUP as it requires the fewest extra components. Using DIGITAL_IN_PULLUP allows us to wire up our button without any extra resistors. Typically, you would add either a ‘pullup’ or ‘pulldown’ resistor to the circuit that would determine the ‘default’ state of the pin. Rather than adding these resistors ourselves, we can use the imp’s internal (40kΩ) pullup and pulldown resistors, as we’ve done in this case.
Since we’ve configured the pin to be a DIGITAL_IN_PULLUP our pin will read HIGH by default. When we press the button, we create an open path to the GND pin that will cause the imp to register LOW on pin1.