Arduino UNO Tutorial 5 - Fade

Arduino UNO Tutorial 5 - Fade

Following on from our Arduino UNO tutorial 3 where we examined timing, here is an update to the standard Arduino Fade example. Instead of using the wasteful delay() function we use the timing functionality from tutorial 3 which allows other code to be run at the same time. The code should be self explanatory.

Simply connect an LED and 220 ohm series resistor between pin 9 and ground.

/*
 Fade
 
 This example shows how to fade an LED on pin 9
 using the analogWrite() function.
 
 This example based on the Arduino Example Fade sketch
 but modified to use timing instead of the delay() function
 
 */
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
unsigned long currentTime;
unsigned long loopTime;

void setup()  { 
  // declare pin 9 to be an output:
  pinMode(9, OUTPUT);
  currentTime = millis();
  loopTime = currentTime; 
} 

void loop()  { 
  currentTime = millis();
  if(currentTime >= (loopTime + 20)){  
    // set the brightness of pin 9:
    analogWrite(9, brightness);    

    // change the brightness for next time through the loop:
    brightness = brightness + fadeAmount;

    // reverse the direction of the fading at the ends of the fade: 
    if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount ; 
    }     
    loopTime = currentTime;  // Updates loopTime
  }
  // Other processing can be done here
                           
}

Tutorial 4 - Simple Cylon

Tutorial 6 - Rotary Encoder

Shopping Cart
0 items
 
DELIVERY/PAYMENT

Free Delivery Orders over £50

UK - £2.40 orders under £50
Airmail from £2.95 (+VAT)
More Details...

 
Brands
 
 Check out our videos
Follow us on:
acebook