Next, you'll add code in your Smart Light device app to control the LED using the push button.
The basic steps to use a push button in your app code are:
Declare a global variable to store the I/O pin number for the button.
Set the pin mode for the button pin in the setup()
function.
Use a digitalRead()
statement to check whether the button is currently pressed, and add code statements that should be performed if the button is pressed (or not pressed).
Declare a global variable to store the I/O pin number for the button by adding this code statement before the setup()
function:
If you connected your button to a different I/O pin other than D2
, then modify this code statement to list the correct pin number for your button.
Set the pin mode for your button pin by adding this code statement within the setup()
function (between the curly braces):
The digitalRead()
method is used to check whether a button is currently pressed.
The digitalRead()
method will return a value of either LOW
or HIGH
:
LOW
indicates that the button is currently pressed.
HIGH
indicates that the button is NOT currently pressed.
A variable named buttonState
will store the value returned by the digitalRead()
method.
An if statement will be used to turn on the LED if the button is being pressed (if buttonState
has a value equivalent to LOW
).
An else statement will be included to turn off the LED if the button is not being pressed.
Replace all the existing code within the loop()
function (everything inside its curly braces) with this code instead:
COPY CODE: Remember that you can copy a code block in this guidebook simply by clicking the copy icon in the upper right of the code block.
Flash your app code to your Photon device by clicking the Flash icon in the left navigation bar.
Once your Photon has downloaded the app and restarted, the updated app will start running:
Confirm that the LED light that you connected to your Photon circuit board turns on when you press (and hold) the button – and turns off when the button is released.
Of course, nobody would want to continually press a button to keep a light turned on – however, this is a good way to verify that your button is connected correctly. In the next step, you'll modify the app code so the LED light toggles on or off with each button press.
If the LED does not turn on when the button is pressed, then there is a mistake in your app code – or a mistake in your wiring connection – or a mistake in both.
If the LED light is turned off and pressing the button has no effect, then verify that one of the button's legs is connected (via a jumper wire) to the same I/O pin number that is assigned to the button
variable in your app code. If necessary, change either your wiring or your code, so the pin numbers match. If you revised your code, flash the updated app to your device.
If that still doesn't solve the issue, then double-check all your button wiring by referring back to the connection instructions.