Retrieving and Storing Data from Flash
- The .db assembler directive — define byte — instructs the assembler to store bytes in program memory.
- The .db directive can be followed with comma delimited list of:
- Numbers,
- Characters (enclosed in single quotes, e.g., 'a'),
- Strings (enclosed in double quotes, e.g., "monkey").
- Typically the data is stored after the program like this:
; program is up here and ends with an infinite loop...
forever:
rjmp forever
data:
.db 5,5,4,3,2,1 ; Stores values in program memory
Examples
- The following stores six bytes in program memory.
- By convention, the first byte indicates the number of data bytes stored in program memory.
.db 5,5,4,3,2,1 ; Stores values in program memory
- The following stores seven characters in program memory.
.db 'C', 'E', '-', '2', '8', '0', '0'
- The following stores a null terminated string in program memory.
.db "CE-2800", 0
Reading from Program Memory
- LPM — Load from Program Memory has three forms
- LPM: Load program memory — Uses the Z pointer.
- To increment the Z pointer, we use:
adiw ZH:ZL, 1
- The ADIW (Add Immediate to Word) does 16 bit addition.
- LPM Rd, Z — Uses Rd and the Z pointer.
- LPM Rd, Z+ — Uses Rd and the Z pointer and auto-increments the Z pointer.
Copying Data from Program Memory to Data Memory
.dseg
mydata:
.byte 6
.cseg
.org 0x0
rjmp start
.org 0x2a
; Initialize stack pointer
; ...
; Call copy to copy program memory into data memory
rcall copy
; Program goes here
; ...
; ...
; Copy function that copies data from program memory into data memory
copy:
; Save registers that are used by this function
push r15
push r16
push XH
push XL
push ZH
push ZL
; Initialize X pointer to point to data memory
ldi XH, high(mydata)
ldi XL, low(mydata)
; Initialize Z pointer to point to program memory
ldi ZH, high(2*data)
ldi ZL, low(2*data)
lpm r15, Z+ ; Get number of bytes to copy
; Loop until all data has been copied
repeat:
lpm r16, Z+ ; Read byte from program memory
st X+, r16 ; Store byte in data memory
dec r15
brne repeat
; Restore registers
pop ZL
pop ZH
pop XL
pop XH
pop r16
pop r15
ret
; Data stored in program memory
; The first byte represents the number of bytes stored in memory
data:
.db 5, 5, 4, 3, 2, 1
- If we are storing character data, we typically null terminate the string:
.db "Jon Dough", 0
- Here we can use the TST (Test) instruction which sets the zero flag if the register tested in zero.
- The loop of our copy function might look like this:
repeat:
lpm r16, Z+ ; Read byte from program memory
st X+, r16 ; Store byte in data memory
tst r16 ; Set zero flag if r16 contains zero
brne repeat ; Repeat if null terminator was not found
- It is possible to store data in flash memory while the program is running.
- The SPM (Store in Program Memory) instruction writes to program memory in much the same was as the LPM instruction reads from memory; however, writing to flash memory is more involved (due to block erase requirements).