Using Variables with digitalWrite

Hello together,

I need your help, because I’m new here :smiley:

I want to program my Arduino so that when I enter a number (1-9) in the serial monitor, the LED at this pin lights up.

I already programmed the following code for Pin 3 and 4, but I don’t want to enter the last part nine times. Because of that I want use a variable. I thought this is quite easy, as is equal the pin, but it doesn’t work out.

Do you got any hints or solutions ?

Thanks in advance!

byte w;                                   
int Pin[6] = {2,3,4,5,6,7};

void setup(){
  for(w=0; w<3;w++)


void loop (){
  while(Serial.available())  {
    w =;
  if (w=='3')  {
    digitalWrite (3,HIGH);

  if (w=='4') {
    digitalWrite (4,HIGH);
digitalWrite (w - '0', HIGH);


digitalWrite (w - 48, HIGH);

Do not use pin 1 or 0 as they are the Serial TX and RX pins.

Pin [w - ‘0’]

I believe you are looking for something like the following?

void loop() {
   if (Serial.available()) {
      w = - '0';  // subtract ASCII code for '0'
      for (byte i = 0; i < 6; i++) {
         if (Pin[i] == w) {
            digitalWrite(Pin[i], HIGH);
         } else {
            digitalWrite(Pin[i], LOW);

Thanks a lot for your fast advice :slight_smile:

Now the programm is working!