from machine import Pin, I2C
import network
import BlynkLib
from BlynkTimer import BlynkTimer
from ssd1306 import SSD1306_I2C # OLED display library
from mpu6050 import MPU6050 # MPU6050 Accelerometer library
import onewire, ds18x20 # DS18B20 temperature sensor
import utime
import math
# === Blynk Template Configuration ===
BLYNK_TEMPLATE_ID = "TMPL3AFGTb6yt" # Do not change
BLYNK_TEMPLATE_NAME = "proj" # Do not change
BLYNK_AUTH = "c_sJX4Mq66dVx-Nbl_ztCNzWRHhvXVaO" # Do not change
# === WiFi Configuration ===
SSID = "Wokwi-GUEST"
PASSWORD = ""
# === Connect to WiFi ===
def connect_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
print("Connecting to WiFi...")
for _ in range(15): # Retry for ~15 seconds
if wlan.isconnected():
print("✅ Connected!")
print("IP Address:", wlan.ifconfig())
return True
utime.sleep(1)
print("❌ WiFi Connection Failed")
return False
if not connect_wifi(SSID, PASSWORD):
raise RuntimeError("WiFi connection failed! Check SSID/password or try again.")
# === Initialize Blynk ===
blynk = BlynkLib.Blynk(BLYNK_AUTH)
timer = BlynkTimer()
# === I2C Setup for OLED and MPU6050 ===
i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=400000)
oled = SSD1306_I2C(128, 64, i2c)
mpu = MPU6050(i2c)
# === DS18B20 Temperature Sensor Setup ===
ds_pin = Pin(15) # Change if needed
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
roms = ds_sensor.scan()
if not roms:
raise RuntimeError("No DS18B20 sensor found!")
# === Buzzer Setup ===
buzzer = Pin(14, Pin.OUT)
# === Accident & Temperature Thresholds ===
ACCIDENT_THRESHOLD = 1.5 # G-force threshold for impact detection
GYRO_THRESHOLD = 50 # Rotation threshold in degrees per second
TEMP_HIGH_THRESHOLD = 45.0 # High temperature alert (°C)
accident_detected = False
temp_alert_triggered = False
# === Blynk Connected Event ===
@blynk.on("connected")
def blynk_connected_handler():
print("✅ Connected to Blynk!")
blynk.virtual_write(0, "Smart Helmet Online")
# === Accident Alert Acknowledgment ===
@blynk.on("V0")
def v0_write_handler(value):
if value[0] == '1':
acknowledge_alert()
def acknowledge_alert():
print("✅ Emergency Alert Acknowledged!")
buzzer.value(0) # Turn off buzzer
oled.fill(0)
oled.text("ALERT ACKNOWLEDGED!", 10, 20)
oled.show()
blynk.log_event("helmet_alert", "🚨 Accident Alert Acknowledged!")
# === Main Loop ===
print("Starting Smart Helmet System...")
while True:
blynk.run()
timer.run()
try:
# === Read MPU6050 Data ===
accel = mpu.get_accel_data()
accel_magnitude = math.sqrt(accel['AcX']**2 + accel['AcY']**2 + accel['AcZ']**2) / 16384
# Read Gyroscope Data
gyro = mpu.get_gyro_data()
gyro_x, gyro_y, gyro_z = abs(gyro['GyX']), abs(gyro['GyY']), abs(gyro['GyZ'])
# === Read DS18B20 Temperature ===
ds_sensor.convert_temp()
utime.sleep(1) # Wait for conversion
temperature = ds_sensor.read_temp(roms[0]) # Read from the first sensor
# === Update OLED Display ===
oled.fill(0)
oled.text("Smart Helmet", 10, 10)
oled.text(f"Accel: {accel_magnitude:.2f}G", 10, 30)
oled.text(f"Temp: {temperature:.2f}C", 10, 50)
# === Accident Detection ===
if accel_magnitude > ACCIDENT_THRESHOLD or gyro_x > GYRO_THRESHOLD or gyro_y > GYRO_THRESHOLD or gyro_z > GYRO_THRESHOLD:
print("🚨 Accident Detected!")
buzzer.value(1)
oled.fill(0)
oled.text("!! ALERT !!", 30, 20)
oled.text("Accident Detected", 10, 40)
oled.show()
blynk.log_event("helmet_alert", "🚨 Accident Detected!")
accident_detected = True
utime.sleep(2)
else:
accident_detected = False
# === High Temperature Alert ===
if temperature > TEMP_HIGH_THRESHOLD and not temp_alert_triggered:
print("🔥 High Temperature Warning!")
oled.fill(0)
oled.text("🔥 TEMP ALERT!", 20, 20)
oled.text(f"Temp: {temperature:.2f}C", 10, 40)
oled.show()
blynk.virtual_write(1, f"🔥 High Temperature: {temperature:.2f}°C!")
blynk.log_event("helmet_temp_alert", f"🔥 High Temperature: {temperature:.2f}°C")
temp_alert_triggered = True
utime.sleep(2)
else:
temp_alert_triggered = False
oled.show()
utime.sleep(1)
except Exception as e:
print("Error in main loop:", e)
utime.sleep(2)