A feature-rich C# console application for controlling the STM32F4 Modbus/TCP-SPI Bridge system. Provides an interactive menu-driven interface for managing both local bridge LEDs and remote SPI slave LEDs.
This client application enables full remote control of the STM32F4 bridge and connected SPI slave devices through a simple, intuitive command-line interface. Perfect for testing, debugging, and demonstrating industrial protocol integration.
[C# Client App] βModbus/TCPβ [STM32F4 Bridge] βSPIβ [STM32F4 Slave]
(This Project) (LEDs)
- Interactive Menu: User-friendly command-line interface
- Dual LED Control: Manage bridge (local) and slave (SPI) LEDs independently
- Real-Time Status: Query and display all LED states
- Bulk Operations: Turn all slave LEDs on/off with single command
- Register Operations: Read holding registers (counter, etc.)
- Visual Display: Formatted status tables with emoji indicators
- Error Handling: Comprehensive exception handling with helpful messages
- .NET 8.0 or later
- Network connection to STM32F4 bridge
- Windows/Linux/macOS (cross-platform)
NModbus(v3.0.74 or later) - Modbus protocol implementation
- Clone or download the project:
git clone https://github.com/yourusername/modbus-client.git
cd modbus-client- Restore NuGet packages:
dotnet restore- Configure connection settings:
Edit
Program.csto match your bridge IP:
string ip = "192.168.1.50"; // Your STM32F4 bridge IP
int port = 502; // Modbus/TCP port (default 502)
byte slaveId = 1; // Modbus unit ID (default 1)- Build the project:
dotnet build- Run the application:
dotnet run=== Modbus/TCP-SPI Bridge Console ===
Connected to 192.168.1.50:502 (Unit 1)
Coil Mapping:
Coils 0-3: Bridge LEDs (Green, Orange, Red, Blue)
Coils 4-7: Slave LEDs via SPI (Green, Orange, Red, Blue)
Select command:
1 - Read Holding Registers
2 - Write Single Coil
3 - Read All Coils
4 - Control Bridge LED (Coils 0-3)
5 - Control SPI Slave LED (Coils 4-7)
6 - Read All LED Status
7 - Turn OFF All Slave LEDs (via register)
8 - Turn ON All Slave LEDs (via register)
0 - Exit
>>
Read one or more holding registers from the bridge.
Example:
>> 1
Enter register address (0 or 1): 0
Enter number of registers: 2
Read 2 register(s):
Register[0] = 42 (0x002A)
Register[1] = 0 (0x0000)
Register Map:
- Register 0: Counter (auto-increments on each read)
- Register 1: Command register (write special commands)
Directly write to any coil (0-7).
Example:
>> 2
Enter coil address (0-7): 4
Enter value (1=ON, 0=OFF): 1
Coil[4] (SPI Slave) set to ON
Display status of all 8 coils (4 bridge + 4 slave).
Example:
>> 3
Bridge LEDs:
Green = ON
Orange = OFF
Red = OFF
Blue = ON
SPI Slave LEDs:
Green = ON
Orange = ON
Red = OFF
Blue = OFF
Interactive control of local bridge LEDs.
Example:
>> 4
Bridge LED Control (Coils 0-3):
0 - Green
1 - Orange
2 - Red
3 - Blue
Select LED: 0
State (1=ON, 0=OFF): 1
Bridge LED set to ON
Interactive control of remote SPI slave LEDs.
Example:
>> 5
SPI Slave LED Control (Coils 4-7):
4 - Green
5 - Orange
6 - Red
7 - Blue
Select LED: 6
State (1=ON, 0=OFF): 1
Slave LED set to ON
Formatted display of all LED states with visual indicators.
Example:
>> 6
ββββββββββββββββββββββββββββββββββ
β LED Status Report β
β βββββββββββββββββββββββββββββββββ£
β Bridge LEDs: β
β Green π’ ON β
β Orange β« OFF β
β Red β« OFF β
β Blue π’ ON β
β β
β SPI Slave LEDs: β
β Green π’ ON β
β Orange π’ ON β
β Red β« OFF β
β Blue β« OFF β
ββββββββββββββββββββββββββββββββββ
Send bulk command to turn off all slave LEDs simultaneously.
Example:
>> 7
Command sent: Turn OFF all slave LEDs
Uses special register command: writes 0xAA00 to register 1
Send bulk command to turn on all slave LEDs simultaneously.
Example:
>> 8
Command sent: Turn ON all slave LEDs
Uses special register command: writes 0xAA01 to register 1
Cleanly disconnect and exit the application.
Edit these constants in Program.cs:
private static void Main()
{
// ===== CONFIGURATION =====
string ip = "192.168.1.50"; // STM32 bridge IP address
int port = 502; // Modbus/TCP port
byte slaveId = 1; // Modbus unit ID
// =========================
// ... rest of code
}If connection fails:
- Verify network connectivity:
ping 192.168.1.50-
Check bridge is running Modbus/TCP on port 502
-
Verify firewall settings (ensure port 502 is not blocked)
-
Try increasing timeout:
using var client = new TcpClient();
client.ReceiveTimeout = 5000; // 5 seconds
client.SendTimeout = 5000;
client.Connect(ip, port);ModbusMaster/
βββ Program.cs # Main application logic
βββ ModbusMaster.csproj # Project configuration
βββ README.md # This file
Add a new menu option by:
- Add state to enum:
private enum State
{
Menu,
// ... existing states
YourNewCommand, // Add here
Exit
}- Add menu option:
case State.Menu:
Console.WriteLine("Select command:");
// ... existing options
Console.WriteLine("9 - Your New Command");- Implement handler:
case State.YourNewCommand:
try
{
// Your command logic here
Console.WriteLine("Executing your command...");
// Use master.ReadCoils(), master.WriteSingleCoil(), etc.
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
state = State.Menu;
break;Modify the LED status display:
case State.ReadAllLEDs:
try
{
bool[] coils = master.ReadCoils(slaveId, 0, 8);
// Custom display format
Console.WriteLine("\n=== LED STATUS ===");
for (int i = 0; i < 8; i++)
{
string location = i < 4 ? "Bridge" : "Slave";
string status = coils[i] ? "β" : "β";
Console.WriteLine($"[{location}] LED {i}: {status}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
state = State.Menu;
break;Problem: Cannot connect to bridge
Solutions:
- Verify bridge IP address is correct
- Ensure bridge is powered on and network is connected
- Check network firewall settings
- Try pinging the bridge:
ping 192.168.1.50
Problem: Bridge disconnected during operation
Solutions:
- Bridge may have crashed or reset
- Check bridge power supply
- Verify bridge firmware is running correctly
- Reduce command frequency
Problem: Bridge not responding to Modbus commands
Solutions:
- Increase timeout values in TcpClient
- Check if bridge Modbus stack is initialized
- Verify correct slave ID (default is 1)
- Check bridge CPU load
Problem: Bridge doesn't support the Modbus function
Solutions:
- Verify bridge firmware supports all Modbus functions
- Check if using correct function (coils vs registers)
- Update bridge firmware if needed
Enable detailed logging:
try
{
using var client = new TcpClient(ip, port);
Console.WriteLine($"[DEBUG] Connected to {ip}:{port}");
var factory = new ModbusFactory();
var master = factory.CreateMaster(client);
// Enable ModBus logging if library supports it
// master.Transport.Timeout = 5000;
// ... rest of code
}Batch reads for better performance:
// Instead of 8 individual reads:
for (int i = 0; i < 8; i++) {
bool[] coil = master.ReadCoils(slaveId, (ushort)i, 1);
}
// Use single batch read:
bool[] coils = master.ReadCoils(slaveId, 0, 8);Minimize network round trips:
// Read multiple registers at once
ushort[] regs = master.ReadHoldingRegisters(slaveId, 0, 2);| Operation | Typical Time |
|---|---|
| Single coil write | 10-50 ms |
| Single coil read | 10-50 ms |
| 8 coil batch read | 15-60 ms |
| Register write | 10-50 ms |
| Complete status query | 50-100 ms |
- Connect to bridge successfully
- Read holding registers (option 1)
- Write bridge LED coil (option 4)
- Write slave LED coil (option 5)
- Read all coils (option 3)
- View formatted status (option 6)
- Turn off all slave LEDs (option 7)
- Turn on all slave LEDs (option 8)
- Verify visual LED changes on hardware
- Test error handling (disconnect bridge)
Create a test script:
public static class AutoTest
{
public static void RunTests(IModbusMaster master, byte slaveId)
{
Console.WriteLine("Starting automated tests...\n");
// Test 1: Write and read coils
Console.WriteLine("Test 1: Coil write/read");
master.WriteSingleCoil(slaveId, 0, true);
bool[] coils = master.ReadCoils(slaveId, 0, 1);
Console.WriteLine($"Result: {(coils[0] ? "PASS" : "FAIL")}\n");
// Test 2: Counter increment
Console.WriteLine("Test 2: Counter increment");
ushort[] reg1 = master.ReadHoldingRegisters(slaveId, 0, 1);
ushort[] reg2 = master.ReadHoldingRegisters(slaveId, 0, 1);
Console.WriteLine($"Result: {(reg2[0] > reg1[0] ? "PASS" : "FAIL")}\n");
// Test 3: Bulk command
Console.WriteLine("Test 3: Bulk LED command");
master.WriteSingleRegister(slaveId, 1, 0xAA00);
System.Threading.Thread.Sleep(100);
bool[] allCoils = master.ReadCoils(slaveId, 4, 4);
bool allOff = !allCoils.Any(c => c);
Console.WriteLine($"Result: {(allOff ? "PASS" : "FAIL")}\n");
Console.WriteLine("Tests complete!");
}
}- No authentication
- No encryption
- Transmits in plain text
- Direct device access
For production environments:
- Use VPN or isolated network
- Implement authentication layer
- Add command logging/audit trail
- Implement rate limiting
- Use TLS encryption if possible
// Coil operations (discrete outputs)
master.WriteSingleCoil(slaveId, address, value);
bool[] master.ReadCoils(slaveId, startAddress, count);
// Register operations
master.WriteSingleRegister(slaveId, address, value);
ushort[] master.ReadHoldingRegisters(slaveId, startAddress, count);| Code | Function | Used For |
|---|---|---|
| 01 (0x01) | Read Coils | Reading LED status |
| 05 (0x05) | Write Single Coil | Controlling individual LEDs |
| 03 (0x03) | Read Holding Registers | Reading counter, etc. |
| 06 (0x06) | Write Single Register | Sending bulk commands |
Improvements welcome! Consider adding:
- Configuration file support (JSON/XML)
- Command-line arguments
- Batch script execution
- CSV logging
- GUI version using WPF/WinForms
- Web interface using Blazor
This project is provided as-is for educational and development purposes.
Samet Arslan
- Project Created: September 2025
- STM32F4 Modbus/TCP-SPI Bridge - Target device
- STM32F4 SPI Slave - Remote LED controller
=== Modbus/TCP-SPI Bridge Console ===
Connected to 192.168.1.50:502 (Unit 1)
>> 4
Bridge LED Control (Coils 0-3):
0 - Green
1 - Orange
2 - Red
3 - Blue
Select LED: 0
State (1=ON, 0=OFF): 1
Bridge LED set to ON
>> 5
SPI Slave LED Control (Coils 4-7):
4 - Green
5 - Orange
6 - Red
7 - Blue
Select LED: 4
State (1=ON, 0=OFF): 1
Slave LED set to ON
>> 6
ββββββββββββββββββββββββββββββββββ
β LED Status Report β
β βββββββββββββββββββββββββββββββββ£
β Bridge LEDs: β
β Green π’ ON β
β Orange β« OFF β
β Red β« OFF β
β Blue β« OFF β
β β
β SPI Slave LEDs: β
β Green π’ ON β
β Orange β« OFF β
β Red β« OFF β
β Blue β« OFF β
ββββββββββββββββββββββββββββββββββ
>> 0
Disconnected.
Status: β
Production Ready
Version: 1.0.0
Last Updated: September 30, 2025
.NET Target: .NET 8.0+