PWM Output¶
The pins of the micro:bit board cannot output analog signal the way an audio amplifier can do it – by modulating the voltage on the pin.
Those pins can only either enable the full 3.3V output, or pull it down to 0V. However, it is still possible to control the brightness of LEDs or speed of an electric motor, by switching that voltage on and off very fast, and controlling how long it is on and how long it is off.
The technique is called PWM.
You can use PWM to drive analog output.
Each of the signals above has a different duty cycle, this is how is called the percentage of time that the PIN spends in the ON vs the OFF state in a given time interval.
Analog Write¶
To produce signals with different duty cycles we use the write_analog
function.
from microbit import *
pin1.set_analog_period(1)
while True:
for brightnessValue in range(0,1024,1):
pin1.write_analog(brightnessValue)
sleep(1)
for brightnessValue in range(1023,-1,-1):
pin1.write_analog(brightnessValue)
sleep(1)
-
The set_analog_period(milliseconds) function set the length of the PWM time interval
-
The write_analog is used to fade an LED connected to pin1, taking a number from 0 to 1023 as a brightness value. The value 0 corresponds to 0% duty cycle, while 1023 represents 100%.
In blocks you use analog write
to emit a PWM signal with a duty cycle from 0 to 100% (mapped to values 0..1023)
Control a Servo Motor¶
Servo write takes a number representing the rotation degrees from 0..180
In blocks you have:
While in Python you use the Servo
class, and the write_angle
function.
In this example we move the servo to 0, 90, 180 degress again and again
from microbit import *
from servo import Servo
while True:
Servo(pin0).write_angle(0)
sleep(200)
Servo(pin0).write_angle(90)
sleep(200)
Servo(pin0).write_angle(180)
sleep(200)
Fade an LED¶
We change the brightness value from 0 to 1023 and back
from microbit import *
pin1.set_analog_period(1)
while True:
for brightnessValue in range(0,1024,1):
pin1.write_analog(brightnessValue)
sleep(1)
for brightnessValue in range(1023,-1,-1):
pin1.write_analog(brightnessValue)
sleep(1)