String variables
published: 2 December 2020 / updated 2 December 2020
I've been working on the LoRa transmission for a few weeks now. At each phase of development emerges a new problem to which a solution must be found.
Create a text variable
Here is the first definition test for the word string
:
\ define a strvar : string ( comp: n --- names_strvar | exec: --- addr len ) create dup c, \ n is maxlength 0 c, \ 0 is real length allot does> 2 + dup 1 - c@ ;
We define a string variable like this:
16 string strState
Here is how the memory space reserved for this text variable is organized:
Assigning a text to a text variable
The word $!
is defined as follows:
\ store str into strvar : $! ( addr1 len1 addrvar lenvar ---) drop dup 2- c@ \ get maxlength of strvar rot min \ keep min length 2dup swap 1- c! \ store real length cmove \ copy string ;
Exemple:
: myText ( --- addr len) s" this is an example text" ; myText strState $! strState type \ display: this is an examp
We intentionally tried to store a starting content "this is an example text"
longer than the maximum size of the strState
string variable.
ATTENTION: the word $! is preceded:
- content to be assigned to the text variable, here
myText
- of the text variable, here
strState
Any other combination can cause serious malfunctions!
The trouble with defining a text string with our definition of
string
is that the structure of our string is written in memory
ram, it is not persistent when we restart FlashForth.
Definition of stable text variables
The first way to define a persistent string is to define it in eeprom memory:
eeprom 16 string strState ram
This is the simplest solution. But the memory space in eeprom is very small and should be used exclusively to store persistent settings.
This new definition of string
is much more daring:
\ define a strvar : string ( comp: n --- names_strvar | exec: --- addr len ) flash create dup ic, \ n ram here i, \ n 0 c, 0 c, \ n allot does> dup \ addrf addrf c@ \ addrf maxlen over \ addrf maxlen addrf 1+ \ addrf maxlen addrf+1 @ \ addrf maxlen addrm c! \ addrf 1+ \ addrf+1 @ \ addrm 2 + \ addrm+2 dup \ addrm+2 addrm+2 1- \ addrm+2 addrm+1 c@ \ addrm+2 currlen ;
The whole trick is to store in flash memory the maximum length of
the text variable and the ram address of the contents of this text variable.
This is what is done between flash
and does>
.
The sequence ram here i,
stores in flash memory the starting address in ram of the
text variable
The execution of a text variable replicates the byte containing the length each time
maximum of the text variable. This guarantees the correct functioning of the word $!
on the content of the text variable which will always be stored in ram memory.
The full listing is available here:
STRINGS management for FlashForth
Happy programming!