from umqtt.simple import MQTTClient # Import MQTT client library
import network # Import network library for WiFi connection
import machine, time
# Initialize pins
trigger = machine.Pin(5, machine.Pin.OUT)
echo = machine.Pin(18, machine.Pin.IN)
# WiFi credentials
ssid = 'Wokwi-GUEST' # Your WiFi SSID
password = '' # Your WiFi password
# ThingSpeak MQTT settings
mqtt_server = "mqtt3.thingspeak.com" # ThingSpeak MQTT server address
channel_id = "2495162" # Your ThingSpeak Channel ID
write_api_key = "KSJFGA0HWGPVZYOS" # Your ThingSpeak channel write API key
client_id = "HQ47ExsZMwwNITA5AgwzCTs" # Client ID for MQTT connection (can be empty)
mqtt_user = "HQ47ExsZMwwNITA5AgwzCTs"
mqtt_password = "Iotf27skR4Lp6yxZLR9v/mPu"
# Connect to WiFi
station = network.WLAN(network.STA_IF) # Create a station interface for WiFi connection
station.active(True) # Activate the station interface
station.connect(ssid, password) # Connect to the WiFi network
while station.isconnected() == False: # Wait until the connection is successful
pass
print("Connection successful")
def measure_distance():
trigger.value(0) # Set trigger low
time.sleep_us(2) # Settle the sensor
trigger.value(1) # Set trigger high
time.sleep_us(10) # Send out an ultrasonic pulse
trigger.value(0)
while echo.value() == 0:
signal_off = time.ticks_us()
while echo.value() == 1:
signal_on = time.ticks_us()
time_passed = signal_on - signal_off
distance = (time_passed * 0.0343) / 2
return distance
def send_to_thingspeak(distance):
client = MQTTClient(client_id, mqtt_server, user=mqtt_user, password=mqtt_password)
client.connect() # Connect to the MQTT server
client.publish("channels/2495162/publish/fields/field1", str(distance)) # Publish payload to the specified channel
client.disconnect() # Disconnect from the MQTT server
while True:
distance = measure_distance() # Measure distance using the ultrasonic sensor
send_to_thingspeak(distance) # Send the measured distance to ThingSpeak
print("Sent distance:", distance, "to ThingSpeak") # Print confirmation message
time.sleep(5) # Delay between posts due to ThingSpeak's rate limit