Introduction: USB Relay With Python: How to Guide

About: Hello! My name is FuzzyPotato, I have a passion for electronics, Python programming, and DIY projects. I have always been fascinated by the way things work, and I have a love for using technology to solve prob…

Hey there! Welcome to my instructable tutorial on how to control a USB relay using Python on Windows. If you've ever wondered how to automate your electrical devices or create cool projects with your computer, you're in the right place! In this guide, I'll walk you through the step-by-step process of setting up a USB relay and controlling it using the power of Python programming. Let's get started!

Supplies

To control the USB relay using Python, you'll need:

  1. USB relay
  2. USB Type A to USB Type B cable
  3. Windows computer with Python installed
  4. IDE (I'm using PyCharm)
  5. pywinusb library

With these supplies, you're all set to dive into the process of controlling a USB relay via a Python program. Let's get started!

Step 1: Setup

We will start by plugging the relay module into your PC.


  1. Connect the USB relay module: Plug in your USB relay module to your computer using the USB cable. Make sure that your relay module uses an external power supply that it is plugged in, failing to power externally may mean the relay doesn't have enough power to cycle. (Don't ask me how I know 😂) .
  2. Windows device detection: Windows should automatically detect the relay module. (You should see a popup that says something like "Relay2/4 device configured")


By following these steps, you'll have a relay module plugged in and ready to receive commands.

Step 2: Install Python Library

We will start by installing the pywinusb library.


  1. Open the pyCharm development environment (IDE).
  2. Navigate to File>Settings>Project>Python Interpreter
  3. Install the pywinusb library. (See image)
  4. Wait for the installation process to complete. You should see a message indicating a successful installation.


By following these steps, you'll have pywinusb installed and the relay module connected to your computer.

Step 3: The Code

Now that we have the pywinusb library installed, it's time to write the Python code that will allow us to control the relay.


  1. Create a new Python script.
  2. Copy and paste the following code:

import pywinusb.hid as hid
from time import sleep

USB_CFG_VENDOR_ID = 0x16c0 # Should suit, if not check ID with a tool like USBDeview
USB_CFG_DEVICE_ID = 0x05DF # Should suit, if not check ID with a tool like USBDeview

filter = None
hid_device = None
device = None
report = None

last_row_status = None


def get_Hid_USBRelay():
global filter, hid_device, device
filter = hid.HidDeviceFilter(vendor_id=USB_CFG_VENDOR_ID, product_id=USB_CFG_DEVICE_ID)
hid_device = filter.get_devices()
device = hid_device[0]


def open_device():
if device.is_active():
if not device.is_opened():
device.open()
get_report()
return True
else:
print("Device already opened")
return True
else:
print("Device is not active")
return False


def close_device():
if device.is_active():
if device.is_opened():
device.close()
return True
else:
print("Device already closed")
else:
print("Device is not active")
return True


def refresh():
get_Hid_USBRelay()
open_device()


def get_report():
global report
if not device.is_active():
report = None

for rep in device.find_output_reports() + device.find_feature_reports():
report = rep


def read_status_row():
global last_row_status
if report is None:
print("Cannot read report")
last_row_status = [0, 1, 0, 0, 0, 0, 0, 0, 3]
else:
last_row_status = report.get()
return last_row_status


def write_row_data(buffer):
if report is not None:
report.send(raw_data=buffer)
return True
else:
print("Cannot write in the report. check if your device is still plugged")
return False


def on_all():
if write_row_data(buffer=[0, 0xFE, 0, 0, 0, 0, 0, 0, 1]):
return read_relay_status(relay_number=3)
else:
print("Cannot put ON relays")
return False


def off_all():
if write_row_data(buffer=[0, 0xFC, 0, 0, 0, 0, 0, 0, 1]):
return read_relay_status(relay_number=3)
else:
print("Cannot put OFF relays")
return False


def on_relay(relay_number):
if write_row_data(buffer=[0, 0xFF, relay_number, 0, 0, 0, 0, 0, 1]):
return read_relay_status(relay_number)
else:
print("Cannot put ON relay number {}".format(relay_number))
return False


def off_relay(relay_number):
if write_row_data(buffer=[0, 0xFD, relay_number, 0, 0, 0, 0, 0, 1]):
return read_relay_status(relay_number)
else:
print("Cannot put OFF relay number {}".format(relay_number))
return False


def read_relay_status(relay_number):
buffer = read_status_row()
return relay_number & buffer[8]


def is_relay_on(relay_number):
return read_relay_status(relay_number) > 0


get_Hid_USBRelay()
open_device()


print(" --- read_status_row: {}".format(read_status_row()))
print("TURN OFF ALL: {}".format(off_all()))


print("TURN ON 1: {} ".format(on_relay(1)))
print("READ STATE 1: {}".format(read_relay_status(1)))
sleep(1)
print("TURN OFF 1: {} ".format(off_relay(1)))
print("READ STATE 1: {}".format(read_relay_status(1)))
sleep(1)

print("TURN ON ALL: {}".format(on_all()))
sleep(1)
print("TURN OFF ALL: {}".format(off_all()))


Now you have the Python code to control a USB relay. In the next steps, we'll execute the code and see the relays in action.

Step 4: Testing

Now that we have the Python code ready, let's test it to see if we can control the USB relay successfully.


Run the Python script.

The script will perform the following actions:

  • It will turn off all the relays initially by calling the off_all() function.
  • Then it will turn on relay 1 using the on_relay(1) function and check its status using read_relay_status(1).
  • After a 1-second delay, it will turn off relay 1 using the off_relay(1) function and check its status again.
  • It will turn on all the relays using the on_all() function and wait for 1 second.
  • Finally, it will turn off all the relays using the off_all() function.

Observe the changes in the relay status during the script execution. If everything is working correctly, you should see and hear the relays turning on and off as expected.


Congratulations! You have successfully tested the USB relay control using Python. You can now integrate this code into your own projects or explore further possibilities with USB relays and Python programming.