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).
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.
anodePin = pyb.Pin(pyb.Pin.board.A5, pyb.Pin.OUT)
anodePin.high() # Turns the LED on
anodePin.low() # Turns the LED off
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.
from pyb import Pin, Timer
pin = Pin(pyb.pin.Board.D3)
timer = Timer(2, freq=1000) # Timer 2
channel = timer.channel(2, Timer.PWM, pin=pin) # Channel 2
#Turns the LED Off
#Turns the LED On dimly
#Turns the LED On a little brighter
#Turns the LED On fully bright