arduino

I have no idea why my code is not working


So my code is something very simple, just a fading led.

The problem is that it just stops suddenly.

My code:

int led = 9;
int brightness = 0;
int fade = 5;


// The setup function runs once when you press Reset or power the board
void setup() {
Serial.begin(9600);
pinMode(9, OUTPUT);
}

// The loop function runs over and over again forever

void loop() {

lum = lum + fade;
for(brightness = 0 ; brightness <= 255 ; brightness++) {
analogWrite(led, brightness);
Serial.println(analogRead(brightness));
delay(8);
}


for(brightness = 255 ; brightness >=0; brightness--) {
analogWrite(led, brightness);
Serial.println(analogRead(brightness));
delay(8);
}

}

My code was working before I put in the lines "Serial.println(analogRead));". With this two lines I just wanted to see the output going from 0 to 255 (as the led gets brighter). As soon as I tried this, the code just returns 0 ... 0 ... 0 ... 0 ... 8. And it just stops.

Probably it has something to do with the thing that I am supposed to write digitalRead? (I also tried that, it doesnt work)


Solution

  • The analogRead function is used to read the voltage on one of the analog inputs (A0-A5). The argument to it is the pin number and it returns a number from 0-1023 depending on the voltage at the input pin. It has nothing to do with your PWM output.

    brightness in your program is a variable that holds the value 0-255 that you are writing to the PWM pin. If you want to print that value then just print it:

    Serial.print(brightness);