We'll start off with the button circuit we created back in an earlier lesson. Make sure one leg of the button is connected to a GPIO pin, and the other to GND. Here, we have them connected to GPIO1 and GND.
00:00
Next, we'll connect the buzzer's GND pin to GND.
00:00
Finally, connect the positive end of the buzzer to GPIO14.
00:00
We start by importing Pin and PWM from the machine library. Then import the utime library. Next, initialise pulse-width modulation (PWM) on pin 14, which is connected to the buzzer. Here, it is assigned to the variable, buzzer.
00:00
Next, set the duty_u16 property of the buzzer object to 1000. Try adjusting the value and see what happens. When it is at 0, there will be no sound at all. Lower values means the sound from the buzzer will be quieter.
00:00
To set a half a second delay between the buzzer sounding on and off, set utime.sleep to 500ms.
00:00
Then, set duty_u16 to 0 so that the sound stops. Doing so, the buzzer will sound on and off. Otherwise, it won't stop sounding even after the program has finished executing. 

00:00
The alarm will only make a sound when the button has been pressed. When it is pressed, its value will be LOW or 0, and the following buzzer.duty_u16 and time.sleep commands will then execute. 

00:00
main.py
xxx
Terminal
screen /dev/tty.usbmodem0000000000001 115200
>>> led = Pin(25, Pin.OUT)
>>> from machine import Pin
Breadboard
Breadboard
Mark
© 2022 Chick Commerce Pty Ltd