Retrieving and Storing Data from Flash

A Dr. Taylor Tutorial

Retrieving and Storing Data from Flash

; 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

      .db    5,5,4,3,2,1  ; Stores values in program memory
      .db    'C', 'E', '-', '2', '8', '0', '0'
      .db    "CE-2800", 0

Reading from Program Memory

      adiw  ZH:ZL, 1

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
.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

Tutorials for Other Courses

Additional Links

Site Mirror

This is a mirror to be used when http://myweb.msoe.edu/taylor/, (EDU instead of US) is not available.