I'm following the book Beginning Arduino and doing some exercises with LEDs.
I noticed that sometimes, usually when there's something wrong in my code, the LEDs get dim. If I change back to a code that I know is working well, the LEDs get back to normal brightness.
Why does this happen?
I'm currently trying this specific exercise where I have 10 LEDs set in a horizontal line and have to make them light as a bouncing ball. It lights up the first LED and goes to the last, then do the same thing but goes until the last but one.
My code seems to be working, except that the LEDs are so dim, and again, when I try another code they work normally.
byte ledPin[] = {4,5,6,7,8,9,10,11,12,13};
byte potPin = 2;
unsigned long changeTime;
int ledDelay;
byte qk = 9;
byte currentLED = 0;
byte direction = 1;
void setup() {
for(int i; i<10; i++){
pinMode(ledPin[i], OUTPUT);
}
changeTime = millis();
}
void loop() {
//delay according to potentiometer
ledDelay = analogRead(potPin);
if((millis() - changeTime) > ledDelay){
changeLED();
changeTime = millis();
}
}
void changeLED(){
//turns off all leds
for(int i=0; i<10; i++){
digitalWrite(ledPin[i], LOW);
}
//turns on current led
digitalWrite(ledPin[currentLED],HIGH);
currentLED += direction;
//changes direction
if(currentLED == qk){
direction = -1;
}
//changes direction and starts the bouncing effect
if(currentLED == 0){
direction = 1;
qk -= 1;
}
if(qk == 1)
qk = 9;
}
Do not connect anything to digital pins 0 or 1, or attempt to write anything to them. There are used for the serial interface with which you communicate to the Arduino, don't muck about with them.
Change your code to avoid pins 0 or 1 in any way, and start again from there.
I don't see where I could be writting anything on pins 0 or 1.
I only set the led array as output, which is from 4 to 13.
"currentLED" is used as the array index later
or in fact, set a temporary variable from millis(), if it exceeds the delay, set changeTime from that value as millis() may have advanced at just that moment.
I cannot see you allocate a value to ledDelay (which also should be a long)! Is this the actual problem?
Except for initialisation, it would seem simpler to turn ledPin[currentLED] off, then change currentLED.
Haha it works now!
I wrote it right after in the other fuction and still didn't notice it!
That's interensting tho, how this could make the LEDs go dimmer