Go Forth on a Breadboard

Forth isn’t a shiny new programming language, but it has a staunch following because it is lightweight and elegant. The brainchild of [Chuck Moore], the language is deceptively simple. Words are character sequences delimited by spaces. In its simplest form, Forth knows a few basic words including–and this is the key–a word to define other words.

[Jean-Claude Wippler] likes to experiment with physical computing and he found a Forth image ready-made for the LPC1114. Why is that interesting? The LPC1114 is one of the few (or maybe the only) modern ARM processor in a breadboard-friendly DIP package. Since [Jean-Claude] had a chip sitting around, he had a Forth system up in no time. All he needed was a breadboard and a 3.3V serial connector. The chip has its own bootloader and the The Mecrisp-Stellaris Forth he used has over 300 words as well as the ability, of course, to add more.

If you ever used HP calculators (or slide rules) you’ll appreciate that Forth uses Reverse Polish Notation (RPN). For example the following words compute and print 2 times 10:

10 2 * .

You could make a word to multiply things by 2 (for example, mydouble) like this:

: mydouble 2 * ;

So you could then say

10 mydouble .

That seems pretty simple, but you can build a lot like this including entire assemblers and even cross-compilers for Forth itself.

By the way, the same Mecrisp-Stellaris Forth will run on the KL25Z mbed boards we covered a few weeks ago. You can even get Forth to run on an Arduino (see video below). If you bought an iCEstick to follow our recent FPGA tutorial series, you can run a Forth CPU on that board, too.

30 thoughts on “Go Forth on a Breadboard

  1. I never understood why forth was so popular, it still looks like a basic interpreter got off with a calculator.

    Still forth CPUs are very popular for HDL learning. That arm dip looks tasty tho.

    1. Back in lat 1970’s in Perth, Western Australia whilst a student at Western Australian Institute of Technology (WAIT) I was contracted out by WAIT Aid Ltd to Pretron Electronics contractor to Mt Newman mining to diagnose a NS Pace-16 based product for Mt Newman Mining Ltd which had an assembler based efficient tokenised/call implementation of Forth which handle quite complex maths for processing random scintillation counts from radionucleotides Cs137 or later Co60 beta sources to assess mass of airflow at Port Hedland’s or Mt Newman’s beneficiation/grading plant. In that the absorption through the falling ore stream would indicate the mass flow rate with low latency – this was used to measure overall mass & control filter/separation screens.

      ie. All the maths and other handlers were implemented in “Assembler-Forth”. The practicality was you would run your compute session with calls to forth call-tokens which operated on 4 x 16 bit registers (native cpu) but extended this to virtual fixed point registers with any number of calls to multiply/divides/adds etc This allowed assembler to be completely interspersed with Forth calls so both co-existed nicely.

      The resulting code was most efficient, it was essentially used to read data from two scintillation counters (beta detectors), do some averaging with Kalmin filter like rate assessments and feed a 12 bit value to a Foxboro motor controller to manage the angle on the iron ore feeder which was over a size separating screen. So more output mean more ore to flow onto the screens. Total flow as also accumulated & sense to a chart recorder for auditing…

      There were 16 of these machines in a line which operated reliably once we constrained the maths via the Kalman filter and outputs so the screens wouldn’t get bogged – otherwise a couple of people had to step into the screen area to shift a couple of tonnes of iron ore with shovels, so the pressure was on so the flow wasn’t reduced & grunts not needed to clear the screens otherwise surprises were waiting for us at the cafe that night !

      The value of Forth, even though that environment wasn’t ideal re eproms & paper tape backup was tha code was efficient, easy to read and 100% reliable as coded. Forth for me was intuitive as it mirrored the HP-41CX calculators (RPN) I used in my course.

      I’ve used Forth like structures in code for radio paging even as recently in early 2002, so although an older programming paradigm it has survived as being a nice mix assembler & high level math coding :-)

      1. Nice to hear of some real world applications of Forth. My Father taught it to me as my first programming language on a Dragon 32 machine about a million years ago (and sadly, I have forgotten it all), as it was the only language he was conversant in. I am still pained by the fact that today he is completely flummoxed by PC’s when once he was skilled. He still misses PC Dos.

        1. Interesting re your father’s perceptions Gregg,

          My eldest (23) is rapidly coming to terms with Java for android on his 8-core Samsung S6 in that we are collaborating on designing a product where I do the 8 bit cpu code which talks to a radio comms cpu of 32 bits & immensely comfortable with procedural based programming as I know where every byte of code/data/stack is at all times – not the case with object oriented or intermediate variants such as virtualisation on Java. I use a lot of windows comman line interfaces ie (the so called dos box) and batch programs with simple procedures. My eldest is doing the user interface which needs to be configurable for a whole heap of devices with fairly straightforward logic but its not straightforward to implement in Java eg not worth creating a bit wise linked list truth table to call tasks on demand interrupts as I would in assembler.

          There is a command line – linux like (so called) dos box (cml window) on the android S6 and its kind of neat to talk to the core of his 128Gig 8 core 64bit machine whilst its doing so many other things but, other than that I can’t see it being productive or even fun past the initial wow stage setting up some simple data processing…

          But, I really don’t like Java on his S6, its so overwhelming declarative with extensions for parallel programming and relies on relationships between sections which don’t appear to be explicitly defined. The result is code is big for what it needs to do having to interact with a GUI & the messy canvass issue which hides the screens memory array. Other than managing resources on Windows XP etc there is no real equivalent in that there seems to be a layer of obfuscation (probably pandering to so called 4 & 5 G programming paradigms originating in academia) which slows down development and adds a great deal of tedium to get simple things done.

          I used to do a lot of logic on the old Z80, AT89S53, 68HC11 and rarely got above 12K !

          My eldest cut his teeth on C in command line when he graduated in chem eng in 2013 and it might be good for your father to look at that and other dos window type command line interfaces as its essentially the initial dos box & still has use today. I notice there are ways to construct programming primitives from batch commands in dos which can now be compiled into .exe’s & relate to their switches as variables & that could be fun as you can build any language you like from such a base eg Forth with as much data space virtualisation only limited by your hard drive size !

    2. I on the other hand never understood why Forth was not more popular. The stress on being past tense however. I think Forth is a great idea (Chuck ‘found’, not invented it) who’s time has come and gone. When compile time measured in minutes or cross compiler where not available and system RAM amounts to mere Kilobytes, then Forth flexibility and potentially high performance is superior to alternatives. It was a perfect fit for the 8 bit Home computers of the early eighties.

      Now even embedded systems have often multi-megabytes of RAM and every developer has a PC with fast cross-compilers available, so it’s a much more questionable proposition. Stack counting is just so much fun. The interactive nature of the development system has still some appeal though (particular for ‘explorative’ computing).

        1. Open firmware PPC it was also used on IBM power based systems and PCI based PowerMacs.
          It was fairly powerful and in some ways better then UEFI but it was forth based vs C.
          Also it’s no secrets nature didn’t fit well with companies like Microsoft.

      1. I don’t think you have to stress the past tense. I am part of the very active Forth community, granted we are not nearly as big as other programming language communities and have missed out to establish a wider audience for Forth in the 8-bit era, but whenever we are on an events like the Chaos Computer Congress, people gain interest in its simple elegance.

        While the stack is often perceived as a main feature it really is not. It’s just a convenient way of passing parameters in concatinative languages. I’d say the main feature is the on-board parser. Whenever you write a program in Forth you are actually extending the language to meet your needs. You can even shift paradigms: C cannot become C++, you’d have to change the compiler to extend the language.
        A standard Forth system starts on about the semantic level of C. However, the smallest implementation of an object oriented Forth (minioof) is but a few lines of code: paste them in the terminal, and your Forth it object oriented. It is not very comfortable, and there are far nicer object oriented systems, but the power of Forth is that you can choose between them, and adopt them to your application.

        Having a parser on board enables even nicer features when you talk to another device. Say you build a telescope mount and program it with forth. Now you can hook it up to a PC and just send the next coordinates as text to the device, no need to think implement a serial protocol. You can use that same connection for firmware upgrades.
        When I come across an old piece of hardware, I don’t have to find the correct version of a compiler and a library, I can just start hacking directly on the device via a plain serial terminal.

        So lets not mark Forth as an enhanced calculator, cause you can also say the same about any interactive language. Get to know the power of CREATE DOES> and the power of typing “$0F PORTA-DIR ! $0A PORTA-OUT !” and seeing the leds being changed immediately without the need for a separated compiler or complex interpreter ;)

  2. There are more modern ARM chips you just have to use a socket. I don’t remember the models because when I use to try and get people to use them everyone went with proto-board chips and I just forgot about them..

  3. I have always found Forth useful when exploring the hardware on a PC. Start off by defining port addresses and gradually build up more complex words to achieve the desired objective. It all executes from the command line with no waiting for it to compile.

    That said, I last used it on a DOS machine!

  4. Getting productive with Forth can be frustrating for people used to conventional languages. It is truly a different way to look at the problem of programming a machine. In some ways it is like learning a human language. There are lots of words with simple meanings, but remembering enough of them to say something useful takes time. If you take that time however you end up with essentially a library of little sub-routines that can be strung together easily to make programs of any complexity. It becomes an integrated environment where you can work at any level from machine code to OOP. Debugging also is different when you don’t guess at what the machine will do for a given sequence of code. You just try it, time it, read the results in memory or I/O ports to confirm the action, all interactively. It could be that it appeals to Hardware geeks more for this reason. You are close to the silicon whenever you want to be. Like any programming language it’s not utopia, just another very useful tool.

    1. Now, I do not have much experience with Forth, but I do know why I always was interested, but never really got anywhere with it. And I also realize that there have been many attempts to solving these things, but I guess they were too late and other languages just ran by Forth.

      I think the reason is simple: there has never been a repository or even a standard for high-level Forth dictionaries. There is a basic dictionary with about 50 words or so, and all the rest is up to the programmers themselves. Every developer has to create his own extensions to the dictionary, and hardly any of them are publicised. And probably the problem is that the dictionaries are system-dependent anyway.

      This is fine if you’re developing some embedded app for an 8-bit CPU, and your program isn’t big. But not if your program has to handle large amounts of complex structured data, has to handle user input/output, possibly has to handle fancy graphics, etc. etc.

      I think that Forth could have become more mainstream if it had had a standard dictionary with higher-level functionality sooner, like C++’s STL.

      Also, I think that another problem is that it’s rather hard to work with the dictionaries. I mean: there are the words ‘:’, ‘words’, and that’s about it. It’s just hard to handle dictionaries. Some Forth systems probably have extensions for them. But again, they came too late. Other languages had full-screen IDE’s and integrated debuggers, and they were all standardized, etc. etc.

      But well, my interest has been sparked again. And I did a quick search on Google and see that there were some attempts at creating standard libraries for Forth, etc. etc. Maybe it would be fun to pick up Forth again. ;)

      I’m wondering why the Forth commandline never made the jump to VT220 with a full-screen positionable cursor and colors. It should be possible to make a full-screen editor out of that, which would still fit into a small device like this LPC1114. It would still be one IC, the connection would still be 2-wire serial (or 4-wire), but the usability would increase dramatically. Seems to me to be a nice project for someone. :)

  5. I think when you jump back in you will find it is a new world. The 1994 Standard created a nice standard language so that it is easier to move code. The commercial Forth systems now come with entire TCP/IP stacks and large libraries of code for floating point, communications, data structures and memory management. The best of these systems generate optimized native code that is as fast as the best C compilers. Some add full OOP functionality on top of standard Forth if you need that. The days of 64 character line editors is also 30 years old. People use their favourite editors.

    There is even new kid in town with the 8th Language which removes the “bumps” from Forth and creates a stack language that is very easy to use because there are no surprises. It is unique in that it can create binaries for Mac OS, Windows or Raspberry PI with the same source code.

    But I think you might have been looking at some homebrew systems in the past. I had a colour screen editor with the 5 lines below the edit window for the Forth interpreter for testing, interactive assembler/compiler, in other words an IDE, on a TI-99 in 1984. :-)
    When the compiler encountered an error and halted, I just typed “WHERE” on the command line and it put the cursor on the problem code. Forth systems from Forth Inc. had that kind of thing in the 1970s.

  6. Decades ago I wrote a WYSIWYG editor for Forth. It still used the 16×64 blocks but that was fine. It took maybe two hours. It used the old WordStar key-codes for cursor movement, etc.

    I saw a Forth, Inc tech try to get Forth running on a Zilog Z80 system without luck. He was very frustrated because they always were able to get a system running. I actually trained in Manhattan Beach for Forth. I met Chuck but Elizabeth Rather taught the course.

  7. A quote:
    Forth is also like a high-wire act; if C gives you enough rope to hang yourself, Forth is a flamethrower crawling with cobras. There is no type checking, no scope, and no separation of data and code. You can do horrible things like redefine 2 as a function that will return seven, and forever after your math won’t work. (But why would you?) You can easily jump off into bad sections of memory and crash the system. You will develop a good mental model of what data is on the stack at any given time, or you will suffer. If you want a compiler to worry about code safety for you, go see Rust, Ada, or Java. You will not find it here. Forth is about simplicity and flexibility.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.