Lighting an LED with PWM
/* Fading LED in a loop, speed set with a potentiometer.
* This test involves A/D conversion and PWM
*/
int ledPin = 6; // LED connected to D6 (pin #9)
int analogPin = 1; // Potentiometer connected to A1 (pin #20)
int pot; // Value read from potentiometer
void setup() {
pinMode(ledPin, OUTPUT); // sets the pin as output
pot = analogRead(analogPin); // read the analog input pin on startup.
}
void loop() {
/**
* Fading LED back and forth continuously
*/
int i=0, maxval = 255;
/** Scale **/
int wait = pot / 4;
/** Fade Up **/
for(i=0;i < maxval; i++){
delay(wait);
analogWrite(ledPin, i);
}
/** Fade down **/
for(i=maxval ; i>0; i--){
delay(wait);
analogWrite(ledPin, i);
}
}
Notes and findings
First argument in functions analogRead() and analogWrite() is the number in the pin name , not the chip pin number. For example, for pin D6 (chip pin #9) we must use:
analogWrite(6, value); // 6 for D6, not 9 for pin#9...
The function analogWrite() will accept values greater than 255 but the result will not be as expected. So always make sure second argument will not exceed 255.
|