# ESP32 and Mycropython: Programming your Hardware
# Author: Mordechai Bar Natan
#
# Lesson 6: Add a buzzer
# https://wokwi.com/projects/394062775671206913
#
# Remember:
# On a LED, the long leg is the anode (+). Connect it to pin #2.
# The short leg is the cathode (-). Connect it to GND.
# On a momentary switch (button), connect one side to pin #4 and the other side to GND.
# The display has 4 connections: GND, VCC (to 3.3V), SCL (pin #22) & SDA (pin #21).
# The + on the buzzer connects to pin #23 on the ESP32.
#
# References
# https://docs.micropython.org/en/latest/library/machine.Pin.html
# https://docs.micropython.org/en/latest/esp8266/tutorial/ssd1306.html#ssd1306
# https://docs.micropython.org/en/latest/esp32/quickref.html#pwm-pulse-width-modulation
# https://micropython-on-wemos-d1-mini.readthedocs.io/en/latest/basics.html#beepers
from machine import Pin, SoftI2C, ADC, PWM
from time import sleep, sleep_ms
from ssd1306 import SSD1306_I2C
oled_scl_pin = 22 # Orange cable
oled_sda_pin = 21 # Blue cable
red_led_pin = 2
blue_led_pin = 15
left_button_pin = 4
right_button_pin = 17
buzzer_pin = 23 # Purple cable
i2c = SoftI2C(scl=Pin(oled_scl_pin), sda=Pin(oled_sda_pin), freq=4000000)
oled_w = 128 # display width (0..127)
oled_h = 64 # display hight (0..63)
oled = SSD1306_I2C(oled_w, oled_h, i2c) # oled will be the display bject
red_led = Pin(red_led_pin, Pin.OUT)
blue_led = Pin(blue_led_pin, Pin.OUT)
left_button = Pin(left_button_pin, Pin.IN, Pin.PULL_UP)
right_button = Pin(right_button_pin, Pin.IN, Pin.PULL_UP)
red_led_state = 0
blue_led_state = 0
left_button_state = 0
right_button_state = 0
def play_note(note=1047, duration_ms=100, active_duty=200): # use my default values
buzzer = PWM(Pin(buzzer_pin, Pin.OUT)) # need PWM to generate (modulate) tones
buzzer.freq(note) # tune
buzzer.duty(active_duty) # duty of 50 is ok, more than 300 is distorted, just try
sleep_ms(duration_ms) # tone duration
buzzer.duty(0) # Turn off the buzzer
buzzer.deinit() # deinitialize the object
oled.fill(0) # clear the display
oled.text('RED LED OFF', 10, 10, 1) # some text at x=10, y=10, colour=1 (def colour)
oled.text('BLUE LED OFF', 10, 20) # some text at x=10, y=20
oled.show() # show the display
# toggle the LED when the button is pressed
while True:
left_button_last_state = left_button_state
left_button_state = left_button.value()
if left_button_state == 0 and left_button_last_state == 1:
red_led_state = not(red_led_state)
red_led.value(red_led_state)
play_note()
right_button_last_state = right_button_state
right_button_state = right_button.value()
if right_button_state == 0 and right_button_last_state == 1:
blue_led_state = not(blue_led_state)
blue_led.value(blue_led_state)
play_note()
oled.fill(0)
if red_led.value() == True:
oled.text('RED LED ON', 10, 10)
else:
oled.text('RED LED OFF', 10, 10)
if blue_led.value() == True:
oled.text('BLUE LED ON', 10, 20)
else:
oled.text('BLUE LED OFF', 10, 20)
oled.show()
sleep(0.1)