# Get started with Pulse Width Modulation (PWM)

## Summary

In this tutorial we will be experimenting with pulse width modulation. This pattern is used for controlling the current given to the board and you can set duration for high and low voltage.

### Requirements

• 1 x LOLIN D1 MINI PRO board
• 1 x Micro USB
• 2 x cables
• 1 x Buzzer / piezo speaker

## External Buzzer

This step should be easy if you completed the first tutorial.

• Connect the one end of your micro usb on your board and the other end to your computer.

• Open PuTTY and select Serial connection type.

• Use the appropriate Serial Line COM5 (same you did on Tutorial 1, if you don't remember it you can find it through device manager) and speed 115200 and click open.

### Create the following circuit

• Use the following code to check that your buzzer works

 1 2 3 4 5 6 7 from machine import Pin, PWM import time // you can set any freq you want up to 1000 to change the beeper sound beeper = PWM(Pin(14), freq=440, duty=512) time.sleep(0.5) // stops the buzzer beeper.deinit() 
• Now you can use the following code to see how you can play melodies with PWM changing the frequency of the voltage

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 from machine import Pin, PWM import time tempo = 5 // tones different frequency tones = { 'c': 262, 'd': 294, 'e': 330, 'f': 349, 'g': 392, 'a': 440, 'b': 494, 'C': 523, ' ': 0, } beeper = PWM(Pin(14, Pin.OUT), freq=440, duty=512) melody = 'cdefgabCbagfedc' rhythm = [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8] for tone, length in zip(melody, rhythm): beeper.freq(tones[tone]) time.sleep(tempo/length) //stop the beeper beeper.deinit() 

This is the end of Tutorial 6, you should now be able to control a buzzer and pwm.