assigning pin values from serial input

Program often start with declarations like:

int led = 13;

Then led gets used in a loop somewhere to perhaps turn on or off an led:

digitalWrite(led, HIGH);

of course after declaring the pin as an output. What I wish to do seems like it should be simple, but after many attempts, it has not yet worked for me. This is what I'd like to do:

I have already written a program on my pc that sends serial commands to the arduino at the press of a button. I want that command to set led to 13 (or some other value of my choosing) and then for the appropriate led to light up. I expect the pc also to be able to CHANGE that value on the fly if need be. Anybody done something like this or know how to?

Awaiting excellent replies.

Timo

Anybody done something like this or know how to?

Yes. Plenty of people have, and know how to.

You need to first define what you are going to send to the Arduino EXPLICITLY - not "something like...".

Then, you write code for the Arduino to collect serial data from when the start of packet marker arrives until the end of packet marker arrives. Then, you parse that data as use it as appropriate.

The principle is easy, your design depends on a lot.

Works with P:[num]:[val] P:13:1

char c[] = { 0, 0, 0, 0, 0, 0, 0 };
char cursor = 0;

while( true ){
  if( Serial.available() > 0 ){
    c[ cursor ] = Serial.read();
    if( cursor++ == 5 ) break;
  }
}
if( c[0] == 'P' ){
  if( c[1] == ':' && c[4] == ':' ){
      int i = atoi( c + 2 );
      int j = atoi( c + 5 );
      digitalWrite( i, j ? HIGH : LOW );
    }
  }