Modbus RTU Slave. Define register addresses

I'm trying to simulate a LeadFluid BT103S pump via Modbus RTU.
The real pump has a lot of registers, but I only need to simulate 3 of the Holdingregisters.
Motor RPM at registeraddress 3100
Motor direction registeraddress 3101
Motor start/stop registeraddress 3102

I use C. M. Bulliner's ModbusRTUSlave Library [GitHub - CMB27/ModbusRTUSlave: This is an Arduino library that implements the slave/server logic of the Modbus RTU protocol.] and it works great when the address of the registers starts at 0 (zero). I can define 3102 Holdingregisters, and just use the last 3 of them, but it takes up a lot of memory and it's not the right way to do it.
Can someone come up with an idea on how to define a limited registeraddress area, perhabs by modifying the ModbusRTUSlave library or by using an other library ?
Thanks in advance.
/Jens

Processor used: STM32F103C8 BluePill

#include <Arduino.h>
#include <ModbusRTUSlave.h>



#define dePin PB1
#define LED_BUILTIN PC13

bool coils[1];
uint16_t holdingregisters[3102];

// put function declarations here:
  HardwareSerial Serial3(USART3);  // Pin PB10 og PB11
  ModbusRTUSlave modbus(Serial3, dePin);

void setup() {
  // put your setup code here, to run once:
  
  pinMode (LED_BUILTIN, OUTPUT);
  modbus.configureCoils(coils, 1);
  modbus.configureHoldingRegisters(holdingregisters, 3102);
  modbus.begin(10, 9600, SERIAL_8E1);
  SerialUSB.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(100);  
  //SerialUSB.println("ModbusSlaveTest");
  modbus.poll();
  digitalWrite(LED_BUILTIN, coils[0]);
}

If it works and you have enough memory, I wouldn't worry about it. The first rule of optimization : don't.

However, as an academic exercise, and you really want to save every byte, then modifying the library to use some sort of sparse array to store the holding registers might be the right method. If written as a suitably generic class (maybe a template), then you could extend to the other register types.

I would add a new method such as:

void configureHoldingRegisters(uint16_t holdingRegisters[], uint16_t  startAddress, uint16_t numHoldingRegisters);

Which could be called multiple times. I guess this now needs a result code or exception in case the caller tries to register overlapping regions, or maybe you code for that, or just ignore it.

bobcousins Thanks for your comment. You are right. I will not receive any Nobel prize for saving 6K bytes, that I don't need anyway :grin:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.