from machine import ADC, Pin, PWM
import time
import math
# Initialize ADC and LED
pot = ADC(26) # GP26
led = PWM(Pin(15, Pin.OUT))
led.freq(1000)
# Settings
threshold_db = 50
print_delta = 1.0 # Only print dB if it changes by this much
last_db = None
def read_db():
raw = pot.read_u16()
voltage_ratio = raw / 65535
if voltage_ratio < 0.0001:
voltage_ratio = 0.0001
db = int((voltage_ratio) * 80)
return db
while True:
current_db = read_db()
# Print only if there's a noticeable change
if (last_db is None) or (abs(current_db - last_db) >= print_delta):
print("Sound Level: {:.2f} dB".format(current_db))
if current_db > threshold_db:
print("Sound is very high")
last_db = current_db
# Alarm: flash LED if sound is loud
if current_db > threshold_db:
Print = current_db * 800
led.duty_u16(Print)
time.sleep(0.15)
else:
led.duty_u16(0)
time.sleep(0.15)