import machine
import utime
import network
import urequests
# Configure pins
trig_pin = machine.Pin(4, machine.Pin.OUT)
echo_pin = machine.Pin(5, machine.Pin.IN)
buzzer_pin = machine.Pin(2, machine.Pin.OUT)
pir_sensor_pin = machine.Pin(27, machine.Pin.IN)
potentiometer_pin = machine.ADC(26) # ADC pin on GP26
red_led_pin = machine.Pin(18, machine.Pin.OUT)
yellow_led_pin = machine.Pin(19, machine.Pin.OUT)
green_led_pin = machine.Pin(20, machine.Pin.OUT)
# Thingspeak API key and URL
api_key = "4919MY9UE360KNLQ"
thingspeak_url = "https://api.thingspeak.com/update"
# Connect to Wokwi Guest WiFi
ssid = "Wokwi-Guest"
password = ""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
utime.sleep(1)
print("Connected to Wokwi Guest WiFi")
# Motion counting variables
motion_count = 0
start_time = 0
counting_duration = 10 # in seconds
def measure_distance():
# Trigger ultrasonic sensor
trig_pin.on()
utime.sleep_us(10)
trig_pin.off()
# Measure echo pulse duration
pulse_start = utime.ticks_us()
while echo_pin.value() == 0:
pulse_start = utime.ticks_us()
while echo_pin.value() == 1:
pulse_end = utime.ticks_us()
pulse_duration = pulse_end - pulse_start
# Convert pulse duration to distance (in cm)
distance = pulse_duration * 0.034 / 2
return distance
def read_potentiometer():
# Read potentiometer value
pot_value = potentiometer_pin.read_u16()
# Map potentiometer value to LED ranges
if pot_value < 10000:
green_led_pin.on()
yellow_led_pin.off()
red_led_pin.off()
elif 10000 <= pot_value < 20000:
green_led_pin.off()
yellow_led_pin.on()
red_led_pin.off()
else:
green_led_pin.off()
yellow_led_pin.off()
red_led_pin.on()
return pot_value
def send_to_thingspeak(distance, pot_value, motion_count):
# Prepare Thingspeak data
data = {"api_key": api_key, "field1": distance, "field2": pot_value, "field3": motion_count}
# Send HTTP POST request to Thingspeak
response = urequests.post(thingspeak_url, json=data)
if response.status_code == 200:
print("Data sent to Thingspeak successfully")
else:
print("Failed to send data to Thingspeak")
response.close()
try:
while True:
distance = measure_distance()
print("Distance: {} cm".format(distance))
pot_value = read_potentiometer()
print("Potentiometer Value: {}".format(pot_value))
if distance < 50:
buzzer_pin.on() # Activate buzzer if distance is less than 50
else:
buzzer_pin.off()
if pir_sensor_pin.value(): # Motion detected
if start_time == 0:
start_time = utime.time()
motion_count += 1
elif start_time != 0 and utime.time() - start_time >= counting_duration:
# Send data to Thingspeak and reset variables
send_to_thingspeak(distance, pot_value, motion_count)
print("Motion Count: {}".format(motion_count))
motion_count = 0
start_time = 0
utime.sleep(10) # Delay between measurements
except KeyboardInterrupt:
print("\nProgram terminated by user")
wlan.disconnect()
wlan.active(False)