Autres articles / Other articles

Conditional compilation for adaptable scripts

published: 17 June 2020 / updated 24 June 2020

Lire cette page en français

 

Preamble

ARDUINO cards exist in different versions: NANO, UNO, MEGA, etc ...

Development kits in C language can automatically adapt functions and libraries with these different cards. Let’s take the most trivial example for beginners: the LED on pin 13 flashes.

On each card, this pin is not located in the same place. Admittedly, it's still spotted with the number 13 . But on the two cards available, NANO and MEGA, we discover that it is not the same bit of PORT B:

Two alternatives are available to us if we want to use this same pin 13 on these two Arduino boards:

  1. create two separate listings, each listing being adapted to the Arduino board corresponding.
  2. create a single listing by adding tests and conditions, which does automatically the C language for Arduino ...

For the first solution, it becomes difficult to create as many listings that there are Arduino boards.

For the second solution, we can go through tests like this:

true  constant NANO 
false constant MEGA 
 
37 constant PORTB 
: LED ( --- msk port) 
    NANO if  %00100000 PORTB   then 
    MEGA if  %10000000 PORTB   then  
  ; 

There we only have two test lines. Imagine if there were a lot more cards to manage!

This solution has the disadvantage of cluttering the executable code with parts of code unused.

Conditional compilation

The word \ is used to mark the rest of the line as a comment.

The idea is to create a word ?\ which acts as a comment if a false Boolean flag precedes this word. Code of this word:

: ?\  ( fl --- ) 
    0= 
    if 
        postpone \ 
    then 
; immediate 

Here is how this new word can be used:

\ Practical example for ARDUINO: 
true  constant NANO 
false constant MEGA 
 
\ require pinsDefinitions.txt 
37 constant PORTB 
flash 
MEGA ?\  PORTB %10000000 defPIN: LED  ( PB7 pin 13 ) 
NANO ?\  PORTB %00100000 defPIN: LED  ( PB5 pin 13 ) 
ram 

Here, the constant NANO is true. When the interpreter meets this sequence NANO ?\ PORTB %00100000 defPIN: LED, the part of code after ?\ is processed by the interpreter.

With the word ?\, the final executable code would no longer be cluttered with unusable parts of code.

Whether you are on Arduino NANO or MEGA, we can now test the ignition and extinction of the integrated LED connected to pin 13. Test from the terminal in interpreted mode:

LED output  
LED high 
LED low 

With conditional compilation, you can write FORTH code adaptable to hardware and options available on the various Arduino boards.