Buzzer - Writing the code#
Write up the code found below.
import board
import pwmio
import time
import math
import digitalio
buzzer = pwmio.PWMOut(board.GP0, variable_frequency = True)
button = digitalio.DigitalInOut(board.GP1)
button.direction = digitalio.Direction.INPUT
runtime = 0
button_press = False
while True:
if button.value == True:
if not button_press:
runtime = time.monotonic()
button_press = True
for val in range(360):
sinval = math.sin(val*(math.pi/180))
buzzer.frequency = 500 + int(300*(sinval))
time.sleep(0.001)
elapsed = time.monotonic() - runtime
if elapsed < 3:
buzzer.duty_cycle = int(0.2*65535) # e operates like **
elif elapsed >= 3 and elapsed < 6:
buzzer.duty_cycle = int(0.3*65535)
elif elapsed >= 6 and elapsed < 9:
buzzer.duty_cycle = int(0.4*65535)
else:
buzzer.duty_cycle = int(0.5*65535)
else:
buzzer.duty_cycle = 0
button_press = False
If all is well, you should find the buzzer emits a siren sound when the button is pressed. This sound should get increasingly loud as you hold the button.
We are again using pulse width modulation here, allowing us to vary the sound output from the buzzer. However, as here we are looking to also change the frequency of the signal, we have to include the extra argument variable_frequency = True
in the pwmio.PWMOut()
function.
int led = 13 //set the pin number
int button = 3 //set the button pin number
// the setup function runs once when you press reset or power the board
void setup() {
pinMODE(led, OUTPUT);
pinMODE(button, INPUT); //button is an input
}
// the loop function runs over and over again forever
void loop() {
int state - digitalRead(button); //read the state of the button (ON/OFF)
if (state == HIGH){
digitalWrite(led,HIGH);
}
else{
digitalWrite(led,LOW);
}
}
If all is well, you should find the buzzer emits a siren sound when the button is pressed. This sound should get increasingly loud as you hold the button.
We are again using pulse width modulation here, allowing us to vary the sound output from the buzzer. However, as here we are looking to also change the frequency of the signal, we have to include the extra arguments.
Using Math#
You will see also that we have imported a new module math. This module allows us to use a range of more complex mathematical functions such as trigonometric functions, exponentials and more.
See more
For more details on the functions included in math
and how to use them, check the documentation here.
In this case we are making use of the math.sin()
function, which takes a number in radians and returns the sine of that number.
Using for val in range(360):
we can generate a full range of sine values for integers between 0 and 360\(^{\circ}\) (or 2\(\pi\) rad).
Then 500 + int(300*(sinval))
allows us to transform our sine values into integers betweem 200 and 800.
You will see also that we have imported a new library math. This library allows us to use a range of more complex mathematical functions such as trigonometric functions, exponentials and more.
In this case we are making use of the math.sin()
function, which takes a number in radians and returns the sine of that number.
Using for val in range(360):
we can generate a full range of sine values for integers between 0 and 360\(^{\circ}\) (or 2\(\pi\) rad).
Then 500 + int(300*(sinval))
allows us to transform our sine values into integers betweem 200 and 800.
At each iteration, we set the frequency equal to the transformed sine value. This means that as we pass through the iterations in the for statement, the frequency will oscillate between 200Hz and 800Hz - giving us a familiar siren noise.
Note
The time.sleep(0.001)
function slows down iterations very slightly to ensure that the frequency isn’t changing too quickly.
More conditionals#
Having created and set a range of frequency values to cycle over - we use a different method to determine the buzzer’s duty cycle and thus its loudness.
We can extend the if/else structure seen before to if/elif/else. Using elif, we can introduce additional conditions into our code.

Fig. 7.5 Logical structure of if/elif/else conditionals.#
Using our code as an example, rather than just having a response for elapsed < 4
and elapsed >= 4
, with elif we can introduce additional responses for intermediate values of elapsed
.
We also see that we can happily use conditionals within other conditionals:
if button.value == True:
if not button_press:
runtime = time.monotonic()
button_press = True
This block of code first checks whether the button is pressed, and then checks that the button wasn’t already being pressed (if not button_press
is equivalent to if button_press == False
).
If both these conditions are satisfied, it updates the value of runningtime
so that it can store the time the button was first pressed.