#26
Follow along with this
series! Joe’s book & kits
are available at
www.nutsvolts.com
by Joe Pardue
AVR Memory Part 4:
Writing to AVR Flash
Recap
Last month, we continued our AVR Memory series and
discussed reading the program memory in Flash. We learned
how to store constants in Flash to avoid unnecessarily
cluttering SRAM and we learned how to read data from
Flash. This month, we will learn how to write to Flash
using C functions from avrlibc. This will be the basis for
our final article in the memory series (next month) where
we apply what we’ve learned to building a bootloader.
cheapest of all and is used to store the program code that
rarely changes. Flash and EEPROM use similar technology,
but EEPROM can be programmed in individual bytes while
Flash is programmed in pages. This reduces the circuitry
necessary to program Flash, thus making it cheaper. Flash
page size varies depending on the particular AVR device.
My Big Fat BSOD
FYI, I got a Vista BSOD (Blue Screen Of Death) while
testing this code. Figure 2 shows the message I got after I
rebooted. You’ll note that it gave me the option to either
cancel or check later, but no option to check now. Ah,
Vista … you gotta love it.
I think my big fat BSOD was because an error in the
AVR code caused the serial port to be blasted with data
while I was using Bray’s Terminal. Well, at least Bray’s was
being blasted with data when I got the BSOD. Everything
recovered okay and I fixed the code to be blast free. But
you never know …
Writing To Flash
Flash is easy to read, but hard to write.
In previous articles, we’ve seen that the AVR uses
three main types of memory: SRAM, EEPROM, and
Flash. We learned that SRAM is the most expensive and
only used to store
data that changes
a lot when the
CPU is running;
that EEPROM is
cheaper and is
useful for storing
byte-sized constants
that change
occassionally; and
Flash is addressed by words, not bytes.
One additional noteworthy feature of Flash versus the
other memory is that Flash stores data as 16-bit words,
meaning that eight-bit byte data is stored in either the high
or low part of a word. For me, this creates a conceptual
problem because for the AVR — which is an eight-bit
system — we think in terms of bytes. So, why is the memory
now considered in words? Well, that is because the Flash
memory itself is a peripheral (something outside the CPU)
that is erased and written to in pages with word-sized
boundaries. I find this confusing and suggest that you just
do what I do: Try to remember that when the CPU is
reading Flash
memory, it is
doing it in
bytes but that
when we are
talking about
actually
erasing or
writing to
the Flash
memory, we
are doing that
■ FIGURE 1. ATmega644 Flash memory.
■ FIGURE 2. After the BSOD.
September 2010 55