Question about CONTROLLING LEDS OVER THE 'NET

Hi Guys-

Being a complete programming novice, I am working through the examples given by spark, such as CONTROLLING LEDS OVER THE 'NET. While doing so, I am trying to understand the function of each line of code. You help is needed with the following:

My understanding is that command.charAt(1) is grabbing the first character of the string being sent. But why then is the code subtracting zero and then subtracting 1? That part has me confused. I assume the intended results of this line of code is to set int pinNumber to either a 1 or 2.

//find out the pin number and convert the ascii to a integer
int pinNumber = (command.charAt(1) - '0') - 1;

Here is the full code for reference:

// -----------------------------------
// Controlling LEDs over the Internet
// -----------------------------------

// name the pins

int led1 = D0;
int led2 = D1;

void setup() 

{

Spark.function("led", ledControl);

pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);

digitalWrite(led1, LOW);
digitalWrite(led2, LOW);

}

void loop() 

{
   
}

// This function gets called whenever there is a matching API request
// the command string format is l<led number>,<state>
// for example: l1,HIGH or l1,LOW
//              l2,HIGH or l2,LOW

int ledControl(String command)

{
    int state = 0;
    //find out the pin number and convert the ascii to a integer
    int pinNumber = (command.charAt(1) - '0') - 1;
    //sanity check to see if the pin numbers are within limits
    if (pinNumber < 0 || pinNumber > 1) return -1;
    
    //find out the state of the led (this should read: find out whether the command is HIGH or LOW by reading command string characters 3-7 or 3-6, respectively)
    if(command.substring(3,7) == "HIGH") state = 1;
    else if(command.substring(3,6) == "LOW") state = 0;
    else return -1;
    
    //write to the appropriate pin
    digitalWrite(pinNumber, state);
    return 1;

}

First of welcome!

There are answers to this very question on this forum already.

I’ll try to search for some, but maybe you can beat me to it :wink:


I guess I won :wink:
Searching for β€œled over net” came up with these

and in there was a link to this for further background info

The search feature does really work and help a lot.

2 Likes