Created
November 23, 2022 15:59
-
-
Save BCadet/f47127756a0448500e8836be9214a745 to your computer and use it in GitHub Desktop.
simple python driver to communicate with USB relay module based on FTDI chip like https://www.sainsmart.com/products/4-channel-5v-usb-relay-module
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
from pyftdi.gpio import GpioController | |
import argparse | |
class FTDIRelays: | |
def __init__(self): | |
self._gpio = GpioController() | |
self._state = 0 # SW cache of the GPIO output lines | |
def pins(self): | |
print(self._gpio.direction) | |
def open(self, out_pins): | |
"""Open a GPIO connection, defining which pins are configured as | |
output and input""" | |
out_pins &= 0xFF | |
self._gpio.configure('ftdi:///1', direction=out_pins, frequency=1e3, | |
initial=0x0) | |
self._state = self._gpio.read_port() | |
print('%x' % self._state) | |
def close(self): | |
"""Close the GPIO connection""" | |
self._gpio.close() | |
def get_gpio(self, line): | |
"""Retrieve the level of a GPIO input pin | |
:param line: specify which GPIO to read out. | |
:return: True for high-level, False for low-level | |
""" | |
value = self._gpio.read_port() | |
print(value) | |
return bool(value & (1 << line)) | |
def set_gpio(self, line, on): | |
"""Set the level of a GPIO ouput pin. | |
:param line: specify which GPIO to madify. | |
:param on: a boolean value, True for high-level, False for low-level | |
""" | |
if on != 0: | |
state = self._state | (1 << line) | |
else: | |
state = self._state & ~(1 << line) | |
self._commit_state(state) | |
def _commit_state(self, state): | |
"""Update GPIO outputs | |
""" | |
self._gpio.write_port(state) | |
# do not update cache on error | |
self._state = state | |
print('%x' % self._state) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-r", "--relay", help="selected relay (start at 0)", type=int, default=0) | |
parser.add_argument("-v", "--value", help="value to apply to the relay", type=int, default=1) | |
args = parser.parse_args() | |
device = FTDIRelays() | |
device.open(0x0f) | |
print("set relay " + str(args.relay) + " to " + str(args.value)) | |
device.set_gpio(args.relay, args.value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment