
MagicCode Lesson 6
Change brightness of LED according to the input
Components Required
Introduction
Learning Outcomes
From this example, you’ll get an understanding about,
- IF-ELSE conditions
- Variables
Theory
To change the brightness of a LED we could change the voltage the LED is supplied with, but in a microcontroller, ability to change the voltage (converting a digital number to an analog voltage) is limited, so a method called PWM (Pulse Width Modulation) is used. What this does is pulsing on and off the pin in a high frequency. The length of the pulses creates the perception of brightness.
Duty cycle is a term used to describe the ratio between on and off times.
In this example higher Duty cycle gives higher brightness & lower duty cycle gives lower brightness.
Methodology
Lets select green LED (which is wired to D16). Drag and Drop following control, operators, variables and MagicBit blocks from the block palate and make the following scripts.
Script
Explanation
This program starts by clicking the green flag. In this example ‘my variable’ block in variables block set has renamed as ‘i’. Then using the ‘set [Variable] to [value]’ block, variable ‘i’ is initializes to zero. The forever block continuously runs the code held inside the block. Duty cycle is represented as a percentage (0 – 0% duty, 255-100% duty) in ‘Set PWM pin [pin] as [Duty cycle]’ block. In the script, a conditional block is used to stop the duty cycle at 100%. By using the ‘Change [variable] by [increment value]’ block, variable ‘ i’ is incremented by 1.
This script increases the brightness of the LED smoothly with increments of the duty cycle and when the duty cycle reaches to 100% LED stays at its maximum brightness.
Note: This example we have coded to increase the brightness, write a code to do the opposite of that, to fade the brightness of the led, & put both effects together to create a beautiful fade & light up effect.