Advertisement
belrey10

Lesson #4: Fade an LED

Nov 2nd, 2024 (edited)
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  Fade
  3.  
  4.  This example shows how to fade an LED on pin 9
  5.  using the analogWrite() function.
  6.  
  7.  The analogWrite() function uses PWM, so if
  8.  you want to change the pin you're using, be
  9.  sure to use another PWM capable pin. On most
  10.  Arduino, the PWM pins are identified with
  11.  a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
  12.  
  13.  This example code is in the public domain.
  14.  */
  15.  
  16. int led = 9;           // the PWM pin the LED is attached to
  17. int brightness = 0;    // how bright the LED is
  18. int fadeAmount = 5;    // how many points to fade the LED by
  19.  
  20. // the setup routine runs once when you press reset:
  21. void setup() {
  22.   // declare pin 9 to be an output:
  23.   pinMode(led, OUTPUT);
  24. }
  25.  
  26. // the loop routine runs over and over again forever:
  27. void loop() {
  28.   // set the brightness of pin 9:
  29.   analogWrite(led, brightness);
  30.  
  31.   // change the brightness for next time through the loop:
  32.   brightness = brightness + fadeAmount;
  33.  
  34.   // reverse the direction of the fading at the ends of the fade:
  35.   if (brightness <= 0 || brightness >= 255) {
  36.     fadeAmount = -fadeAmount;
  37.   }
  38.   // wait for 30 milliseconds to see the dimming effect
  39.   delay(30);
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement