import time
import math
from machine import ADC, Pin, I2C, PWM
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
import network
from BlinkLib import Blynk
# Define ADC pin for the microphone
mic_pin = ADC(Pin(34))
# Initialize I2C
i2c = I2C(0, sda=Pin(21), scl=Pin(22), freq=400000)
I2C_ADDR = 39
I2C_ROWS = 4
I2C_COLS = 20
lcd = I2cLcd(i2c, I2C_ADDR, I2C_ROWS, I2C_COLS)
# Define the noise threshold in dB
noise_threshold = 60 # Adjusted to 60 dB
# Microphone sensitivity (in dB per Volt) - replace with your microphone's sensitivity
MIC_SENSITIVITY = 3.0
# Define your Wi-Fi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
# Create a Blynk instance with your Blynk authentication token
blynk = Blynk("UeDZ-EmFytNWjjr8Mc3hgZXCDNo7rWfu")
# Initialize Wi-Fi
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASS)
# Wait until Wi-Fi connection is established
while not wifi.isconnected():
pass
# Function to calculate sound pressure level (SPL)
def calculate_noise_level(adc_value, reference_voltage, sensitivity):
# Calculate noise level in decibels (dB) based on sensitivity and voltage
noise_db = 20 * math.log10(adc_value / (reference_voltage * sensitivity))
return noise_db
# Function to update noise level
def update_noise_level():
global noise_level
# Read ADC values from the microphone
mic_value = mic_pin.read()
# Set a constant reference voltage based on your system's maximum voltage
reference_voltage = 5.0 # Assuming 5V maximum reference voltage
# Calculate noise level
noise_level = calculate_noise_level(mic_value, reference_voltage, MIC_SENSITIVITY) # Update noise_level directly
# Display the value on the LCD
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("Noise Level: {:.2f} dB".format(noise_level))
# Display the value on the Wokwi simulator screen
print("Noise Level: {:.2f} dB".format(noise_level))
# Main loop with continuous data transmission
while True:
# Update noise level
update_noise_level()
# Send the noise level to Blynk's Gauge widget (V0)
blynk.virtual_write("V0", noise_level)
# Delay for 2 seconds
time.sleep(2)