Noob needs help with Modbus communication

What I'm wondering now is:

  • do you have any suggestion of a Modbus library that I could learn to understand fairly easily with my level of skills but which also satisfies the needs of the project?

  • Are there any general methods/tactics I need to learn that would enable me to more easily understand any given library?

My final goal of the project is to have the Arduino function as a slave to the computer but also as a master to a variable frequency driver (both via RS485). The Arduino will also have to control a stepper motor, a temperature reader, and a fan (there could be a few more things, I do not have the full list in my head) -but without RS485, just normal IDE analog/digital outputs.

A callback is a callable (see further down) accepted by a class or function, used to customize the current logic depending on that callback.

One reason to use callbacks is to write generic code which is independant from the logic in the called function and can be reused with different callbacks.
source

Let's assume:
I'm the author of a library
You are the writer of the user Sketch

When I write the library, I don't know which pin you want to change when your master sends "switch Relay A to off).
Therefore I implement the call of a callback function - and handover parameters to this function.

YOU implement the callback function in your sketch, you know what the master will send and you know which pin should be set to zero.

Therefore your callback could look like following

constexpr byte coilPin[] {13, 4, 5, 6};          // GPIO to "coils"

// Callback used for FC5 Force Single Coil and FC15 Multiple coils
// the function must be able to set the pin
// value 0x0000 is allways to clear the pin. 
// Any other value should set the pin
// The callback receives 0xFF00 from Modbus FC5 to set a pin. 
// The callback receives 0x0001 from Modbus FC15 to set a pin.
void cbWriteCoil(const uint16_t reg, uint16_t value)
{
  //Serial.print(F("FC5/FC15 Write Coil, register:")); Serial.println(reg);
  if (value == 0x0000)
    digitalWrite(coilPin[reg], LOW);   // you could invert the coils if necessary
  else
    digitalWrite(coilPin[reg], HIGH);
}

so when the slave receives "register 0, new value 0"
the library calls your callback
the callback receives the parameters reg = 0 and value = 0
the code does the digitalWrite on that particular pin - to LOW

this is w

Yeah, maybe I didn't make it clear but I went and LEARNED what a callback function is while reading your library guide. :sweat_smile:
Would much appreciate some help with the other questions I posed above though if possible.
-Einar

honestly, this was the only question I thought it's worth that I should explain.

You will find tons of information about the difference of .h and .cpp files. But imho this will not help you in the current stage.

Make the/my library working.
Experiment with the simple examples.
If you have specific questions on my examples - feel free to ask.
Obviously I will not suggest another library and I will not dig deeper into others code :wink:

Ok, I will download your library and try to get familiar with it and also ask any specific questions about it then.

-Einar

That it's implemented in software.

I don't know if it uses a library but most probably it implements the complete Modbus protocol in software. Maybe the vendor used a library, maybe he implemented everything himself. I don't see why this should be important.

Very bad definition. I accept the phrase if the word "computers" is removed. It's a way how applications communicate if simplify it very much. It depends on the definition of an application if the phrase is correct or not.

A protocol is a set of rules how a communication has to be done.
An API is a definition of objects, methods or functions of a library or application that determines how that functionality can be used.
So if you have a library implementing the Modbus protocol than it's list of objects and methods is the libraries API.

In Modbus registers may either be holding registers (unsigned 16 bit values) or coils (digital I/Os, either on or off).

The values the variables has on initialization, in this case on startup.

More or less. As long as you stay inside the limitations (16 bit unsigned) you can choose them arbitrarily.

Yes.

Probably because the programmer thought that this initialization value makes sense. For example if you have several counters an initialization value of 0 makes probably sense.

Pylon,
thank you so much for your detailed response and explanations.
-Einar

Hi Noiasca,
I have downloaded your library and am now going about trying to understand the Modbus_Server_HelloWorld example.
A few questions:

  • How is the Arduino Uno lacking Hardware Serial? It has one set RX/TX pins after all which is sufficient to connect to the ttl/RS485 setup (?)
constexpr byte modbus_enable_pin = 11;       // The GPIO used to control the MAX485 TX pin. Set to 255 if not needed (i.e. a selfsensing module or RS232).
  • When you say "control the MAX485 TX pin", do you mean the DE/RE pins which are controlled by one pin on the Arduino (my MAX485 does not have a TX pin)?
// FC3/FC16 holding registers - not used in this example
enum
{
  // just add or remove registers and your good to go...
  // The first register starts at address 0 which is for Function 3 Register 40001
  DI12,              // a digitlRead of a GPIO
  DO13,              // a digitalWrite to GPIO
  ADC0,              // analogRead
  ADC1,              // analogRead
  ADC2,              // analogRead
  ADC3,              // analogRead
  HOLDING_REGS_SIZE  // leave this one
};
  • I do not understand this part. Below it says it adds predefined Modbus registers yet here we are adding registers? :thinking:
    Could you explain what this whole code segment is doing please?
#include <NoiascaModbusCommon.h>                 // predefined Modbus registers for the library examples

Do you have any recommended order to follow the examples in in order to learn the library as well as possible?
Also any documentation you recommend reading except for the ModbusServer Class Reference?
Also will this library be able to handle the Arduino working as a simple client/master with a variable frequency driver via RS485?

-Einar

a) For usual I spare the HW Serial of the UNO for debug messages to the serial monitor. Therefore I would use SoftSerial at a slow baudrate for Modbus. You are using a MEGA, therefore you don't need to bother with SoftSerial. Just use one of the additional HW Serials for Modbus.
b) if one uses a MAX485 he has for usual DE/RE pins. So I meant "if you want to SEND data you have to control DE/RE pins. your MAX485 MUST have a TX pin, otherwise your node can't send a response/acknowledgement to the client. In post #1 you added a picture with the "rs485 to ttl max485" ... this kind of adapters have a RX, TX and DE/RE lines for usual. I'm using similar ones.

you can delete this include. It is only used later in the LCD examples. just delete this line.

The examples are ordered by numbers. It's ok that you start with this helloWorld. Afterwards just procede with each FunctionCode example.

I don't know your "variable frequency driver".
my Library is a SERVER/SLAVE library only.
If you are asking if you can implement another Modbus MASTER/CLIENT library together with my Modbus SERVER library - I assume it should work togehter - at least with Modbus Master / 2.0.0 by Doc Walker.

Thank you for your answer Noiasca

your MAX485 MUST have a TX pin, otherwise your node can't send a response/acknowledgement to the client. In post #1 you added a picture with the "rs485 to ttl max485" ... this kind of adapters have a RX, TX and DE/RE lines for usual. I'm using similar ones.

here is a picture that is the same as my MAX485


Do you mean that the "DI" and "RO" pins correspond to RX/TX?

you can delete this include. It is only used later in the LCD examples. just delete this line.

So that bit of code was only useful for an LCD and not for the actual registers (I am talking about the enum with the HOLDING_REGS_SIZE (basically I do not understand the enum section :sweat_smile:))? :thinking:

my Library is a SERVER/SLAVE library only. If you are asking if you can implement another Modbus MASTER/CLIENT library together with my Modbus SERVER library - I assume it should work together - at least with Modbus Master / 2.0.0 by Doc Walker.

Ok, thank you for the recommendation. But how come there is a "client" section in the library folder if this is a "server/slave only" library?

Also, in what situation would you need to control the transmit pin manually?

/*
   if you need to control the transmit pin manually
   this callback will be called before the transmission starts  
*/
void cbPreTransmission()
{
  digitalWrite(modbus_enable_pin, HIGH);
}

yes. Go find a MAX485 datasheet and see how these MAX485 ICs are working.

do you know what a enumeration is and why people are using it?

```
enum
{
  // just add or remove registers and your good to go...
  // The first register starts at address 0 which is for Function 3 Register 40001
  DI12,              // a digitlRead of a GPIO
  DO13,              // a digitalWrite to GPIO
  ADC0,              // analogRead
  ADC1,              // analogRead
  ADC2,              // analogRead
  ADC3,              // analogRead
  HOLDING_REGS_SIZE  // leave this one
};
```

DI12 gets 0,
D013 gets 1,
ADC0 gets 2
ADC1 gets 3
ADC2 gets 4
ADC3 gets 5
HOLDING_REGS_SIZE gets 6

0 to 5 represent the valid holding register.
In total there are 6 valid holding registers.

May be you know understand what I've told you in #7. You have to plan your registers on paper.
This is conceptional work you do without any line of code. Write down your registers.
I have done this planing on paper and than I used an enumeration,
register 0 is to read data input pin 12
register 1 is to write to output pin 13 (the built in LED).

EVERYTIME before you can send data on the RS485 line you must pull DE/RE to HIGH, and then you can start transmitting.
therefore this callback is called PREtransmission.

Search the datasheet for the MAX485 and read how this IC is working.

because I felt it is necessary to provide some master examples which fit to my slave examples.

I think the most important thing would be that you get "0202_Modbus_Server_HelloWorld" uploaded and wired correctly so that you can control the registers 0 .. 5 with your PC.

Noiasca,
I am somewhat familiar with the enum having talked to my friedns studying CS about it and also watching some videos explaining it.
I think my question was poorly formulated. I see you are creating the references to holding registers / preparing to create holding registers and naming the total number of registers.
What I do not understand is this:
What is the part below doing?

unsigned int holdingRegs[HOLDING_REGS_SIZE];

Is this another way of writing this (that also says its an unsigned int?):

enum holdingRegs{
a
b
c
HOLDING_REGS_SIZE};

xxx

modbusServer.begin(&mySerial, modbus_baud, modbus_format, modbus_slave_id, HOLDING_REGS_SIZE, holdingRegs);

Also, I assume the above is the part that actually "creates" the slave and the registers?

-Einar

Ok, I will work on this now :+1:
Thanks for the help - Einar

EVERYTIME before you can send data on the RS485 line you must pull DE/RE to HIGH, and then you can start transmitting.
therefore this callback is called PREtransmission.

Yes, I am aware of this but thought that the code handled it automatically (?). So I was wondering in what situation(s) you would want to do it manually?
-Einar

no absolutly not.

unsigned int holdingRegs[HOLDING_REGS_SIZE];

creates an array with 6 fields.

the enumeration is separtely. but instead of
holdingRegs[1] = HIGH;

you can use the enumeration and write
holdingRegs[DO13] = HIGH;
which is the same but DO13 expresses more than a hardcoded 1. What does 1 stand for - no idea.
But behind the DO13 is clearly the register for the DigitalOut13

It's not manually - it will be done by the library. But you can create a callback to get this job done as needed by your hardware.
some people use autosensing RS485 drivers - they don't need to change pins,
some people need one pin and drive both pins
some people add two different pins to drive DE and RE separatly - they would need to add two digitalwrites.

each group of users need different handling of the lines - therefore different callbacks.

By the way ... the Modbus Master Library is using a very similar concept. Callbacks are very common if you want to have a versatile interface to a library.

Noiasca,

Ok, I get it now :slight_smile:

I am close to running my modified sketch but have one last problem before I can Upload:
Since I am using a Mega I do not need to use SoftwareSerial, so do I delete all references to mySerial in the code?
Or do I replace SoftwareSerial with HardwareSerial? When I write "HardwareSerial" it does not change color like it does with "SoftwareSerial"...

Basically Im a bit confused about these instructions:

// if you don't have enough HW Serial (i.e. on an UNO)
// you are forced to use SoftwareSerial or AltSoftSerial
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3);               // RX, TX

// On a Mega you can simply use 
// a Reference to an existing HW Serial:
// HardwareSerial &mySerial = Serial3;

// If you don't need debugging output, you can use
// a reference to Serial
// HardwareSerial &mySerial = Serial;

-Einar

have you tried to comment/uncomment ?

it just creates a reference called "mySerial" ... and will be used later for Modbus.

otherwise you must replace all "mySerial" in the code with Serial3 - therefore I prefer a reference.

have you tried to comment/uncomment ?

Yes, it ("HardwareSerial") does not light up for me.

it just creates a reference called "mySerial" ... and will be used later for Modbus.

so by adding the "&" in front (in the Hardware part) that means the code can use either [HardwareSerial Serial3] or [SoftwareSerial mySerial(2, 3)] when mySerial is called upon?

-Einar

this is what it looks like for me btw:
image
-Einar