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
.db 5,5,4,3,2,1 ; Stores values in program memory
.db 'C', 'S', '-', '2', '8', '0'
.db "CS-280", 0
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.
.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
.db "Jon Dough", 0
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.