Skip to content

Instantly share code, notes, and snippets.

@c2h2
Created June 10, 2023 07:17
Show Gist options
  • Save c2h2/80532c6b6c30ff7e8e21947c0732ce61 to your computer and use it in GitHub Desktop.
Save c2h2/80532c6b6c30ff7e8e21947c0732ce61 to your computer and use it in GitHub Desktop.
import minimalmodbus
import time
import serial
import datetime
import redis
import pickle
rconn = redis.Redis('localhost')
instrument = minimalmodbus.Instrument('/dev/ttyUSB0', 1, debug=False) # port name, slave address (in decimal)
instrument.serial.port = '/dev/ttyUSB0' # this is the serial port name
instrument.serial.baudrate = 9600 # Baud
instrument.serial.bytesize = 8
instrument.serial.parity = serial.PARITY_NONE
instrument.serial.stopbits = 1
instrument.serial.timeout = 0.2 # seconds
instrument.address = 1 # this is the slave address number
instrument.mode = minimalmodbus.MODE_RTU # rtu or ascii mode
instrument.clear_buffers_before_each_transaction = True
def read_temp():
return instrument.read_registers(registeraddress=0, number_of_registers=1, functioncode= 3)
def read_humi():
return instrument.read_registers(registeraddress=11, number_of_registers=1, functioncode= 3)
time.sleep(1)
while True:
temp = None
humi = None
while True:
try:
temp = read_temp()
except:
print(".", end="")
if temp != None:
time.sleep(0.1)
break
time.sleep(0.2)
while True:
try:
humi = read_humi()
except:
print("*", end="")
if humi != None:
time.sleep(0.1)
break
t = temp[0]/10.0
h = humi[0]/10.0
ts = time.time()
rconn.set("temphumi", pickle.dumps({"temp":t,"humi":h,"time":ts}))
print(pickle.loads(rconn.get("temphumi")))
dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("\n"+dt+"|"+str(t)+"c, "+ str(h)+"%", end=" ")
time.sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment