import network
import time
from machine import Pin, PWM, time_pulse_us
from umqtt.simple import MQTTClient
# WiFi details
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASSWORD = ''
# MQTT details
Mqtt_Broker = 'mqtt3.thingspeak.com'
Mqtt_Client = 'FgY0DwInJzQqKzchGiEtKjM'
Mqtt_Username = 'FgY0DwInJzQqKzchGiEtKjM'
Mqtt_Password = 'AI/s/7747+Y4PbAnL9XLKx+g'
Mqtt_Topic = 'channels/2491429/publish'
Write_API_Key = '4XJ64X5FBTY3NP0G'
# HC-SR04 sensor pins (replace 'your_trigger_pin' and 'your_echo_pin' with actual pin numbers)
trigger_pin = Pin(14, Pin.OUT)
echo_pin = Pin(5, Pin.IN)
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to network...')
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
pass
print('Network config:', wlan.ifconfig())
def measure_distance():
trigger_pin.off() # Ensure the trigger pin is low
time.sleep_us(2)
trigger_pin.on() # Send a 10us pulse
time.sleep_us(10)
trigger_pin.off()
duration = time_pulse_us(echo_pin, 1, 1000000) # Measure the duration of the echo pin being high
if duration < 0:
duration = 1000000 # Set a maximum value if no echo received
distance = (duration / 2) / 29.1 # Calculate the distance in cm
return distance
def send_thingspeak_mqtt(client, distance):
payload = "field1={}&api_key={}".format(distance, Write_API_Key)
client.publish(Mqtt_Topic, payload)
# Connect to WiFi
connect_to_wifi()
# Initialize MQTT client and connect
client = MQTTClient(Mqtt_Client, Mqtt_Broker, port=1883, user=Mqtt_Username, password=Mqtt_Password)
client.connect()
# Main loop
while True:
distance = measure_distance()
print('Measured Distance: {} cm'.format(distance))
send_thingspeak_mqtt(client, distance)
time.sleep(15) # ThingSpeak free account allows an update every 15 seconds