Interacting with Hardware and Memory
Forth is great for debugging embedded hardware. You can use Forth to examine the contents of memory or peripheral registers:
2000 @
This places the content of address 2000 onto the stack. You can also use Forth to set memory or peripheral registers:
41 2000 !
This sets the content of address 2000 to 41. Remember that you can do this from within a word or interactively from the command prompt. This means that from the prompt, you can interactively probe and change peripheral registers—a very powerful debugging tool.
Warning
If you're using a version of Forth that is running on a desktop computer (such as a Mac or PC), don't try using store (!) or any other word that directly modifies memory, as it may have unforeseen (and possibly disastrous) results.
Fetch (@) and store (!) work with 16-bit-wide locations. To access 8-bit-wide locations, use the words c@ ("c-fetch") and c! ("c-store"), respectively. To access 32-bit-wide locations, use 2@ and 2!.
Warning
On some versions of Forth, such as gnu's gforth
running on a PowerPC processor, @ and ! operate on 32-bit values rather than 16-bit values. Similarly, on the same platform, 2@ and 2! are 64-bit operations.
As an example, let's create a Forth program called status
that will read the content of an 8-bit register located at address 2100 and place the result onto the stack.
: status 2100 c@ ;
This can be manually run from the prompt to examine the register during debugging:
status .
Perhaps you would like ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access