MOVING FORTH WITH MECRISP-STELLARIS and EMBELLO

In the last episode, I advocated a little bit for Forth on microcontrollers being a still-viable development platform, not just for industry where it’s normally seen these days, but also for hackers. I maybe even tricked you into getting a couple pieces of cheap hardware. this time around, we’re going to get the Forth system set up on that hardware, and run the compulsory “hello world” and LED blinky. but then we’ll also take a dip into one of the features that make Forth very neat on microcontrollers: easy multitasking.

Pracovať!

Hardware

Mecrisp-Stellaris Forth runs on a great number of ARM microcontrollers, but I’ll focus here on the STM32F103 chips that are available for exceptionally little money in the form of a generic copy of the Maple Mini, often called a “STM32F103 minimum System Board” or “Blue Pill” because of the form-factor, and the fact that there used to be red ones for sale. The microcontroller on board can run at 72 MHz, has 20 kB of RAM and either 64 or 128 kB of flash. It has plenty of pins, the digital-only ones are 5 V tolerant, and it has all the normal microcontroller peripherals. It’s not the most power-efficient, and it doesn’t have a floating-point unit or a DAC, but it’s a rugged old design that’s available for much less money than it must be.

Programmer Connected, Power over USB
Similar wonders of mass production work for the programmer that you’ll need to initially flash the chip. any of the clones of the ST-Link v2 will work just fine. (Ironically enough, the hardware inside the programmer is nearly identical to the target.) Finally, considering that Forth runs as in interactive shell, you’re going to need a serial connection to the STM32 board. That probably indicates a USB/serial adapter.

This whole setup isn’t going to cost much a lot more than a fast food meal, and the programmer and USB/serial adapter are things that you’ll want to have in your kit anyway, if you don’t already.

You can power the board directly through the various 3.3 and GND pins scattered around the board, or through the micro USB port or the 5V pins on the target board. The latter two options pass through a 3.3 V regulator before joining up with the 3.3 pins. all of the pins are interconnected, so it’s best if you only use one power supply at a time.

Firmware: The Forth System

Go get the super-special Hackaday-edition Mecrisp Forth package from GitHub. included in the “ROMs” directory is a Forth system that’ll work for the demos here. I’ve loaded in a respectable base from [jcw]’s exceptional Embello Forth libraries as well, supplying things like easy GPIO configuration, delay functions, and so on. There are lots of a lot more libraries available, and we’ll look into them next time when we need them.

The coolest thing about using a Forth system is that very little support software is needed in any way — the Forth interpreter compiles its own code, and you interact with it over the serial terminal. everything happens inside the microcontroller. The one hurdle, then, is getting Forth onto the chip. In the old days, this used to be done by toggling in the bytes manually, and Forth is actually small enough that literally bootstrapping it this way is possible. but you already gotten that chip programmer, right?

[Texane]’s ST utilities are the easiest way to get Forth onto your chip. download them from GitHub, and build it yourself or try your luck with your distro’s package manager. (Windows folks, you’re not left out either. Although that binary hasn’t seen updates in a while, it’ll do.)

Connect up the programming wires in the evident fashion, and issue the magic commands st-flash erase and st-flash write mecrisp-stellaris-hackaday-edition.bin 0x8000000. In five seconds, you’ll be ready to rumble.

GND — GND

SWCLK — CLK

SWSIO — DIO

Having to get a programmer is a hassle if you don’t have one, but it will make the rest of your life easier, and getting one is as basic as clicking “pay” and waiting. Our own [Al Williams] (no relation) has a recent post on using the same software for debugging C or Arduino code with GDB, so it’s worth your time to set this up.

Software

Serial Hookup, Powered by Laptop
Put the programmer away for now and connect to the STM32 over serial; the default baud rate must be 115,200. If you haven’t unplugged power yet, you might need to hit the reset button on the STM32 board. If all went well, you’ll be greeted by a familiar skull-and-cross-wrenches. Mecrisp is expecting a linefeed at the end of lines, so if you’re sending LF+CR, you’ll be successfully hitting return twice.

A9 TX — Serial RX

A10 RX — Serial TX

GND — GND

[jcw]’s folie is a nice, multi-platform serial terminal emulator for this application. What it does that your normal terminal program doesn’t is allow you to re-enter a command line with the up-arrow, which makes taking care of mistakes much, much much easier than re-typing a long command. To tiežAutomaticky obsahuje ďalšie súbory, ktoré som urobil značné použitie pri budovaní binárneho pre tento článok. Nemusíte bežať Folie, ale stavím sa, že sa vám to páči.

Ahoj svet

Teraz je to “hello svet”. Ak ste nový, tu prichádza veľmi selektívny úvod. Typ 2 2 + a stlačte ENTER. Hovorí sa, že ok .. to je upokojujúce, že? Teraz typ. (Prečítajte si “DOT”) a vytlačí sa neprekvapivý výsledok. Dot je prvý z málo globálnych skratiek, ktoré budete chcieť internalizovať. Veľa príkazov s bodkou vytlačí svoje výsledky okamžite. .s (DOT-ESS) sa napríklad vytlačí obsah zásobníka. Dve oveľa viac idiomov, ktoré uvidíme veľa @ na získanie premennej alebo čítania vstupu a! pre nastavenie premennej alebo výstupu. Prečítajte si ich ako “Získať” a “Set” vo vašej hlave pri skenovaní kódu.

Ďalej pozrime, ako písať funkciu. : Spustí definíciu funkcie a; končí. Takže: štyri 2 2 +; Definuje funkciu, ktorá pridáva dve a dve spolu. (A kompiluje ho v reálnom čase!) Potom sa môžete okamžite otočiť a zavolať túto funkciu. Štyri .s vám ukážu, že naša funkcia opustila sumu dvoch a dvoch na stohu. V tomto zmysle nie sú funkcie v skutočnosti. Neberú explicitné argumenty ani výslovné hodnoty. Práve pracujú na akýchkoľvek údajoch, ktoré sú na stohu, a nechať tu aj výsledky. To je dôvod, prečo sú funkcie nazývané “slová”. Teraz sa držím tohto dohovoru odteraz.

Tu, nakoniec, je “Hello World” :: HW. “Ahoj, svet!” cr, “reťazce sú trochu zvláštne, najmä kvôli spôsobu, akým je jazyk analyzovaný – kompilátor číta až do priestoru a potom vykoná to, čo zistilo, takže tam musí byť priestor medzi tlačou-a-string Príkaz (. “) A prvý znak, ktorý chcete vytlačiť. Tlačový príkaz skenuje dopredu, až kým nenájde uzavretie “, takže tam nepotrebujete extra priestor.

Blikajúce LED

Aj keď je sériový textový vstup a výstup tak jednoduchý, blikanie LED je štandardným “hello svetom” mikrokontrolérov, takže je čas na nejaké GPIO. Pretože systém je už nakonfigurovaný pre tento konkrétny mikrokontrolér dosky, otáčanie LED ON je rovnako jednoduché ako písanie LED.on na výzvu. Chcete ho vypnúť? LED.off. Manuálne blikanie dostane staré, aj keď napíšeme blikajúce slovo. : Blink LED.on 100 MS LED.off 200 ms; urobí trik. Skúste blikať blikať blikať. Pozrite si prosím môj blink demo kód pre vypracovanie. (Viac na MS v niekoľkých tisíc milisekundách.)

Podrobnosti o inicializácii GPIO sú skryté v jadre / hawaday / led.fs av resp. Vykopať cez, uvidíte štandardný postup inicializácie: Konkrétny kód PIN je nastavený ako výstup obopínaním niektorých bitov v registroch periférneho riadiaceho riadiaceho systému STM32. [JCW] definoval zväzok z nich, takže nastavenie PIN ako výstup, s ovládačom push-pull, ako je jednoduché ako PC13 OMODE-PP IO-MODE!. (Zapamätajte si “!” Indikuje nastaviť hodnotu v premennej alebo registrácii.)

Konfigurácia PIN PA7 pre vstup ADC: PA7 IMODE-ADC IO-MODE!. Testovacie tlačidlá, pomocou zabudovaného pullup alebo puldown rezistory: PA3 IMODE-PULL IO-MODE! A potom nastavte výstup, aby ste vytiahli nahor alebo nadol pomocou TRUE PA3 IO! alebo Pa3 iOS!. Potom budete môcť čítať stav tlačidlo s PA3 IO @ (“IO GET”) neskôr.

GPIO na čipoch STM32 je veľmi flexibilné, a ak sa chcete dostať hlboko do možností konfigurácie v datasheet, môžete to všetko ľahko ľahko použiť pomocou IO.FS kódu [JCW]. Napríklad io.all vytlačí všetky registre GPIO a ich hodnoty, čo je veľkou pomocou interaktívne ladenie. To povedal, je tu nejaká miestnosť pre oveľa viac užívateľsky príjemnej hardvérovej vrstvy, ak chcete prispieť.

Multitasking na rýchle

Takže teraz máme blikajúce LED a sériovú tlač “Ahoj svet”. Nie je to zlý štart, a obidva z nich sa dobre využívajú interaktivitu: LED dióda sa rozsvieti len vtedy, keď zadáte blikať. Jeden z hlavných cností, pre mňa je ľahkosť ísť medzi interaktívnym testovaním slov, ako je tento, a potom nasadenie funkčnosti v pracovnom systéme. Jedným z dôvodov je, že takmer celú podporu podporujú základné družstevné multitasking. Tu je to, čo tým myslím.

Po prvé, poďme slučka našej blinkovej funkcie, aby sme tak nemuseli písať. : BB Začiatok znova blikať; Vytvorí funkciu, BB pre “Bad Blink”, ktorý bude bežať navždy. Problém s “Beh Forever” ďalej je, že sa nikdy nevrátite späť na príkazový riadok tlmočníka bez fyzického stlačenia tlačidla RESET, a potom všetko, čo ste pracovali v RAM, sa stratí.

Instead, let’s blink in a loop with a way out. : gb begin blink key? until ; creates a function that will run our blink command until there’s some input from the keyboard — the return crucial is pressed. This particular looping construct is very beneficial for testing out functions that you’d like to run continuously, without hanging the system. keep it in mind.

Once we’ve tweaked our blink function to run just the way we want it, let’s create a background task so it can blink unattended.

task: blinktask
: blikať&
blinktask activate
begin blink again
;
robiť viac vecí naraz
blikať&

Briefly, the task: word creates some memory space for our blinking background task that we’re calling blinktask. The function blink& does the work in the background. blink& starts off by declaring that it will use the blinktask task context, and that it must start off running. then it goes into an limitless blinking loop from which it never leaves. multitask turns multitasking on, and blink& executes our task. Run it, and the LED blinks while you can still interact with the console. Sweet. type tasks and you’ll see that there are two active: one is our blinker and the other is the interactive interpreter.

But how does the blink task know when to yield to other simultaneous processes? In Forth, the word pause yields from the current context and moves on to the next, round-robin multitasking. The ms function, among others, consists of a pause command, so what looks like a blocking delay in a single-task setup ends up playing fantastically well with your other tasks.

The great thing about cooperative multitasking is that you control exactly when there’s going to be a context switch, which can help eliminate glitches that you’ll find in preemptive systems. The downside is that you’re responsible for remembering to pause your functions now and then, and you have to verify the timing yourself. Of course, this is a microcontroller, and you have the ARM’s quite rich internal interrupt controller to play with as well.

The real point of multitasking on micros in Forth is that it makes a great workflow for writing, testing, and deploying little daemons: functions that want to be “always on”. First, write the function that does the action once. Second, test it in a loop with an escape hatch. Third, once it’s working, remove the escape and make a background task for it. You can then turn it on and off using idle and wake, even from within other tasks. See Mecrisp’s multitask.txt, the source, for a lot more details.

Čo bude ďalej?

So far, we’ve set up Mecrisp-Stellaris, with additional libraries from Jeelabs’ Embello Forth framework, and run some quick demos. If this has piqued your interest, I’ll take you on a walkthrough of building some real software next time. There’s a lot a lot more to say about the way that Mecrisp handles the nuances of flash versus RAM, inputs and outputs, and the practice of interactive development. some of the really freaky aspects of working in Forth will raise their funny-shaped heads, and we’ll learn to love them anyway.

In the meantime, get your cheap STM32F103 boards flashed up with our binary, and get a little bit used to playing around in the Forth environment on the chip. Blink some LEDs. look around the Mecrisp-Stellaris glossary and the embello API documentation. Or just type list to see all the command at your disposal and start hacking away.