Micropython Lesson 3: Working with Analog Write
Micropython Lesson 3

Working with Analog Write

Use PWM to control the brightness of a LED

Components Required



In this example, you are learning how to turn on and off a LED or any other actuator which can be controlled by a digital output such as relay, bulb, motor.

Learning Outcomes

From this example, you’ll get an understanding about,
  • Pulse Width Modulation
Click here


To change the brightness of a LED, we could change the voltage the LED is supplied with. But in a microcontroller, the 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 at 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.

Pulse Width Modulation

In this example, a higher Duty cycle gives higher brightness & the lower duty cycle gives lower brightness.


Let us select green LED (which is wired to D16). We will use a for loop to generate the duty cycle (0 — 0% duty, 255-100% duty). And also to generate 255 cycles.



from machine import Pin,PWM
import time
LED=Pin(16, Pin.OUT)
pwm = PWM(LED)
while True:
  for i in range (0,256,1):


for i in range (0,256,1): There are 3 parameters in a for loop, the first parameter we are defining is the starting value for the loop. The second parameter specifies the ending value for the loop, the third parameter specifies the change that 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.

Related Posts
Leave a Reply