Controlling an LED with MicroPython

Powering an LED with a MicroPython embedded board is extremely easy with only a few lines of code.  This can be achieved using the REPL or by writing code to main.py.  In this example we will use the REPL to turn on and off the LED, as well as change the brightness using pulse width modulation (PWM).

Circuit Schematic

The anode of a the LED is connected to a 100Ω resistor and then connected to one of the Analog GPIO pins of the microcontroller.  The cathode of the LED is connected to a ground pin of the microcontroller.  In the example below, the LED is connected to the A5 pin of a STM32 Nucleo board.

Turning the LED on/off

The LED can be turned on and off by configuring the anode pin as a digital output pin.  To do so, use the pyb.Pin() method.  The first argument to the Pin() method is the GPIO pin name, and the second argument is the pin mode.  The pin mode “OUTPUT” will configure the pin as a digital output, where Pin.high() outputs 3.3V and Pin.low() outputs 0V.  Note:  In future versions of MicroPython, the pyb module will be replaced by the machine module.

Changing LED Brightness using PWM

The brightness of the LED can be controlled by changing the voltage to the anode.  This can be accomplished using two methods: by using pulse width modulation (PWM)or by using an digital-analog converter (DAC).  For this example, we will be using PWM to accomplish brightness control.

To use PWM in MicroPython, we will need both a Pin object and a Timer object.  We must use a GPIO pin that has a timer function, this can be determined in the user manual specific for your board.  For example, with the STM32 Nucleo L476RG, the user manual is located here, and on  page 53 we can see that pin D3 has the TIM2_CH2 function.  Change your circuit to reflect this: move the anode of the LED to Pin D3.

Now we can create the Pin and Timer object to control the LED.  Reset your microcontroller, and enter the following into the REPL.  You can determine the correct timer number and channel number from the data table.  Recall, we are using Pin D3, which has function TIM2_CH2: Timer 2 Channel 2.  With the channel.pulse_width_percent method, you can enter a PWM percent between 0-100.