Last active
February 18, 2024 06:31
-
-
Save omenlabs/3b795dc50e8ac985d6e8b4161131c613 to your computer and use it in GitHub Desktop.
Example code for driving the Sainsmart 16-Channel 9-36V USB Relay Module (Product 101-70-208)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Example code for driving the Sainsmart 16-Channel 9-36V USB Relay Module (Product 101-70-208) | |
Documents for this module were found at: | |
https://s3.amazonaws.com/s3.image.smart/download/101-70-208/101-70-208.zip | |
The protocol appears to be MODBUS ASCII: | |
https://en.wikipedia.org/wiki/Modbus#Protocol_versions | |
This script depends on python serial library: | |
https://pythonhosted.org/pyserial/ | |
""" | |
import serial | |
import time | |
def lrc(b): | |
b = bytearray.fromhex(b) | |
l = 0 | |
for i in b: | |
l = (l+i)&0xff | |
return ((l ^ 0xff) + 1) & 0xff | |
def cmd(relay, command): | |
on = "FE0500{:02X}{:02X}00".format(relay, command) | |
packet = ":{}{:02X}\r\n".format(on, lrc(on)) | |
return packet.encode('ascii') | |
def on_cmd(relay): | |
return cmd(relay, 0xFF) | |
def off_cmd(relay): | |
return cmd(relay, 0x00) | |
def all_on(): | |
return ":FE0F0000001002FFFFE3\r\n".encode('ascii') | |
def all_off(): | |
return ":FE0F00000010020000E1\r\n".encode('ascii') | |
def status(): | |
return ":FE0100000010F1\r\n".encode('ascii') | |
def main(): | |
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1) # open serial port | |
print("Status") | |
ser.write(status()) | |
print(ser.readline().hex()) | |
print("All On") | |
ser.write(all_on()) | |
print(ser.readline().hex()) | |
time.sleep(1) | |
print("All Off") | |
ser.write(all_off()) | |
print(ser.readline().hex()) | |
time.sleep(1) | |
for i in range(16): | |
print("Turning on relay {}".format(i)) | |
ser.write(on_cmd(i)) # write a string | |
time.sleep(.25) | |
for i in range(16): | |
print("Turning off relay {}".format(i)) | |
ser.write(off_cmd(i)) | |
time.sleep(.25) | |
ser.close() # close port | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment