import time
from machine import Pin, time_pulse_us, ADC
from time import sleep_us
from umqtt.simple import MQTTClient
import network
time.sleep(0.1) # Wait for USB to become ready
#thingspeak mqtt broker info
MQTT_BROKER = "mqtt3.thingspeak.com"
MQTT_PORT = 1883
MQTT_CLIENT_ID = "BwErAhwWOCY9ES87Kjg5KzE"
MQTT_USERNAME = "BwErAhwWOCY9ES87Kjg5KzE"
MQTT_PASSWORD = "yuPno0sE68UQTb1ieN2eEc16"
CHANNEL_ID = "2447204"
PUBLISH_TOPIC = f"channels/{CHANNEL_ID}/publish"
print("Hello, Pi Pico!")
slide = ADC(Pin(34, Pin.IN))
#wifi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ''
#connect to wifi, 5 attempts
def connect_wifi():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
return True
wifi_connected = connect_wifi()
#connect to MQTT broker
def connect_mqtt():
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=MQTT_PORT, user=MQTT_USERNAME, password=MQTT_PASSWORD)
client.connect()
print("Connected to MQTT Broker")
return client
#publish to thingspeak using MQTT
def publish_to_thingspeak(client, potent):
message = f"field1={potent}"
client.publish(PUBLISH_TOPIC, message)
print("Published to ThingSpeak via MQTT")
while True:
potent = slide.read()
print("Potent:", potent)
mqtt_client = connect_mqtt()
publish_to_thingspeak(mqtt_client, potent)
time.sleep(10)