filou
The first hurdle I stumbled over was actually trivial. I chose the Arduino UNO as the test target system, because it was ready to hand. Everything went well until the upload, as so often the boot loader didn't want to connect. First thought, wrong port or wrong baud rate, but it couldn't be set anywhere. So first, I only compile and start the avrdude manually and play with the baud rate. It turned out that it is an older variant, not the UNO but the DUEMILANOVE, which requires a different baud rate. I wanted to use the IDE and not mess around with the command line. So I started looking for a starting point.
     
The “hal” folder and the “hals.json” file sounded promising and I found quickly what I am looking for. Copying the section for the UNO and changing the heading and platform name, restarted OpenPLC_Editor and the upload worked fine.
 
The next steps were much more laborious, the script “builder.py” in the “arduino” folder provided information about how the entire process took place. After a lot of preparatory work, “arduino-cli” took over the main work of compiling all the files into single hexfile and loading it onto the target platform with “avrdude”.
 
The findings from the analysis of the build process, based on the Arduino UNO, should make it possible, to integrate other processors from the ATMega series into OpenPLC, through minor adjustments. After all worked as desired, everything had to ported back into the OpenPLC editor. The only thing standing in the way of all , was the upload via ISP and that didn't work as easily as with the DUEMILANOVE.
 
“arduino-cli” expects a parameter for the programmer, which is not provided from the script. The “hals.json” offers a way to save platform specific data, but to do this, it is necessary to create a new entry and evaluate it in the appropriate place in the build script. So that the entire “hals.json” doesn’t have to be revised, I preset the new variable with the empty string.
 
Look further down in the step by step tutorial:
Reply 2 0
thiagoralves
Thanks for the detailed explanation @filou!! Could you refactor it to be like a tutorial that could be added to the Documentation section on the website? I believe many users would benefit from this
Reply 3 0
filou
HOW TO add a new Arduino based Platform
 
This tutorial describes the necessary steps to add a new board to OpenPLC. In order to understand the procedure, it is important to take a closer look at the build process. It consists of two parts, one that is identical for all platforms an and one that depends on the hardware used. The interface between the two is the hardware abstraction layer HAL. The frontend is the OpenPLC editor, the backend is implemented by the Arduino toolchain.
 
First step, collect all information about the board:
 
In principle, all Arduino targets can be used, as long as they are known to OpenPLC and a suitable HAL exists. The necessary information, of the OpenPLC site, can be found in the (please adjust the path accordingly) file:
 
“/opt/OpenPLC_Editor/editor/arduino/examples/Baremetal/halls.json”
 
Arduino-cli provides us with the toolchain part:
 
“/opt/OpenPLC_Editor/editor/arduino/bin/arduino-cli-l64 board listall”
 
shows all boards available from the Arduino IDE:
 
Board Name                                                  FQBN
3D printer boards                                 STMicroelectronics:stm32:3dprinter
4D Systems gen4 IoD Range                         esp8266:esp8266:gen4iod
4D Systems gen4-ESP32 16MB Modules       esp32:esp32:gen4-ESP32-S3R8n16
AI Thinker ESP32-CAM                               esp32:esp32:esp32cam
ALKS ESP32                                                  esp32:esp32:alksesp32
ATMegaZero ESP32-S2                                 esp32:esp32:atmegazero_esp32s2
ATmega1284                                                  MightyCore:avr:1284
ATmega16                                                    MightyCore:avr:16
ATmega164                                                   MightyCore:avr:164
...
Arduino Duemilanove or Diecimila arduino:avr:diecimila
...
Arduino Uno arduino:avr:uno
...
 
How many entries there are, depends on the board packages installed in the Arduino IDE, there are hundreds of different boards available. First, we will just focus on the classic ATmegas.
 
“/opt/OpenPLC_Editor/editor/arduino/bin/arduino-cli-l64 board details -b MightyCore:avr:1284”
 
gives us more details about hardware for our board:
 
...
Platform name:         MightyCore
Platform category:     Contributed
Platform architecture: avr
...
 
Board related information used by build process, could be found in the Arduino platform folder. For example, for avr arduinos like the "UNO" or "NANO" at:
 
“~/.arduino15/packages/arduino/hardware/avr/1.8.6/boards.txt” ( on Linux usually )
 
If you have an older board, that is not listed in OpenPLC but is included here, chances are good that you can get it working without much hassle.
 
 
Second step, adding a new variant:
 
For example, if the baud rate is not correct, you can search for a similar board with the appropriate parameters and create a new entry in "halls.json", pointing to the suitable platform FQBN and HAL source file.
 
"Arduino Duemilanove": {
    "platform": "arduino:avr:diecimila",
    "source": "uno_leonardo_nano_micro_zero.cpp",
    "version": "1.8.6",
    "last_update": 0,
    "core": "arduino:avr",
    "default_din": "2, 3, 4, 5, 6",
    "default_ain": "A0, A1, A2, A3, A4, A5",
    "default_dout": "7, 8, 12, 13",
    "default_aout": "9, 10, 11",
    "user_din": "2, 3, 4, 5, 6",
    "user_ain": "A0, A1, A2, A3, A4, A5",
    "user_dout": "7, 8, 12, 13",
    "user_aout": "9, 10, 11"
  },
 
The “diecimila” is an older variant from “uno” and uses the same board layout an pin numbering schema. However, the baudrate and bootloader are different but they match our needs.
 
Let's take a closer look at the entries and their meaning for code generation:
 
"platform": "arduino:avr: diecimila" corresponds with the FQBN from "arduino-cli listall" command.
 
"version": "1.8.6" and "core": "arduino:avr" are also used by the arduino-cli to build for the correct target.
 
"source": "uno_leonardo_nano_micro_zero.cpp"
 
This file is responsible for initializing the hardware and controlling the pins. I will show how this works in another example below. As the name suggests, the code is for 5 different boards, that all have one thing in common, the ATmega328 processor and the pin layout. Since the boards are largely compatible with ours, nothing needs to be done here yet.
 
If you append this entry to your “hals.json” you have simply added an new Arduino board to OpenPLC.
 
 
Third step, adding a new core:
 

If the board you want to use is not in the "arduino-cli" list, you must first install the necessary software using the Arduino IDE and the board manager. The manufacturers usually offers a customized package for their hardware. If not, you can find some corresponding generalized cores for AVR processors on GitHub (https://github.com/MCUdude).

I like to use MyghtyCore because it supports a whole range of pin-compatible MCUs, so that you can choose the right hardware depending on your application. Because of the higher memory requirements, I chose the ATmega1284 here, which with 16K RAM and 4x8-bit ports, is the most suitable for a small PLC.

Before we use the new board for OpenPLC, a functional test should be carried out, using the Arduino IDE and the Blink Scatch. Don't forget to set the fuses and install a bootloader first! The IDE also provides support for this.

If everything is OK, we can create a new entry for "hals.json". This is where the board-specific HAL file comes into play. The starting point is the one for the standard Arduinos. The downside, however, is that the various AVR processors use very different definitions for bits and bytes in their hardware registers. That's why I left out the initialization of the PWMs, i.e. the analog outputs, for the first one. The JSON part of the HAL then looks like this:

  

"Arduino MC1284": {
    "platform": "MightyCore:avr:1284",
    "source": "arduino_MC1284.cpp",
    "version": "2.2.2",
    "last_update": 0,
    "core": "arduino:avr",
    "default_din": "8, 9, 10, 11",
    "default_ain": "A0, A1, A2, A3, A4, A5, A6, A7",
    "default_dout": "12, 13, 14, 15",
    "default_aout": "",
    "user_din": "8, 9, 10, 11",
    "user_ain": "A0, A1, A2, A3, A4, A5, A6, A7",
    "user_dout": "12, 13, 14, 15",
    "user_aout": "",
    "options": "-P usbasp"
  },
 

There's still a bit of work to do to connect the C code generated by "matiec" with the outside world. The build script has already done some of the preparatory work for us and generated the necessary glue code. The last step is reserved for "arduino.cpp". This file is nothing more than a renamed copy of our "source": "arduino_MC1284.cpp" from the HAL layer.

  

#include <stdlib.h>
extern "C" {
#include "openplc.h"
}
#include "Arduino.h"
#include "../examples/Baremetal/defines.h"

//Create the I/O pin masks
uint8_t pinMask_DIN[]  = {PINMASK_DIN};
uint8_t pinMask_AIN[]  = {PINMASK_AIN};
uint8_t pinMask_DOUT[] = {PINMASK_DOUT};
uint8_t pinMask_AOUT[] = {PINMASK_AOUT};

void hardwareInit()
{
    for (int i = 0; i < NUM_DISCRETE_INPUT; i++)
    {
        pinMode(pinMask_DIN[i], INPUT);
  if ( (pinMask_DIN[i] == 8) || (pinMask_DIN[i] == 9)  || (pinMask_DIN[i] == 10)  || (pinMask_DIN[i] == 11) ) {
    digitalWrite(pinMask_DIN[i], HIGH);  // Pullup
        }
    }
    
    for (int i = 0; i < NUM_ANALOG_INPUT; i++)
    {
        pinMode(pinMask_AIN[i], INPUT);
    }
    
    for (int i = 0; i < NUM_DISCRETE_OUTPUT; i++)
    {
        pinMode(pinMask_DOUT[i], OUTPUT);
    }

    for (int i = 0; i < NUM_ANALOG_OUTPUT; i++)
    {
        pinMode(pinMask_AOUT[i], OUTPUT);
    }
}

void updateInputBuffers()
{
    for (int i = 0; i < NUM_DISCRETE_INPUT; i++)
    {
        if (bool_input[i/8][i%8] != NULL)
            if ( (pinMask_DIN[i] == 8) || (pinMask_DIN[i] == 9)  || (pinMask_DIN[i] == 10)  || (pinMask_DIN[i] == 11) )
              *bool_input[i/8][i%8] =  ! digitalRead(pinMask_DIN[i]);  // Invers, switch to ground
            else
    *bool_input[i/8][i%8] = digitalRead(pinMask_DIN[i]);
    }
    
    for (int i = 0; i < NUM_ANALOG_INPUT; i++)
    {
        if (int_input[i] != NULL)
            *int_input[i] = (analogRead(pinMask_AIN[i]) * 64);
    }
}

void updateOutputBuffers()
{
    for (int i = 0; i < NUM_DISCRETE_OUTPUT; i++)
    {
        if (bool_output[i/8][i%8] != NULL)
            digitalWrite(pinMask_DOUT[i], *bool_output[i/8][i%8]);
    }
    for (int i = 0; i < NUM_ANALOG_OUTPUT; i++)
    {
        if (int_output[i] != NULL)
            analogWrite(pinMask_AOUT[i], (*int_output[i] / 256));
    }
}
 

The editor, or rather the build script, needs another file named acordingly the main source "arduino_MC1284.hal":

  

# HAL configuration
# Format :
# Board type, FQBN

Arduino MC32, MightyCore:avr:32
 

Now we can use the new board with the new processor for OpenPLC.

 

A small addendum, I'm sure someone has already wondered what the line "options": "-P usbasp" is doing in the JSON code.

I prefer to program the boards via ISP, but this is not the standard method of "arduino-cli" and must be communicated to it via a command line option. In our first example, this could be avoided with a little trick. Here you could try to adapt the "boards.txt", I decided me to extend "OpenPLC" accordingly.

 

Last step, a general option for the build script:

In the “builder.py” script, declare the new variable “options” at the level of the line with the text “#Check if board is installed” and read the entry from JSON if available:

  

Originally:
  
   hals = loadHals()
    
    #Check if board is installed
    board_installed = False
    core = ''
    for board in hals:
        if hals[board]['platform'] == platform:
            core = hals[board]['core']
            if hals[board]['version'] != "0":
                board_installed = True

Modified:
    
    hals = loadHals()
    
    #Check if board is installed
    board_installed = False
    core = ''
    options = '' # FILOU hals options option
    for board in hals:
        if hals[board]['platform'] == platform:
            core = hals[board]['core']
            if hals[board]['version'] != "0":
                board_installed = True
                # FILOU hals options option
                if 'options' in hals[board]:
                     options = hals[board]['options']
 
Now pass the new options further down in the script to the “arduino-cli”:
 
Old:
  
                compiler_logs += runCommand('editor/arduino/bin/arduino-cli-l64 upload --port ' +
                                            port + ' --fqbn ' + platform + ' editor/arduino/examples/Baremetal/')
          
New:

                compiler_logs += runCommand('editor/arduino/bin/arduino-cli-l64 upload --port ' +
                                            port + ' --fqbn ' + platform + ' ' + options + ' editor/arduino/examples/Baremetal/')
 
Reply 5 0
Reply