0

Gör en solcellstester med MecRisp-Stellaris framåt

June 17, 2022

i de senaste två artiklarna, jag har ranted om hur det är fantastiskt men konstigt, och sedan fick du upp på ett grundläggande system och blinkade några lysdioder. Och medan jag har pekat på multitasker, har vi inte gjort mycket verklig användning av det än. Komma igång i ett nytt system som det här är ungefär hälften av slaget. Arbeta inuti mikrokontrollern skiljer sig från att sammanställa för mikrokontroller och räkna ut arbetsflödet, hur man teknikproblem, och där de fördelaktiga resurserna är inte nödvändigtvis uppenbara. Dessutom finns det några fantastiska egenskaper hos Mecrisp-Stellaris, att du kanske inte märker förrän du har hackat på systemet ett tag.

Helst skulle du kika över att någon gör sin sak, och du skulle se några av hur de fungerar. Det är målet med denna del. Om du redan har blinkat i vår version av MecRisp-Stellaris-Plus-Embello är du redo att följa med. Om inte, gå tillbaka och gör din läxa riktigt snabbt. Vi kommer fortfarande vara här när du är klar. Mycket av det här inlägget kommer att vara väldigt säkra på Mecrisp-Stellaris-smaken, men med tanke på att det går på massor av armflis där ute, det är inte ett dåligt ställe att vara.

Blir acklimatiserad

Det första du behöver vänja dig i fram är stapeln. Du vet den gamla kastanjen om människor som bara kan hålla fem (sju?) Saker i sitt sinne på en gång? Fram sätter det till testet.

Förra gången påpekade jag kortfattat .s (“Print Stack”) -kommandot. I Hackaday-utgåvan har jag återupprättat den konventionella mecisp .s för att vara lite mindre verbose, och till mina ögon är mycket mer läsbar. Om du befinner dig som slår .s mycket, och du vill, har jag också skrivit en funktion som (tillfälligt) skriver över “OK”. Fråga genom att lägga till en stackutskrift till det, när du trycker på Enter. Skriv ut Print.Stack och tryck på en mycket mer tid för att se hur det fungerar. Att slå på återställningsknappen, eller skriva RESET kommer att torka allt i RAM, och det inkluderar stack-tryckprompten, så du kommer tillbaka till en ren skiffer.

Nu är det förmodligen en bra tid att leka med stackoperatörerna. Har du läst Mecrisp Ordlista? Kolla in listan över stack jonglering operationer där. Slå på PRINT.Stack och leka tills de alla är meningsfulla.

Har du kört ord än? Det spetsar ut en länkad lista över varje ord som går ut, tillsammans med minnesplatserna där de bor, och några extra detaljer – för mycket detaljer, om inte du felsökar själva systemet. Det finns en extra, nonstandard, ord i Mecrisp som bara skriver ut funktionsnamnen: listan. Ge det ett skott nu. Om du inte redan har definierat några ord, gör det.

: HW. “Hej, värld!” cr;
är en bra att ha till hands.

Lager i minnet

Mecisp-Stellaris-minnet är uppdelat i två bruttoplatser: RAM och Flash. Alla ord som tillhandahålls före “- Meckisp-Stellaris Core -” -märket är i RAM, och kommer att gå vilse vid återställning eller nedbrytning. Nya RAM-funktioner kommer att bifogas framsidan av listan.

Efter “- MecRisp-Stellaris Core -” Mark kommer funktioner i Flash. I de tidiga delarna av Flash, före “- Flash Dictionary -” är den konventionella mecisp-färgen kärnan. Därifrån tills “<>” är ord som tas från MecRisp-distributionen som normalt är användbara, inklusive vissa felsökningsfunktioner och multitasking. Föregående “<>” är bidrag från Embello-biblioteken, inklusive många GPIO-definitioner, och de före “<>” tillsattes bara för den här inläggsserien.

Det som inte är uppenbart är att alla dessa markörer med parentes som omger dem är hörnstenar. Dessa tillåter dig att rensa ut blinkar tills den här minnesplatsen. Så om du har lagt till några extra funktioner i Flash, och vill rensa tillbaka till standardläget Hackaday Edition, kan du skriva << Hackaday-Extra >>. De extra funktionerna raderas och chipåterställning. (Observera att det här förlorar vad som var i RAM!) Kommandot Eraseflash får dig tillbaka till “- Flash-ordlistan -” -markören.

Överskrivning historia

Om du definierar ett ord två gånger med samma namn har du två versioner av ordet i ordlistan. When a word is called or compiled, the interpreter looks through memory, from the top of RAM down, and then from the end of flash back to the beginning. Words with the same name in RAM thus get called before those in flash. What can be particularly odd about Forth is that, because it compiles in real-time, the word that is referred to in any calling word is the one that was on the top at the time the calling word was defined. Making tangled histories is a sure way to go insane.

: foo .” foo!” ;
: bar foo .” bar!” ;
bar foo! bar! ok.
: foo .” bizzle!” ; Redefine foo. ok.
foo bizzle! ok.
bar foo! bar! ok.

On the other hand, here’s a great way to work that takes advantage of these various memory features. RAM gets erased on every reset, giving you a clean slate, but by using cornerstones, flash isn’t immutable either. Of course, the deeper in flash you have to erase,the a lot more words you have to redefine later, assuming that some of them were useful. This suggests a layered technique to development, with the most “core” words innermost in flash. That’s also natural because words need to be defined to be called, so defining the basics first makes sense anyway.

You can compile a new word to RAM (the default) by calling compiletoram or to flash by invoking compiletoflash. Prototype your words in RAM. feel complimentary to overwrite them as lots of times as you want, but remember that you have to redefine any dependent words after you change something upstream to keep the calling history intact. once you’re made with a chunk of development, type reset and clear RAM. now redefine these words into flash. If you develop your application from the bottom up, you’ll find that this all hangs together nicely. When you’ve discovered a bug in something that’s already written to flash, the cornerstones come to the rescue.

Finally, this layered nature of Forth definitions can be really handy. For example, a function init that’s defined in flash gets run on each reset. It includes things like setting the processor speed and the system tick, that you probably don’t want to mess with. because you can overwrite init, and any compilation uses the words available at the time of compilation, you can simply layer your functionality onto init: : init init .” howdy!” cr ;. The first “init” is the name of the new word, and the second is calling the pre-existing init, and doing all of the setup. The remainder of the definition is yours to play with. On restart, everything will get carried out in the buy it was defined.

Creature Comforts

I write a lot of code in an editor (Vim) and then send it over to the chip to play around with. very specifically, I wrote a script called forth_upload.sh that contains the following:

[[ $1 ]] && TERM=$1 || TERM=/dev/ttyUSB0
DELAY=0.2
while read -r f; do echo “$f” ; echo “$f” > $TERM ; sleep ${DELAY}s ; Gjort

To send a file to the serial port, and thus to Forth, forth_upload.sh < myfunctions.fs will work. It loops through each line in the file, allowing a 0.2 second delay for the system to compile anything. This delay is too long, in my experience, but the bugs from having it short are lousy to find. Folie takes the technique of trying to find the “ok.” prompt to speed things up, but this has issues of its own. If you’re using Vim, you can send individual words or a full file with the following: nnoremap u vip:silent w !forth_upload.sh
inoremap u :silent .w !forth_upload.sh
nnoremap U :silent w !forth_upload.sh

This setup lets me develop and tweak functions in an editor that I like, and then send them nearly quickly into the Forth system to test out. I keep a terminal window open that’s always logged into the Forth system, so I can enjoy the new words get defined in, and then start playing around with them interactively. It’s pretty sweet.

The Solar Cell Tester

Now to a quick real example that will make use of all of the above. I recently made a decision to characterize a bunch of small solar panels that I had in my junk drawer. This indicates adjusting the load on the panel and noting down the voltage generated by the panel and the current through the load. I hooked up two multimeters and wrote down some numbers, but this is undoubtedly a job for a microcontroller.

As is clear from the image, this is a quick lashup. The larger chunk of copper-clad has a current-measurement resistor and a pair of resistors configured as a voltage divider to step down the panel voltage to something the 3.3 V ADC can handle.

Dangling off that is the (silvered) variable load circuit, which is entirely sub-optimal: a MOSFET dissipates the heat by being turned half on by a PWM’ed voltage fiiltered by that 100 uF capacitor. The 9 V battery and optoisolator were cobbled on to make sure a high enough voltage to fully open the MOSFET, which wanted a lot more than 3.3 V. This horrible, but functional, load circuit was a later addition — the first version just had a potentiometer here, until that got smoked by running too much current through it.

The pushbuttons are used to start and stop recordings from the device out on the balcony without having to run back inside. The procedure was to alligator-clip in a new panel, and hold the white button while it made recordings. The small black button is pressed once to demarcate a new cell’s data. The data goes back to my laptop over UART serial through an ESP8266 running esp-link as a transparent WiFi serial bridge, seen in the upper left, ideal next to the recycled laptop batteries. hot glue and cardboard round out the state-of-the-art build.

To the Datasheet!

This kind of quick and hands-on tool-building is where Forth shines. The Jeelabs Forth libraries already have some functions that simplify the ADC setup, but they actually didn’t work for me, so I looked to the datasheet.The bare minimum that one needs to get the ADC working is to turn on the ADC peripheral clocks, enable the ADC unit, and then select the ADC sampling time. We might also want to run the ADC calibration procedure to make sure our readings are correct. This is all the sort of low-level detail that you’d have to make with any microcontroller — or lean on a library that does it for you.

Reading the datasheet, to turn on the ADC system clock, we need to set the ADC1EN bit in the RCC-APB2ENR memory register. Vad som helst. Mecrisp-Stellaris has some support code that reads these values from files that are supplied by the manufacturer. I’ve included them in the core/registers/ directory. The memory map file had great mnemonics for all of the registers, but I’m not thrilled with the way that the individual bit names are handled. That’s a yak to shave on another day, I’m trying to get stuff done.

Here’s the set of bit-level ADC words that I came up with:

\ Träffas
\ PB0 – AIN8 is connected to panel voltage
\ PB1 – AIN9 is connected to current sense resistor

: adc.rcc-enable 9 bit RCC-APB2ENR bis! ; \ set ADC1EN
: adc.set-adon 0 bit ADC1-CR2 bis! ; \ set ADON to enable ADC
: adc.set-cal-bit 2 bit ADC1-CR2 bis! ;

: adc.cal-done? 2 bit ADC1-CR2 bit@ 0= ;
: adc.isdone? 1 bit ADC1-SR bit@ ;

9 bit creates a number with the ninth bit set and all others zero, and RCC-APB2ENR bis! sets the desired bit in the relevant ADC control register. all in all, pretty opaque, but also one-for-one with the datasheet’s instructions. good naming of these bottom-layer words makes things a little better one layer up. For instance, the word that is responsible for running a calibration (set one bit, wait until another is clear) is relatively readable: : adc.cal adc.set-cal-bit begin adc.cal-done? fram tills ;.

And here we see our first flow control, the begin…until construct. The buy is strange, right? begin starts the loop, The test function adc-cal-done? executes, leaving a true or false value on the stack, and then until reads this value and loops back to begin until the value is true. This is the same as a C while (!adc-cal-done()){;} busy-wait loop. and it’s an introduction to another Forth idiom: using ? for anything that returns a Boolean.

Test, Fix, and test Again

So let’s test these words out. Initializing the ADC and reading it are easy: now let’s take them for a run and make sure that the values are what we’re expecting. Whipping up a quick test fixture in Forth is one of its main strengths. : test-adc begin adc@ . cr 10 ms key? fram tills ; defines a word that reads the ADC, prints the value, and repeats every ten milliseconds until you hit enter. If you do this with a solar panel under a fluorescent light, for instance, you’ll pick up the mains frequency ripples as they hit your panel, which is something you might not have been thinking about. The ability to play around with your new words as soon as you define them makes this sort of investigative coding flow naturally.

True story time. When I was writing this code, I had set a too-short sample time on the ADC inputs. This causes the value from one reading to affect the next because the ADC’s internal capacitor doesn’t have time to charge or discharge fully. I was getting too-high readings for the current when the voltage was high, and too-low readings for current when voltage was low. I debugged this fairly swiftly by writing a routine that read each channel a few times in a row and printed the values out, and I left those words in for posterity.

( Take 8 samples of each, for debugging )
: read-both 8 0 do read-V . loop 8 0 do read-I . loop ;
: readloop begin read-both cr 100 ms key? fram tills ;

Feedback from this testing exercise lead me to switch up the sample times on the ADC to their maximum value, because nothing here was time vital and I was using a fairly high-impedance source. (The default is to sample as swiftly as p