Monday, January 03, 2011

Testing a port

Here is a bit of code that I've been using to test microprocessor pins (also know as ports).

// ( port# -- )
: test_port0
// program port as an output
." Testing port 0." dup . ." ->"
dup p0_out_bit
dup p0set_bit ." 1"
500 ms
dup p0clear_bit ." 0"
500 ms
KEY drop

This word turns the selected output on and off every half a second (500 milliseconds) until a key is pressed. ('Word' is the Forth name for what other languages call functions, procedures or methods)

I won't explain all of the detail, but here are some bits worth noting.
  1. The // comment is supported on this Forth platform but not normally. The more traditional backslash (\) to end of line comments and round brackets (parentheses) are also supported.
  2. p0_out_bit, p0set_bit and p0clear_bit are words I created earlier. These do the following: p0_out_bit turns a particular pin (port) into an output, p0set_bit turns a pin high (on, 3v) and p0clear_bit turns a pin low (off, 0v).
  3. Forth syntax is words or numbers separated by spaces.
  4. Forth stores values on the stack, so 500 ms will store 500 onto the stack and the word 'ms' on this Forth system waits for that number of milliseconds.
  5. The Forth word ':' (colon) defines a new word called the name that follows it. The Forth word ';' (semicolon) ends that new word creation process.
  6. The BEGIN marks the start of the loop and the UNTIL marks the end of the loop. UNTIL will loop until it gets a true (In the above case KEY? produces a true when a key is ready).
  7. This Forth system is not case sensitive - so it doesn't matter whether the words are spelt DROP or drop.
To use this word you would type:
31 test_port0
This will print:
Testing port 0.31 ->setting31
On this system, port 0.31 is the on-board LED, and hence this particular example will flash the LED. (Note: the 'setting31' is test output printed by p0_out_bit)


Post a Comment

<< Home

Newer›  ‹Older