Page 1 of 1

Forth code for LED blinking

PostPosted: Thu Jun 21, 2012 11:24 pm
by Bluebee
LED blinking is the first thing most of us have learned when using a microprocessor or microcontroller board first time.

Taking advantage of the really cheap LaunchPad from TI, there is an initiative offering a Forth for education, named 4e4th.
Once having transferred 4e4th to the LaunchPad, only a terminal is needed to "speak" with the on board MSP430G2553 and to program this little bugger. Since the RED and the GREEN LED on board are predefined, it is easy to switch a LED on or off.
Just by typing:

GREEN CCLR \ switches the green LED off (both LEDs are on at start)
RED CCLR \ switches the red LED off
GREEN CSET \ switches the green LED on
RED CSET \ switches the red LED on

Capital letters are optional. 4e4th isn't case sensitive. The preceding 'C' is used because these SET and CLR commands are 'character commands', that means, working on an 8 bit address. CLR and SET are working on 16 bit addresses - the MSP430 is a 16 bit micro.

As you can see, the object (RED or GREEN in this case) is named first, followed by the command CCLR or CSET.
The backslash '\' starts a commentary which can be omited.

Next step: let's begin with LED blinking!

: BLINKING RED CCLR GREEN CSET \ Let's begin with green!
BEGIN 200 MS RED CTOGGLE GREEN CTOGGLE KEY? UNTIL ;

BLINKING \ start the BLINKING module (a module is named WORD in Forth)

I am sure the word BLINKING is self-explaining. The colon marks the beginning of a new word - BLINKING in this example - which is added to the 4e4th dictionary when completed. The semicolon marks the end of the new defined word.
KEY? checks if there was a serial line input, that means the BLINKING begins, toggles RED and GREEN LEDs every 200 milliseconds, until a terminal KEY is hit.

The LaunchPad has a reset button - in case you like to stop your program immediately - and a freely usable button named S2.

: S2-TEST GREEN CCLR RED CSET
BEGIN S2? IF GREEN CTOGGLE RED CTOGGLE 50 MS THEN
BEGIN 50 MS S2? 0= KEY? OR UNTIL KEY? UNTIL ;

S2-TEST \ starts the new defined word/module S2-TEST

'S2?' checks the button S2, leaves a true (-1) on stack in case S2 is pressed, leaves a false (0) if not pressed.
'IF' checks this topmost number on stack. If this number is zero/false/0, the words between 'IF' and 'THEN' are skipped.
If this number is true/0>, the words between 'IF' and 'THEN' are executed.

'0=" checks the topmost number on stack, if it is zero/0 it leaves a true/-1 on top of stack, otherwise a false.
The results of S2? 0= and KEY? are combined with OR and checked by UNTIL. A 50 MS delay is used to prevent a bouncing switch malfunction.

Enjoy programming!
You can download 4e4th from http://www.4e4th.eu/