PIC Forth and Assembly


You can use the code word instead of a colon to define a word completely in assembly language. You can also dynamically switch into assembly language (using ]asm) and switch back to Forth using asm[. We provide a Forth file for our APP-II processor that has to call library routines in the chip. This is a good job for assembly:

: SerialTransmit ( char -- )
  $0f pclath !
  >w
  ]asm
  $f14 call
  pclath clrf
  asm[
;
 
: SerialReceive ( -- char )
 $0f pclath !
 ]asm
  $F0e call
  pclath clrf
 asm[
  w>
;

The >w word gets the top of the stack to W and the w> reverses the process.

Once you are ready to build real programs you'll want to ditch interactive mode. For Windows you need to execute this command: gforth picforth.fs -e 'include xxx.fs file-dump xxx.hex map bye'

If you are using Linux of Cygwin just issues a "make xxx.hex" command.

There are plenty of other features  you can use in your programs. The compiler can create tables in flash, EEPROM, or RAM (although the APP-II doesn't know how to load EEPROM from a hex file, so EEPROM tables are not useful with the APP-II). You can handle interrupts and even set the configuration words for the processor (not necessary for the APP-II, by the way).

For more details, have a look at the PIC Forth manual.  Just to review, here's a simple program set up to blink two LEDs and display a counter on the APP-II's serial port:

$6 org \ skip boot loader junk (leave room for ISR)
$F0 constant divreset
$D constant cr
create divider divreset ,
create counter 0 ,
include app2.fs  \ APP-II library
include libfetch.fs  \ system libraries
include libstore.fs
include piceeprom.fs

0 pin-b led   \ define the LEDs
3 pin-c led1
\ print one hex digit
: printhexdigit $f and dup $a < if $30 else $37 then + SerialTransmit ;
\ print a hex byte
: printhex dup swapf-tos printhexdigit printhexdigit ;
\ print a space
: space $20 SerialTransmit ;
\ print a CRLF
: crlf $0d SerialTransmit $0a SerialTransmit ;
\ blink an led
: blink ( -- )
1 divider -! divider @
0= if led bit-toggle led1 bit-toggle divreset divider ! then
;
\ do the output - tail recursion optimized to a goto
: send 1 counter +! counter @ printhex space blink send ;
\ main program
main : program led >output led1 >output SerialSetup send ;

You can compile this to a hex file using:

gforth picforth.fs -e 'include demo.fs file-dump demo.hex map bye'

Then you simply use a terminal program (like Hyperterminal) to download the hex file directly to the APP-II (see the APP-II manual or tutorial for details).