Arduino Modbus with Teensy 4.0

HSEY

Member
Of the many Modbus libraries, I like Arduino Modbus the best – it's easy to use, clearly laid out, and works very well with a Teensy.

Unfortunately, there's no naming convention at the beginning of the program, so you have to prefix all commands with "ModbusRTUClient".

This leads to confusion in larger programs. I would like to be able to replace the term "ModbusRTUClient" with a shorter form such as

MO or MB. Apparently, this has to be done in the h. or ccp. files. Can anyone help me with this?
 
Hi BriComp, thank you so much for the quick reply – the solution was simple, but I just couldn't figure it out.

It's great that there are such active forum members!

Thank you very much!
 
I know, sometimes you can get so engrossed in your project you cannot see the wood for the trees.
Glad I could help.
 
In the spirit of using more modern C++ features instead of #defines, here’s another alternative:
C++:
ModbusRTUClientClass& MB = ModbusRTUClient;
// This is the same thing (spacing difference): ModbusRTUClientClass &MB = ModbusRTUClient;

Or the more "flexible" version, where you don't need to know the type of the ModbusRTUClient object:
C++:
decltype(ModbusRTUClient)& MB = ModbusRTUClient;

That creates a reference variable pointing to the same thing as ModbusRTUClient. For all intents and purposes, MB and ModbusRTUClient are the same object. If I can avoid #defines in some convenient way, I often do. (This line, of course, needs to go after the library include(s) in your program.)
 
Last edited:
Isn't this the same as auto& ?
Indeed! I just couldn’t remember offhand which version of C++ that was introduced in. For sure it’s in the compiler included with Teensyduino (C++17), but I was trying to be “generic”. Let me look that up, actually…

Update: from a cursory glance, auto appears usable in this context in C++11, while decltype() was introduced in C++14. Heh. Yep. @jmarsh's solution is more concise, and probably better here. Thanks!

Sidebar: I’ve been poking around lately with making some things compatible with C++11, and there are certain contexts where auto can’t be used.
 
Last edited:
Back
Top