jdz/modbus.py

69 lines
1.8 KiB
Python
Raw Normal View History

2024-07-05 15:05:28 +00:00
import minimalmodbus
import time, os
import serial
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
# MQTT Broker settings
mqttBroker ="65.108.199.212"
myhost = os.uname()[1]
client = mqtt.Client(myhost)
client.connect(mqttBroker, 1883)
# Modbus configuration
mb_address = 1 # Modbus address
sensy_boi = minimalmodbus.Instrument('/dev/ttyUSB0', mb_address)
sensy_boi.serial.baudrate = 9600
sensy_boi.serial.bytesize = 8
sensy_boi.serial.parity = minimalmodbus.serial.PARITY_NONE
sensy_boi.serial.stopbits = 1
sensy_boi.serial.timeout = 0.5
sensy_boi.mode = minimalmodbus.MODE_RTU
# Configure buffer clearing and port closing settings
sensy_boi.clear_buffers_before_each_transaction = True
sensy_boi.close_port_after_each_call = True
# GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
try:
while True:
if GPIO.input(17) == GPIO.HIGH:
print("Adquiriendo datos...")
# Read data from multiple registers
data = sensy_boi.read_registers(0, 2, 3)
print("")
print(f"Datos crudos {data}")
# Process the raw data
hum = data[0] / 10
temp = data[1] / 10
client.publish("iiot/"+ myhost +"/temperature", temp)
client.publish("iiot/"+ myhost +"/humidity", hum)
# Print the processed data
print("-------------------------------------")
print(f"Temperatura = {temp}\u00B0C")
print(f"Humedad relativa = {hum}%")
print("-------------------------------------")
print("")
2024-07-11 20:10:55 +00:00
time.sleep(1.5)
2024-07-05 15:05:28 +00:00
except KeyboardInterrupt:
print("Programa terminado por el usuario")
except Exception as e:
print(f"Error: {str(e)}")
finally:
GPIO.cleanup()
2024-07-11 20:10:55 +00:00
print("Programa finalizado")