import machine
import time
import network
import urequests # For HTTP requests
from machine import Pin, SoftI2C
from mpu6050 import MPU6050
import hcsr04
# Wi-Fi Credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ThingSpeak API
THINGSPEAK_API_KEY = "75X6XSW1F4XLKPXP"
THINGSPEAK_URL = "http://api.thingspeak.com/update?api_key=" + THINGSPEAK_API_KEY
# Ultrasonic Sensor Pins
TRIG_PIN = 5
ECHO_PIN = 18
ultrasonic_sensor = hcsr04.HCSR04(trigger_pin=TRIG_PIN, echo_pin=ECHO_PIN)
# IR Receiver Pin
IR_PIN = 4
ir_receiver = machine.Pin(IR_PIN, machine.Pin.IN)
# MPU6050 Setup (I2C)
i2c = SoftI2C(scl=machine.Pin(22), sda=machine.Pin(21))
mpu = MPU6050(i2c)
# Buzzer Pin
BUZZER_PIN = 15
buzzer = Pin(BUZZER_PIN, Pin.OUT)
# Connect to Wi-Fi
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(1)
print("Connected to WiFi:", wlan.ifconfig())
# Send data to ThingSpeak
def send_to_thingspeak(distance, accel, gyro):
url = THINGSPEAK_URL + "&field1={}&field2={}&field3={}&field4={}&field5={}&field6={}".format(
distance, accel[0], accel[1], accel[2], gyro[0], gyro[1])
response = urequests.get(url)
print("Response:", response.text)
response.close()
# Function to trigger the buzzer (alarm)
def trigger_alarm():
buzzer.value(1) # Turn on the buzzer
time.sleep(1) # Alarm duration
buzzer.value(0) # Turn off the buzzer
# Function to read Ultrasonic sensor
def read_ultrasonic():
distance = ultrasonic_sensor.distance_cm()
print("Distance:", distance, "cm")
return distance
# Function to read MPU6050 (Accelerometer + Gyroscope)
def read_mpu6050():
accel = mpu.accel
gyro = mpu.gyro
print("Accelerometer:", accel)
print("Gyroscope:", gyro)
return accel, gyro
# Function to read IR Receiver
def read_ir_receiver():
if ir_receiver.value() == 1:
print("IR signal detected!")
return True
return False
def main():
connect_to_wifi()
while True:
# Read sensors
distance = read_ultrasonic()
accel, gyro = read_mpu6050()
# Check if the object is out of the boundary
if distance > 50: # Example: boundary is 50 cm
print("Object is outside the boundary! Triggering alarm!")
trigger_alarm() # Trigger the buzzer
# Send data to ThingSpeak
send_to_thingspeak(distance, accel, gyro)
time.sleep(15) # ThingSpeak allows data upload every 15 seconds
if __name__ == "__main__":
main()