Micropython Lesson 3
Working with Analog Write
Use PWM to control the brightness of a LED
- Pulse Width Modulation
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.
from machine import Pin,PWM import time LED=Pin(16, Pin.OUT) pwm = PWM(LED) pwm.freq(50) while True: for i in range (0,256,1): pwm.duty(i) time.sleep_ms(500)
for i in range (0,256,1): There are 3 parameters in a for loop, first parameter we are defining the starting value for the loop. Second parameter specifies the ending value for the loop, third parameter specifies the change happens to the variable in each cycle, in this i is incremented by one.
pwm.duty(i) You can input the pin number you need to do pwm and then the pwm value you need to give to that pin. This assigns the corresponding duty cycle to the pin.
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.