Page 119 - Programming the Photon Getting Started With the Internet of Things
P. 119
Let’s take a look at the following code, which we will use to turn the LED on and off
using the Internet:
int led1 = D0;
void setup()
{
pinMode(led1, OUTPUT);
Spark.function("led",ledToggle);
digitalWrite(led1, LOW);
}
void loop()
{
}
int ledToggle(String command) {
if (command=="on") {
digitalWrite(led1,HIGH);
return 1;
}
else if (command=="off") {
digitalWrite(led1,LOW);
return 0;
}
else {
return -1;
}
}
The code first defines the variable led1 for digital pin D0, so whenever we call led1
we are actually calling pin D0. Labeling the pin makes it easier to know which pin you are
using and allows efficient debugging. This is also the pin that we have connected our LED
to so we can turn it on and off. The setup function defines led1 as an output pin so the
Photon board knows how to handle it when we send a command to the pin. The second
line is where we declare our function that we can call through the Internet: