print("Ahmad Zuhairi Bin Wahidudin")
print("51220122074")
import machine
import time
from machine import Pin, SoftI2C,PWM
import ssd1306
BUZZER_PIN = 13
BUZZER_CHANNEL = 0
# Define musical notes in Hertz
NOTE_C = 262
NOTE_D = 294
NOTE_E = 330
NOTE_F = 349
NOTE_G = 392
NOTE_A = 440
NOTE_B = 494
oled_width = 128 #based on spec
oled_height = 64 #based on spec
# Setup button pins as input with pull-up resistor
button1 = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
button2 = machine.Pin(18, machine.Pin.IN, machine.Pin.PULL_UP)
button3 = machine.Pin(19, machine.Pin.IN, machine.Pin.PULL_UP)
button4 = machine.Pin(2, machine.Pin.IN, machine.Pin.PULL_UP)
# Setup LED pins as output
led1 = machine.Pin(14, machine.Pin.OUT)
led2 = machine.Pin(27, machine.Pin.OUT)
led3 = machine.Pin(26, machine.Pin.OUT)
led4 = machine.Pin(25, machine.Pin.OUT)
# Setup PWM output for the buzzer
buzzer = machine.PWM(machine.Pin(BUZZER_PIN))
buzzer.freq(440) # Set initial frequency to A4 note (440 Hz)
# Setup I2C bus and OLED display
i2c_oled = SoftI2C(scl=Pin(22), sda=Pin(3))
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_oled)
while True:
# Read button states
b1 = button1.value()
b2 = button2.value()
b3 = button3.value()
b4 = button4.value()
if b1 == 0:
led1.on() # Turn on LED 1
buzzer.freq(NOTE_D)
buzzer.duty(512) # Set duty cycle to 50% (half of the maximum)
oled.fill(0)
oled.text("Note: D", 0, 0)
oled.show()
time.sleep(0.01) # Play note for 10 ms
led1.off() # Turn off LED 1
elif b2 == 0:
led2.on() # Turn on LED 2
buzzer.freq(NOTE_A)
buzzer.duty(512)
oled.fill(0)
oled.text("Note: A", 0, 0)
oled.show()
time.sleep(0.01)
led2.off() # Turn off LED 2
elif b3 == 0:
led3.on() # Turn on LED 3
buzzer.freq(NOTE_G)
buzzer.duty(512)
oled.fill(0)
oled.text("Note: G", 0, 0)
oled.show()
time.sleep(0.01)
led3.off() # Turn off LED 3
elif b4 == 0:
led4.on() # Turn on LED 4
buzzer.freq(NOTE_A)
buzzer.duty(512)
time.sleep(0.15)
buzzer.freq(NOTE_B)
buzzer.duty(512)
time.sleep(0.02)
buzzer.freq(NOTE_C)
buzzer.duty(512)
time.sleep(0.02)
buzzer.freq(NOTE_D)
buzzer.duty(512)
time.sleep(0.02)
buzzer.freq(NOTE_E)
buzzer.duty(512)
time.sleep(0.02)
buzzer.freq(NOTE_A)
buzzer.duty(384) # Set duty cycle to 37.5% (3/8 of the maximum)
time.sleep(0.03)
buzzer.freq(NOTE_C)
buzzer.duty(512)
time.sleep(0.02)
buzzer.freq(NOTE_C)
buzzer.duty(576) # Set duty cycle to 56.25% (9/16 of the maximum)
time.sleep(0.02)
buzzer.freq(NOTE_F)
buzzer.duty(512)
time
led4.off() # Turn off LED 4
else:
buzzer.duty(0) # Turn off the buzzer
time.sleep(0.01)