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 serial.read 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++)
  pinMode(Pin[w],OUTPUT);

  Serial.begin(9600);
}

void loop (){
  while(Serial.available())  {
    w = Serial.read();
  }
  
  if (w=='3')  {
    digitalWrite(4,LOW);
    digitalWrite(2,LOW);
    digitalWrite (3,HIGH);
  }


  if (w=='4') {
    digitalWrite(3,LOW);
    digitalWrite(2,LOW);
    digitalWrite (4,HIGH);
 
  }
digitalWrite (w - '0', HIGH);

or

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 = Serial.read() - '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!