Hi All,
I've come across a strange behaviour when I set pinMode by an array.
The setup:
- Arduino Nano
- 10x LEDs wired individually (from ground, through resistors) to pins 2 to 11.
- The wiper of a 10k pot wired to A7 (i.e. 0-5v input).
- The code progressively lights up the LEDs as the pot is turned up.
The problem:
- When I set pinModes individually, the code works fine.
- When I set pinModes by a for loop and an array, the LED on pin 10 lights up, but is very dimly lit (all other LEDs light up as expected).
Here is the code that works:
int PINS[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
void setup() {
// Manually set each output pin => works as expected
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(A7, INPUT);
}
void loop() {
for (int i = 1; i <= 10; i++) {
if (analogRead(A7) > i * 93) {
digitalWrite(PINS[i - 1], HIGH);
} else {
digitalWrite(PINS[i - 1], LOW);
}
}
}
So I'm assuming that since that code works and all LEDs light up as expected, the hardware is operating and wired correctly.
Here is the code that has the dim LED on pin 10:
int PINS[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
void setup() {
// Set each output pin using for loop => works EXCEPT FOR PIN 10 !!
for (int i = 0; i <= 9; i++) {
pinMode(PINS[i], OUTPUT);
}
pinMode(A7, INPUT);
}
void loop() {
for (int i = 1; i <= 10; i++) {
if (analogRead(A7) > i * 93) {
digitalWrite(PINS[i - 1], HIGH);
} else {
digitalWrite(PINS[i - 1], LOW);
}
}
}
Doesn't matter where I put the "10" in the array, the LED on pin 10 is always dim.
Oh, and if I take that malfunctioning code, and just add pinMode(10, OUTPUT); after the pinMode for loop, it works correctly:
int PINS[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
void setup() {
for (int i = 0; i <= 9; i++) {
pinMode(PINS[i], OUTPUT);
}
pinMode(10, OUTPUT); // Add this line and then the LED on pin 10 works correctly
pinMode(A7, INPUT);
}
void loop() {
for (int i = 1; i <= 10; i++) {
if (analogRead(A7) > i * 93) {
digitalWrite(PINS[i - 1], HIGH);
} else {
digitalWrite(PINS[i - 1], LOW);
}
}
}
Something weird going on with pin 10 and the pinMode for loop. Very strange. Any ideas ? Thanks !