We’re going to now use the last circuit to learn about duty cycle simply by tuning our code.
1 Metro M0 Express
1 breadboard
7 wires
2 resistors (330 ohms)
1 LED light
1 push button
Follow the circuit diagram provided to wire the Metro M0 Express. (Same circuit as "Blinking LED and Button").
4 pin push button
2 pin push button
import time
import board
import pulseio
from digitalio import DigitalInOut, Direction, Pull
import simpleio
led = pulseio.PWMOut(board.D13, frequency=5000, duty_cycle=0)
button = DigitalInOut(__________)
button.direction = Direction.__________
button.pull = Pull.UP
buttonState = False
ledState = False
count = -1
dutycycle = 0
button_out = [0, 13101, 26209, 39318, 52426, 65535, 0]
while True:
buttonState = button.value
if buttonState:
count = count + 1
led.duty_cycle = button_out[count]
print(led.duty_cycle)
dutycycle = round(simpleio.map_range(button_out[count], 0, 65535, 0, 100))
print("Duty Cycle:", dutycycle, "%")
time.sleep(0.3)
if count == 6:
count = 0
Note: analog output range is 0 to 65535 (16 bit)
Note 2: Some students have reported issues using pulseio, so if that doesn't work, try changing all instances of pulseio to pwmio.
import time
import board
import pulseio
from digitalio import DigitalInOut, Direction, Pull
import simpleio
led = pulseio.PWMOut(board.D13, frequency=5000, duty_cycle=0)
button = DigitalInOut(board.D2)
button.direction = Direction.INPUT
button.pull = Pull.UP
buttonState = False
ledState = False
count = -1
dutycycle = 0
button_out = [0, 13101, 26209, 39318, 52426, 65535, 0]
while True:
buttonState = button.value
if buttonState:
count = count + 1
led.duty_cycle = button_out[count]
print(led.duty_cycle)
dutycycle = round(simpleio.map_range(button_out[count], 0, 65535, 0, 100))
print("Duty Cycle:", dutycycle, "%")
time.sleep(0.3)
if count == 6:
count = 0