-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
54 lines (46 loc) · 1.49 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from machine import UART, Pin
import network
import time
from umqtt.simple import MQTTClient
# Configure your WiFi and MQTT details
WIFI_SSID = "ssid"
WIFI_PASSWORD = "password"
MQTT_BROKER = "broker"
MQTT_TOPIC = "topic"
MQTT_USER = "user"
MQTT_PASSWORD = "pass"
# Set up UART
uart = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))
# Set up WiFi connection (ESP8266 module or compatible is required for Pico)
def connect_wifi():
import network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
print("Connecting to WiFi...")
time.sleep(1)
print("Connected to WiFi:", wlan.ifconfig())
# Set up MQTT
def connect_mqtt():
client = MQTTClient("barcode scanner", MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected to MQTT Broker")
return client
# Main loop to read from UART and publish to MQTT
def main():
connect_wifi()
client = connect_mqtt()
while True:
if uart.any():
barcode_data = uart.read().decode('utf-8').strip()
print("Received barcode:", barcode_data)
client.connect()
client.publish(MQTT_TOPIC, barcode_data)
client.disconnect()
print(f"Published barcode data '{barcode_data}' to MQTT topic '{MQTT_TOPIC}'")
time.sleep(1) # Small delay to avoid multiple rapid scans
try:
main()
except KeyboardInterrupt:
print("Stopped by user")