I make things, and sometimes I'd like to share my experiences, to help others who possibly encounter similar stumbling-blocks. The joy that I sometimes still get when something starts working is indescribable, and if some of my projects inspire others, then that also makes me happy.
The things I make often involve computers, simple electronics, and Arduinos. I also make quite a few things in my workshop, using a lathe, milling machine, and an 'Ender 3' 3D printer. So I often tend to mix mechanical, electrical, electronic and computing work in my projects.
My work is television engineering related, and so quite a lot of what I do is involved with the field I'm immersed in. I do hardware and software for game shows, often using buttons, lights and multiple screen feeds displaying scores, logos and what-have-you.
My main interest is "interfacing". This is the connecting of real-world devices to a microprocessor or computer, so that external conditions may be read, or actions may be taken, or both, one possibly as a result of the other.
JUNE, 2021
PROJECT 1: A serial-controlled 8-channel relay
A recent device that I made is a really simple output device which may be controlled from a PC running RealTerm or a terminal program of your choice. I still program in VB6, which I know reasonably well, though seasoned programmers might baulk at my flagrant use of public variables. I've written a simple VB program to control it, and you can adapt it to suit your purposes.
The outputs are in the form of relays. I use a commonly-available 8-way relay module, like this one, bought from DIY Electronics in Durban.
The 8-channel relay board I use for this project.
If you'd like to know more about this project, read on.
I'll be posting photos, videos and all the code required, including the VB required to control it using the MSComm control.
Hardware:
You will need:
An Arduino or clone, you may use any board, but I'd recommend the Nano for this project, for several good reasons:
It has a USB mini connector, which is much more robust than the USB micro
It's nice and small.
It's got lots of I/O pins.
An Arduino Nano
You'll also need a relay board, like the one in the photo.
Bear in mind that each relay on this particular board is ACTIVATED by its control pin going LOW, and deactivated by it going HIGH. If your board is different, or if you made your own board using positive logic, then no matter, then there is a jumper on the PCB which sets this normal / invert parameter.
And lastly you'll need to make a simple adapter board, which neatly connects the output pins of the Nano to the inputs of the relay board. You could also hard-wire this yourself, but using the board makes it much easier and neater. I'll include the Eagle files for this layout, and possibly also a PDF.
Power for the relay board is supplied by the host PC via the USB connection, this is more than adequate to activate all the relays simultaneously if required.
The 8 channel interface board is really simple, it plugs straight onto the 8 way relay board, and it looks like this. Here I'm using it in a game control system for Kyk Wie Praat, an excellent show coming to Kyknet in July:
The device is controlled by sending simple serial commands from the host computer, either using a terminal program, such as Putty, or by writing your own serial command sender, which I've made really easy by including all the VB code you'll need:
A screen-grab of the example VB control program
Individual relays may be switched ON or OFF, and ALL relays may also be switched ON or OFF.
Serial port settings are 115200, N, 8, 1
Command set:
10 = Switch relay 1 OFF
11 = Switch relay 1 ON
20 = Switch relay 2 OFF
21 = Switch relay 1 ON
30 = Switch relay 3 OFF
31 = Switch relay 3 OFF
And so on, to
80 = Switch relay 8 OFF
81 = Switch relay 8 ON
I trust you get the idea...
Now, to switch all channels, simply send 200 for ALL OFF, and 201 for ALL ON
The Arduino code for the 8 channel device appears below.
July 2021
I've also made a 16 channel interface, which looks like this when plugged onto the standard 16 relay board:
16 channel relay with serial interface
Note that 16 relays activated simultaneously require more current than a standard USB port can provide, so this board requires an external 5V power source. Fortunately the board has a terminal block provided.
For the Arduino code for the 16 channel device, see below.
Arduino code for 8 channel interface:
//NanoRelay by Jules Costa
int ledPin[9] = {3, 4, 5, 6, 7, 8, 9, 10}; //Order to match Nano PCB
int chanNo;
void setup()
{
// initialize serial:
Serial.begin(115200);
// make the pins outputs:
for (int ledNum = 0; ledNum < 8; ledNum++)
{
pinMode(ledPin[ledNum], OUTPUT);
}
}
void loop()
{
//Get incoming serial:
if (Serial.available()>0)
{
int intString = Serial.parseInt();
chanNo = intString / 10;
int modString = intString % 10; // Modulo function, to get "remainder"
if (chanNo > 0 && chanNo < 8)
{
if (modString == 1)
{
digitalWrite (ledPin[chanNo - 1], HIGH);
}
else if (modString == 0)
{
digitalWrite (ledPin[chanNo - 1], LOW);
}
}
if (chanNo == 20)
{
//All LEDs:
if (modString == 1){ // All ON:
for (int ledNum = 0; ledNum < 8; ledNum++){
digitalWrite (ledPin[ledNum], HIGH);
}
}
else if (modString == 0)
{ // All OFF:
for (int ledNum = 0; ledNum < 8; ledNum++)
{
digitalWrite (ledPin[ledNum], LOW);
}
}
}
}
}
VB code for both boards, and the Arduino code for the 16 channel device:
If there is interest in the above code I'll happily share it, just send me a message
I also made a 16 - 64 input button sensor, using an Arduino Pro Micro.
The design uses 16 channel I2C port expanders, and inputs are all relay-isolated.
July 2026
Additionally, the same hardware may be controlled from a local web page using the WebSerial API. Save this code to an html file and open it with any Chromium-based browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arduino Relay Board Tester</title>
<style>
:root {
--bg-color: #121212; --card-bg: #1e1e1e; --text-color: #e0e0e0;
--accent-color: #00adb5; --relay-off: #333333; --relay-on: #00e676;
}
body {
font-family: 'Segoe UI', sans-serif; background-color: var(--bg-color);
color: var(--text-color); margin: 0; padding: 20px;
display: flex; flex-direction: column; align-items: center;
}
/* Replace your old container and grid styles with these */
.container {
width: 100%;
max-width: 1200px; /* Gives the interface plenty of room to stretch wide */
background: var(--card-bg);
padding: 25px;
border-radius: 12px;
box-shadow: 0 8px 24px rgba(0,0,0,0.5);
box-sizing: border-box;
}
.grid {
display: grid;
grid-template-columns: repeat(8, minmax(80px, 1fr)); /* Guarantees exactly 8 columns across */
gap: 12px;
margin-bottom: 20px;
width: 100%;
}
h1 { margin-top: 0; text-align: center; color: var(--accent-color); }
.config-panel { display: flex; gap: 15px; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 1px solid #333; align-items: flex-end; flex-wrap: wrap; }
.form-group { display: flex; flex-direction: column; gap: 5px; }
label { font-size: 12px; text-transform: uppercase; letter-spacing: 1px; color: #aaa; }
select, button { padding: 10px 15px; background-color: #2d2d2d; border: 1px solid #444; color: white; border-radius: 6px; font-size: 14px; cursor: pointer; outline: none; }
select:focus, button:focus { border-color: var(--accent-color); }
.btn-connect { background-color: var(--accent-color); color: #fff; font-weight: bold; border: none; }
.btn-disconnect { background-color: #cf6679; color: white; border: none; }
.global-controls { display: flex; gap: 10px; margin-bottom: 20px; }
.relay-card { background: #252525; border: 2px solid var(--relay-off); border-radius: 8px; padding: 15px; text-align: center; }
.relay-card.active { border-color: var(--relay-on); box-shadow: 0 0 10px rgba(0, 230, 118, 0.2); }
.relay-title { font-weight: bold; margin-bottom: 10px; font-size: 16px; }
.status-dot { width: 12px; height: 12px; background-color: var(--relay-off); border-radius: 50%; margin: 0 auto 15px auto; }
.relay-card.active .status-dot { background-color: var(--relay-on); box-shadow: 0 0 8px var(--relay-on); }
.console { background: #000; font-family: monospace; padding: 10px; border-radius: 6px; height: 80px; overflow-y: auto; font-size: 12px; color: #00ff00; border: 1px solid #222; }
</style>
</head>
<body>
<div class="container">
<h1>Relay Board Command Center</h1>
<div class="config-panel">
<div class="form-group">
<label for="baudrate">Baud Rate</label>
<select id="baudrate">
<option value="9600">9600</option>
<option value="19200">19200</option>
<option value="38400">38400</option>
<option value="57600">57600</option>
<option value="115200" selected>115200</option>
</select>
</div>
<div class="form-group">
<label for="relayCount">Hardware Model</label>
<select id="relayCount">
<option value="8" selected>8-Channel Board</option>
<option value="16">16-Channel Board</option>
</select>
</div>
<button id="btnConnect" class="btn-connect">Connect Port</button>
<button id="btnDisconnect" style="display: none;" class="btn-disconnect">Disconnect</button>
</div>
<div class="global-controls">
<button id="btnAllOn" style="border-color: var(--relay-on)">ALL ON (Cmd: 201)</button>
<button id="btnAllOff" style="border-color: #cf6679">ALL OFF (Cmd: 200)</button>
</div>
<div id="relayGrid" class="grid"></div>
<label style="margin-top: 15px; display: block; margin-bottom: 5px;">Serial Traffic Log</label>
<div id="console" class="console">System active. Select parameters and click Connect...</div>
</div>
<script>
let heartbeatInterval;
let port;
let writer;
let relayStates = [];
const btnConnect = document.getElementById('btnConnect');
const btnDisconnect = document.getElementById('btnDisconnect');
const baudrateSelect = document.getElementById('baudrate');
const relayCountSelect = document.getElementById('relayCount');
const relayGrid = document.getElementById('relayGrid');
const consoleLog = document.getElementById('console');
// Dynamically build the relay buttons based on count
function renderRelays() {
const count = parseInt(relayCountSelect.value);
relayGrid.innerHTML = '';
relayStates = new Array(count).fill(false);
for (let i = 1; i <= count; i++) {
const card = document.createElement('div');
card.className = 'relay-card';
card.id = `relay-card-${i}`;
card.innerHTML = `
<div class="relay-title">Channel ${i}</div>
<div class="status-dot"></div>
<button onclick="toggleRelay(${i})">Toggle State</button>
`;
relayGrid.appendChild(card);
}
}
// Transmit string + newline delimiter over Web Serial
async function sendSerialCommand(command) {
logToConsole(`Transmitting command: "${command}\\n"`);
if (writer) {
try {
const encoder = new TextEncoder();
await writer.write(encoder.encode(command + '\n'));
} catch (err) {
logToConsole(`Write error: ${err.message}`, true);
}
} else {
logToConsole("Execution Blocked: Serial port not connected.", true);
}
}
// Toggle handling using protocol template: [Channel][State]
function toggleRelay(channelIndex) {
const arrayIdx = channelIndex - 1;
// Flip local state tracker
relayStates[arrayIdx] = !relayStates[arrayIdx];
const isOn = relayStates[arrayIdx];
// Update UI card elements
const card = document.getElementById(`relay-card-${channelIndex}`);
if (isOn) {
card.classList.add('active');
} else {
card.classList.remove('active');
}
// Map variables directly to requested patterns (e.g. Ch 1 ON -> "11")
const stateBit = isOn ? "1" : "0";
const targetCommand = `${channelIndex}${stateBit}`;
sendSerialCommand(targetCommand);
}
// Master global triggers using override patterns
document.getElementById('btnAllOn').addEventListener('click', () => {
const count = parseInt(relayCountSelect.value);
for (let i = 0; i < count; i++) {
relayStates[i] = true;
document.getElementById(`relay-card-${i+1}`).classList.add('active');
}
sendSerialCommand("201");
});
document.getElementById('btnAllOff').addEventListener('click', () => {
const count = parseInt(relayCountSelect.value);
for (let i = 0; i < count; i++) {
relayStates[i] = false;
document.getElementById(`relay-card-${i+1}`).classList.remove('active');
}
sendSerialCommand("200");
});
// Connection Utilities
// Upgraded Connection Utilities with Active Heartbeat Pulse
async function connectSerial() {
if (!("serial" in navigator)) {
logToConsole("Browser restriction: Web Serial API is unavailable.", true);
return;
}
try {
port = await navigator.serial.requestPort();
const baudRate = parseInt(baudrateSelect.value);
await port.open({ baudRate });
writer = port.writable.getWriter();
btnConnect.style.display = 'none';
btnDisconnect.style.display = 'inline-block';
logToConsole(`Port link operational at ${baudRate} baud.`);
// Start the heartbeat timer: transmits 'h\n' every 1000ms
heartbeatInterval = setInterval(async () => {
if (writer) {
try {
const encoder = new TextEncoder();
await writer.write(encoder.encode('h\n'));
} catch (err) {
// If a background write fails, the port likely dropped physically
logToConsole(`Heartbeat write failed: ${err.message}`, true);
disconnectSerial();
}
}
}, 1000);
logToConsole("Fail-safe heartbeat background thread engaged.");
} catch (error) {
logToConsole(`Link Initialization Failure: ${error.message}`, true);
}
}
async function disconnectSerial() {
// Instantly clear the background pulse thread
if (heartbeatInterval) {
clearInterval(heartbeatInterval);
heartbeatInterval = null;
}
try {
if (writer) {
await writer.releaseLock();
writer = null;
}
if (port) {
await port.close();
port = null;
}
btnConnect.style.display = 'inline-block';
btnDisconnect.style.display = 'none';
logToConsole("Port link terminated safely. Heartbeat disengaged.");
} catch (error) {
logToConsole(`Teardown Error: ${error.message}`, true);
}
}
function logToConsole(message, isError = false) {
const time = new Date().toLocaleTimeString();
const hexColor = isError ? '#cf6679' : '#00ff00';
consoleLog.innerHTML += `<div style="color: ${hexColor}">[${time}] ${message}</div>`;
consoleLog.scrollTop = consoleLog.scrollHeight;
}
// Configuration listeners
relayCountSelect.addEventListener('change', renderRelays);
btnConnect.addEventListener('click', connectSerial);
btnDisconnect.addEventListener('click', disconnectSerial);
// Frame initialization
renderRelays();
</script>
</body>
</html>





