Arduino Control over serial

What i am looking for is how to control x number of leds, buzzers etc over serial. I have done some research on this subject with close results. The examples i found online are if the number say 5 is sent it will turn on pin 5 and then if you send it another number it will turn off all except the new number. what i want is to be able to send it a number and it will turn it on and then if you send it again it would shut off or if another number is sent it would shut off also. any advice would be greatly appreciated.

Thanks

Have a flag hold the state of '5'. Every time it receives a '5', invert the state of the flag.
Psuedo code

if('5' received){
flag5 =!flag5; //invert flag
digitalWrite(pin5, flag5); //turn pin 5 on or off
}

Seems pretty straightforward.

if (Serial.available()>0){
incomingByte = Serial.read() - 0x30; // read ASCII from serial monitor & convert to decimal
outputArray[incomingByte] = 1-outputArray[incomingByte]; // toggle state: 1-1=0, 1-0=1
digitalWrite (incomingByte, outputArray[incomingByte]);
}

Works for 2 to 9. Above 9, need to read 2 characters:
2digits = (incomingByte1 - 0x30) x10 + (incomingByte2 - 0x30);

Or always send to characters: 02 to 19.

Have a look at the examples in serial input basics. One of them will probably be suitable.

There was a similar (almost identical) question in the last few days. Google should find it for you.

...R

if (Serial.available()>0){
incomingByte = Serial.read() - 0x30; // read ASCII from serial monitor & convert to decimal
outputArray[incomingByte] = 1-outputArray[incomingByte]; // toggle state: 1-1=0, 1-0=1
digitalWrite (incomingByte, outputArray[incomingByte]);
}

Wow! That's cool, creative. Gonna put that in my 'cool code' folder. Can't imagine what coding 'hoops' I would've set up to get the same end result. Thanks for posting. - Scotty

KesL:
What i am looking for is how to control x number of leds, buzzers etc over serial. I have done some research on this subject with close results. The examples i found online are if the number say 5 is sent it will turn on pin 5 and then if you send it another number it will turn off all except the new number. what i want is to be able to send it a number and it will turn it on and then if you send it again it would shut off or if another number is sent it would shut off also. any advice would be greatly appreciated.

Here I have posted a serial command program I made for another forum user:

You can assign ‘device names’ to the devices controlled on different pins.
And there are three commands supported

  • on (set pin HIGH)
  • off (set pin LOW)
  • click (set pin HIGH for a number of milliseconds, then LOW again)

So you could create a serial control program that reacts on commands like:
motor on
pump off
buzzer click 75

Perhaps have a look at the sketch.