Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import serial
- import time
- import paho.mqtt.client as mqtt
- SERIAL_PORT = 'COM10'
- BAUD_RATE = 9600
- MQTT_BROKER = 'broker.emqx.io'
- MQTT_PORT = 1883
- MQTT_TOPIC = 'temperatura-arduino'
- client = mqtt.Client()
- def send_temperature_to_mqtt(temperature):
- client.publish(MQTT_TOPIC, temperature)
- print(f"Temperature sent to MQTT: {temperature} C")
- def on_connect(client, userdata, flags, rc):
- if rc == 0:
- print("Connected to MQTT broker")
- else:
- print("Failed to connect, return code:", rc)
- client.on_connect = on_connect
- client.connect(MQTT_BROKER, MQTT_PORT)
- ser = serial.Serial(SERIAL_PORT, BAUD_RATE)
- time.sleep(2)
- try:
- while True:
- if ser.in_waiting > 0:
- temperature = ser.readline().decode('utf-8').strip()
- print(f"Received temperature from serial: {temperature} C")
- send_temperature_to_mqtt(temperature)
- client.loop()
- time.sleep(1)
- except KeyboardInterrupt:
- print("Program interrupted. Closing...")
- finally:
- # Zamknij port szeregowy
- ser.close()
Add Comment
Please, Sign In to add comment