defPIN:   high   low   output   input   pin@

defPin: ( PORTx mask --- <word> | <word> --- mask port)

Specific Flash Forth

The definition word defPIN: allows to create a pseudo-constant which concatenates in two bytes a port number and a binary mask. The word defPin: is followed of the pine mask to be defined. Example: PORTB %00000001 defPIN: RELAY1 creates the word RELAY1 connected to PORT B, bit 0.

At runtime, the word defined by defPIN: stacks the masking value and port number. Example, running RELAY1 will stack 1 37.

Here is the definition of the word defPIN: which you can use wherever you will need to define a pin corresponding to a PORT:

: defPIN: ( PORTx mask --- <word> | <word> --- mask port)
    create
        c, c,           \ compile PORT and min mask
    does>
        dup c@          \ push pin mask
        swap 1+ c@      \ push PORT
    ;
 
\ Examples, for Arduino MEGA:
eeprom
PORTB %00010000 defPIN: SER     \ PB4 -> pin 14 on the 75HC595 - dataPin
PORTB %00100000 defPIN: RCLK    \ PB5 -> pin 12 on the 75HC595 - latchPin
PORTB %01000000 defPIN: SRCLK   \ PB6 -> pin 11 on the 75HC595 - clockPin
ram

Before using defPIN: you must first define ports as constants.

The names of the constants and pseudo-constants created by defPIN: are written in capital letters.

high ( mask PORTx ---)

high toggles a bit high in a port register. high is a more explicit version than mset.

Here is the definition of the word high:

\ Turn a port pin on, dont change the others.
: high ( pinmask portadr -- )
    mset
  ;

low ( mask PORTx ---)

low toggles a bit high in a port register. low is a more explicit version than mclr.

Here is the definition of the word low:

\ Turn a port pin off, dont change the others.
: low ( pinmask portadr -- )
    mclr
  ;

output ( mask PORTx ---)

The word output allows to switch a bit in input mode on the register DDR of the corresponding port. By default, all DDR registers are in input mode when starting up ARDUINO cards.

Here is the definition of the word output:

\ Set DDRx so its corresponding pin is output.
: output ( pinmask portadr -- )
    1- high
  ;

input ( mask PORTx ---)

The word input allow to switch a bit in input mode on the register DDR of the corresponding port. By default, all DDR registers are in input mode when starting up ARDUINO cards.

Here is the definition of the word input:

: input  ( pinmask portadr -- )   
    1- low
  ;

pin@ ( mask PORTx ---)

The word pin@ retrieves the state of a bit in a data read register PINx. Stacks -1 (true) if this bit is non-zero, stacks 0 if this bit is zero.

Here is the definition of the word pin@:

\ read the pins masked as input
: pin@  ( pinmask portaddr -- fl )
    2- mtst \ select PINx register as input
    if      true
    else    false   then
  ;