Asynchronous Modbus-RTU library for mbedOS 6.
This project is inspired by the Arduino ModbusMaster library by 4-20ma.
NOTE: Previous mbed 5 version can be found on the mbed5
branch.
Read registers:
#include <mbed.h>
#include <ModbusMaster.h>
typedef ModbusMaster<16, 32> MBM;
EventQueue queue;
MBM modbus(&queue, PA_2, PA_3, 115200, 1);
int main() {
modbus.readHoldingRegisters(1, 4, [](auto res){
if(res != MBM::Result::success) {
// Handle error
} else {
uint16_t* reg = modbus.getRegisters();
reg[0]; // => register 1 value
reg[1]; // => register 2 value
reg[2]; // => register 3 value
reg[3]; // => register 4 value
}
});
queue.dispatch_forever();
return 0;
}
Create a new ModbusMaster instance.
Template args:
size_t txBufSize
Transmit buffer sizesize_t rxBufSize
Receive buffer size
Constructor args:
EventQueue* queue
EventQueue used for processing response off IRQ contextPinName txPin
Target TX pinPinName rxPin
Target RX pinint baud
: Serial baud rate (also used for Modbus frame delimiting)uin8_t slaveId
: Modbus slave IDstd::chrono::milliseconds rxTimeout = 50ms
: Modbus response timeout
Attach callback to be called before transmit. Can be used to toggle RS485 direction.
Attach callback to be called after transmit. Can be used to toggle RS485 direction.
Attach callback to be called after receive frame, before CRC calculation. (Can be used to modify received frame to workaround slave device quirks)
Callback function must return the buffer length.
Change modbus slave ID for subsiquent requests.
Change receive timeout for subsiquent requests.
Change whether CRC check is performed on the received response. (Can be used for slave devices with incorrect CRCs)
Get coils result after readCoils
or readDiscreteInputs
.
First result is on first byte LSB.
Get register result after readHoldingRegisters
or readInputRegisters
.
Registers values are converted to little-endien.
Modbus Read Coils function.
Modbus Read Discrete Inputs function.
Modbus Write Single Coils function.
Modbus Write Multiple Coils function.
Modbus Read Holding Registers function.
Modbus Read Input Registers function.
Modbus Write Single Register function.
Modbus Write Multiple Registers function.