LED PWM fade up-down beginner example


  • Newbie
  • *
    • Posts: 4
    • View Profile
On the off chance that someone is interested in a little beginner project, this code will fade an LED (or some LEDs) up and down.
My circuit takes Pin 3 through a 100Ohm resistor into the base of a little Darlington transistor.  4 purple LEDs in parallel are in the collector circuit to +4.5V, the emitter is grounded.  I have some yellow LEDs and they have a lower forward voltage so I put them two in series in parallel with another two in series.

Code: [Select]
TinyLily LED fade up-down PWM test
LED is attached to pin 3 in series with an appropriate resistor
I only know for sure that pin 3 is a PWM pin.
Pin 2 does not PWM when LEDpin = 2, LED goes on and off.
Pin 0 & 1 are associated with the USB/serial port and are active while uploading the sketch
This sketch does not work when powered from USB, only when powered externally (3xAA).  Why?
int i = 0;
int LEDpin = 3;

void setup() {
  pinMode(LEDpin, OUTPUT); // this is optional, sketch works without it
  digitalWrite(LEDpin, LOW); // this is also optional, sketch works without it
void loop()
// Fade up
  for(i = 0 ; i <= 255; i+=1)
    analogWrite(LEDpin, i);

// fade down
  for(i = 255 ; i >= 0; i-=1)
    analogWrite(LEDpin, i);


Hey, you gotta start somewhere, right?



SMF spam blocked by CleanTalk