Creating external variables allows the ladder diagram to interact with the code from the Arduino extension. To properly achieve this, there's some steps that have to be followed. In this blog we'll also learn how to directly interact with IOs from an Arduino extension.
Previous blogs
This blog is part of a series of blogs about OpenPLC on Arduino and M-Duino. If you still have not familiarized yourself with the software, we recommend you go through the previous blogs first:
Modbus on Arduino with OpenPLC
Mapping any M-Duino on OpenPLC
MQTT on M-Duino with OpenPLC and Raspberry PLC
Using ESP32 PLC, M-Duino and Ardbox with OpenPLC
Hardware used
For this blog, we used an M-Duino 42+, but you can use any M-Duino PLC, Ardbox or ESP32 PLC as long as you select the correct model in OpenPLC.
Understanding IEC variables
OpenPLC variables are stored as IEC types, which sometimes do not translate directly into C types, requiring some extra work. Also, when dealing with numerical variables, the range of values used by OpenPLC will not match the range of values of the analog IOs unless a conversion is made.
How to declare external variables
In your ladder diagram, create a new variable and set its class to "External".
Then, create an Arduino extension by clicking on the grey plus icon.
And declare the external variable in the Arduino extension, giving it an initial value.
Now the external variable is ready to be used in either the ladder diagram or the Arduino extension.
BOOL external variables
BOOL external variables are the simplest and they can be directly assigned true or false in the Arduino extension. Here's an example in which we activate a digital output:
UINT external variables
UINT external variables, like BOOL variables, can be directly assigned their values in the Arduino extension, but they require an extra step. This example reads an analog input and sends the same value to an analog output:
OpenPLC uses a range of 0-65535 for its analog IOs, while M-Duino's analogRead() has a range of 0-1023, this means we have to multiply the value we are reading by 64. Here are all the conversions you need to take into account:
- M-Duino and Ardbox:
- analogRead: multiply by 64.
- analogWrite: divide by 256.
- ESP32 PLC (all except 14):
- analogRead: multiply by 32.
- analogWrite: divide by 16.
- ESP32 PLC 14:
- analogRead: multiply by 16.
- analogWrite: divide by 16.
STRING external variables
STRING external variables are more complex. They are stored as a struct containing two variables, one containing the length of the string and one for the body of the string. To properly store a string we have to access both of them. In this example, the Q0_0 output is activated when the incoming string matches with 'Hello':
The length of the string can be assigned directly, but the body requires a memcpy.
Creating external variables in OpenPLC to interact with an Arduino extension