USB Relay Modules are versatile devices used for switching electrical circuits on and off remotely. These modules are commonly used in home automation, IoT projects, and laboratory setups. However, managing them via command-line tools or scripts can be tedious, especially when remote access is needed.
This article demonstrates how to integrate USB Relay Modules with a simple web interface using Python, pyserial
, and Flask. By following this guide, you’ll create a user-friendly control panel that allows you to manage your relay module from any device on the network.
Table of Contents
Setting Up the Environment
Prerequisites:
- A USB Relay Module connected to your Ubuntu system.
- Python 3 installed on your machine.
pyserial
and Flask Python libraries installed.
Install the required libraries:
pip install pyserial flask
For a comprehensive instruction on PySerial and installation procedure, check How to Control a USB Relay Module Using Python on Linux and macOS and if you are encountering Ubuntu’s Ubuntu’s Externally-Managed-Environment Policy, this article may help.
Serial Communication Basics
USB Relay Modules are controlled using specific commands sent through a serial interface. These commands usually follow a format such as:
- ON:
[Header, Channel, ON-State, Checksum]
- OFF:
[Header, Channel, OFF-State, Checksum]
For instance:
- Turn relay 1 ON:
0xA0, 0x01, 0x01, 0xA2
- Turn relay 1 OFF:
0xA0, 0x01, 0x00, 0xA1
Implementing the Web Interface
Python Flask Script
Here’s the complete Flask app for controlling your USB relay module:
from flask import Flask, render_template, request
import serial
import time
# Initialize Flask app
app = Flask(__name__)
# Serial connection setup
SERIAL_PORT = "/dev/ttyUSB0" # Replace with your device path
BAUD_RATE = 9600
TIMEOUT = 1
def send_command(command):
"""Send a command to the USB relay."""
try:
with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=TIMEOUT) as ser:
ser.write(command)
time.sleep(0.1) # Small delay to ensure the command is sent
return True
except Exception as e:
print(f"Error: {e}")
return False
@app.route('/')
def index():
return render_template('index.html')
@app.route('/control', methods=['POST'])
def control():
channel = int(request.form['channel'])
action = request.form['action']
if action == 'on':
success = send_command(bytes([0xA0, channel, 0x01, 0xA2]))
else:
success = send_command(bytes([0xA0, channel, 0x00, 0xA1]))
if success:
return f"Relay {channel} {action.upper()}"
else:
return "Error: Unable to connect to relay"
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=5000)
HTML Control Panel
Create an index.html
file for the control panel:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>USB Relay Control</title>
</head>
<body>
<h1>Control USB Relay Modules</h1>
<form action="/control" method="post">
<label for="channel">Channel:</label>
<input type="number" name="channel" id="channel" min="1" max="8" required>
<br>
<label for="action">Action:</label>
<select name="action" id="action" required>
<option value="on">Turn ON</option>
<option value="off">Turn OFF</option>
</select>
<br><br>
<button type="submit">Send Command</button>
</form>
</body>
</html>
Running the App
Save the Python script as app.py
and the HTML file in a folder named templates
.
Start the Flask app:
python3 app.py
Access the web interface by visiting http://<your-ip-address>:5000
from any device on the network.
Use Cases for USB Relay Modules
Use Case | Description |
---|---|
Home Automation | Control lights, fans, or other appliances. |
IoT Projects | Integrate with sensors and actuators. |
Laboratory Experiments | Automate equipment in controlled experiments. |
Industrial Automation | Manage machinery or tools remotely. |
Conclusion
Integrating USB Relay Modules with a web interface makes them accessible and easy to use from anywhere on your network. By leveraging pyserial
and Flask, you can create a robust control panel for your projects. This method is not only efficient but also highly customizable, making it a great choice for home automation, IoT, and more.
Explore the potential of USB Relay Modules and transform your projects into remotely operable systems!