Page 113 - Programming the Photon Getting Started With the Internet of Things
P. 113
}
else if (percentage > 66) {
digitalWrite(green, LOW);
digitalWrite(red, HIGH);
digitalWrite(blue, LOW);
}
}
When you run the program on the Photon, the LED should light up a particular color
depending on the light levels taken from the photocell. Try covering the photocell with
your hand and see if the color changes again; then try shining something bright at the
photocell, and it should change the LED color. Because we are using an RGB LED, we
can use a number of different combinations of colors, so we are not necessarily forced to
use three different colors—we can easily use up to six with the function digitalWrite.
However, if we use an analog output, then the number of colors and shades we can create
is limitless.
We can look at the code in a bit more detail by breaking it up into the following
sections. When programming code, it is always easier to break your code up into sections,
as it makes it easier to understand what’s going on and easier to debug your code when
there are issues.
Declare the digital pins on the RGB LED. Label these with the color that each pin
will represent.
Tell the Photon that the RGB LED pins are digital output pins by using the function
digitalWrite.
Read the input value from the light-dependant resistor and store this as an integer in
the variable called “value.”
Use the function map() to convert the input value to a percentage.
Calculate the value using if statements to determine which color on the RGB LED
to switch on and off.
Add a short delay to the end of the code.
Within our firmware we use if else functions, which allows us to check another
condition if the first condition is false. The syntax looks like this:
if (conditions A) {
execute the code here if A is true
}
else if (condition B) {
execute the code here if condition A is false and condition
B is true