Journal
Journal
Journal
Special AVR
Microcontrollers
ISSUE
In this
issue:
• Atmel Notes
• Novice’s Guide to AVR
Development
• Basic Interrupts and I/O
• Device Drivers and the
Special Function
Register Hell
• Variable Message Sign
Development
• GPS-GSM Mobile
Navigator
• AT86RF401 Reference
Design
• Designer’s Corner
• Atmel AVR and
Third-Party Tools
Support
• And More.
R
Our AVR microcontroller is
probably 12 times faster than
the one you’re using now.
(It’s also smarter.)
Introducing the Atmel AVR®. An 8-bit MCU that And when you consider that it can help slash months off your
can help you beat the pants off your competition. development schedule and save thousands of dollars in project
AVR is a RISC CPU running single cycle instructions. cost, it could make you look pretty smart, too.
With its rich, CISC-like instruction set and 32 working registers, AVR comes in a wide range of package and performance
it has very high code density and searingly fast execution–up to options covering a huge number of consumer and industrial
16 MIPS. That’s 12 times faster than conventional 8-bit micros. applications. And it’s supported by some of the best development
We like to think of it as 16-bit performance at an 8-bit price. tools in the business.
With up to 128 Kbytes of programmable Flash and EEPROM, So get your project started right. Check out AVR today at
AVR is not only up to 12 times faster than the MCU you’re using www.atmel.com/ad/fastavr. Then register to qualify for your free
now. It’s probably 12 times smarter, too. evaluation kit and bumper sticker. And get ready to take on the world.
© 2002 Atmel Corporation. Atmel and the Atmel logo are registered trademarks of Atmel Corporation.
A T M E L A P P L I C A T I O N S J O U R N A L
communicate and share lessons learned with other engineers who MEGA AVR
encountered and solved similar problems. In addition to the application FPGA AVR
LCD AVR
notes on the Atmel web site and AVR Freaks.com users forum, we now CAN AVR
have our own publication-- the Atmel Applications Journal. Here is the FPGA AVR
charter issue, dedicated to the AVR Microcontroller. DVD AVR
The Mega AVR Family has a unique Self-Programming Memory and Read while AVR Roadmap
Write capability. This is a break through technology that enables new appli-
grated LCD controller. Typical power consumption is less than 20uA at 32KHz
cations and provides the user a significant cost reduction by eliminating addi-
operation. It targets battery-powered applications like residential thermostats,
tional circuitry including a second CPU to implement remote programming
portable medical instruments and cordless communication devices.
capability. Today the AVR is more than a solution supporting the general-pur-
pose marketplace. The product family now integrates unique peripheral func-
The AT86RF401 SmartRF processor combines the AVR with a high perform-
tions that provide solutions for specialized markets. Examples are the portable
ance RF transmitter operating at 250 – 460MHz.
appliances, wireless communication, security and PC segments.
It is targeted at cost sensitive wireless remote control markets such as auto
Atmel recently introduced four new application specific extensions to the AVR
keyless entry, garage door openers and home convenience controls. The
Family. The Mega 169 is the first member of a family of devices with an inte-
AT97SC3201 Trusted Computing Platform Module brings affordable hardware
4-WIRE IN/OUT 3-WIRE IN/OUT
security to the PC Platform. It consists of an AVR with sophisticated tamper
detection circuitry designed to be mounted on the motherboard of the small-
SERIAL
est platforms including pocket PC’s and PDA’s. AT90SC Secure AVR Family
JTAG PERIPHERAL EEPROM
INTERFACE FLASH
INTERFACE integrates a random word generator, crypto coprocessor and on chip security
to enable GSM SIM card, Internet transaction, pay TV and banking designs.
ANALOG These smart card applications require high performance to perform encryption
COMPARATOR
functions in real time. There are six members of the USB AVR product offering.
OCD
PROGRAM
COUNTER A/D
The AT43USB351M is the only configurable low / high speed USB controller
CONVERTER
supporting five end points. With integrated 12 channel 10-bit A/D capability,
LCD
it supports video game controllers, data acquisition devices, and sensors and
INSTRUCTION
REGISTER
INTERFACE
mass storage applications.
32 GENERAL
PURPOSE
RIGISTERS
CONTROL
USART
Based on unprecedented market acceptance and customer demand, Atmel cre-
LINES
ated two new AVR design teams. One is located in Nantes, France, the other
SPI in Helsinki, Finland. These teams have specialized DSP, analog and communi-
RAM
INSTRUCTION
REGISTER ALU cation protocol design skills, which will expand the product portfolio and open
CPU TWI new markets for the AVR. To ensure adequate production capacity, we com-
missioned a new 8-inch wafer Fab in Tyneside, UK. This facility is capable of
processing twelve thousand eight-inch wafers per week with geometries as
small as 0.13u technology. This new production facility will accelerate cost
WATCHDOG I/O
INTERRUPTS
TIMER/ reduction efforts for both existing and new AVR components. Atmel has made
TIMER PORTS COUNTERS
a significant investment in design capability, process technology, plant and
equipment to ensure that state of the art AVR solutions are readily available
AVR Chip Diagram and are cost effective. ❑
www.atmel.com
page 1
A T M E L A P P L I C A T I O N S Number 1 • Summer, 2003
T A B L E O F C O N T E N T S
1 4-WIRE IN/OUT
page 1
JTAG
INTERFACE FLASH
3-WIRE IN/OUT
SERIAL
PERIPHERAL
INTERFACE
EEPROM
19
Welcome to the AVR Edition of Variable Message Sign Develop-
ANALOG
COMPARATOR
OCD
PROGRAM
COUNTER A/D
CONVERTER
USART
ment with AVR and ImageCraft
By Jim Panfil, Atmel By Patrick Fletcher-Jones and Chris Willrick
LINES
SPI
RAM
INSTRUCTION
REGISTER ALU
CPU TWI
5 WATCHDOG
TIMER
I/O
PORTS INTERRUPTS
TIMER/
COUNTERS
20
An Inexpensive Altitude GPS-GSM Mobile Navigator
Deviation Alert By Ma Chao & Lin Ming
By Larry Rachman, Innovation Design
and Solutions, Inc.
page 28 25
6 AT86RF401 Reference Design
Novice’s Guide to AVR By Jim Goings, Atmel
Development
By Eivind A. Sivertsen, Sean Ellis &
Arild Rødland, AVR Freaks page 11
28
An RF-Controlled Irrigation
System
11 By Brian Miller
Departments
By Eivind A. Sivertsen, Sean Ellis &
Arild Rødland, AVR Freaks Atmel Notes Page 3
Designer’s Corner Page 32
R
www.atmel.com
page 2
A T M E L A P P L I C A T I O N S J O U R N A L
Atmel Notes...
First secureAVR
Microcontroller with IAR visualSTATE® for AVR tool entry updated
32Mega-bit Flash Automated design and code generation with IAR visualSTATE for AVR:
Atmel Corporation announced that it is sampling a
®
The first state machine graphical design tool generating highly compact C code for embedded systems
secureAVR™ RISC Microcontroller with 32Mega-bit Flash. • Automatic generation of C/C++ code from state machine models
This product is based on the AT90SC3232CS (secureAVR • Automatic generation of full documentation
processor, 32Kbytes Flash, 32Kbytes EEPROM) with in addi- • Intuitive, easy to use graphical editor
tion 32Mega-bit of Flash for very efficient and secure data • Full verification and simulation tools including on-target debug capability using RealLink
storage. The AT90SC3232CS-F32M is a unique and innova- • UML compliant state machine standard
tive solution that combines programmability and processing
power with a very large Flash memory. IAR visualSTATE allows you to represent your specification/requirement in a graphical state machine model, debug,
simulate, document and generate micro-tight C code for your embedded device.
With the AT90SS3232CS-F32M, mobile communication
operators have access to a powerful product for emerging Benefits include:
applications with an important secure memory in a SIM
card. For other applications, wherever any system requires a • Faster development through graphical design of any application
large amount of data to be protected, the AT90SC3232CS- • Rapid implementation of change requests avoiding C code rewrite
F32M provides a highly secure, high memory capacity solu- • Accurate, structured documentation that is always in-sync with the final design
tion. • Interactively simulate and model your system before committing to hardware
• Embedded applications that are much easier to maintain
The AT90SC3232CS-F32M offers all of the AT90SC3232CS • Generate micro-tight embedded C code from graphical design with a single mouse click
features, a flexible secure microcontroller using Flash pro-
gram memory to satisfy a user's code modification require-
ments. For example, its state-of-the-art security features that
make it resistant against the most aggressive hardware or A Fully Integrated USB Secure µC Solution in a Single Package
software attacks and its powerful cryptography capabilities
(Elliptic Curves hardware support, fast DES/TDES and fast Atmel Corporation is sampling a fully integrated USB Full- and ISO 7816, for direct connection to either of these pop-
RSA processor). It is designed to meet Common Criteria Speed secure microcontroller in a PQFP44 package. The ular communication parts. It also incorporates 64Kbytes of
EAL4+ security certification. The AT90SC3232CS-F32M is AT90SC6464C-USB-I integrated package solution that on-chip Flash memory and 64Kbytes of EEPROM. Flash pro-
available in a 3V version, as well as 5V, and can be deliv- requires no external clock is based on Atmel's gram memory gives unrivalled flexibility for new applications
ered in module form or in package form. secureAVR(TM) RISC microcontroller. It includes 128Kbytes with the ability to load or upgrade application code during
of on-chip non-volatile memory, powerful cryptography capa- the production run with no delay.
Herve Roche, Smart Card IC Marketing Manager stated, bilities, a very high level of physical and data security, and a
"The content protection barrier is being surpassed. The dual interface USB V2.0 Full-Speed interface as well as the The AT90SC6464C-USB-I includes all the security features
AT90SC3232CS-F32M is the industry's first high-end secure standard ISO 7816 smart card interface. already built into the AT90SC secure microcontroller series.
microcontroller with this type of large Flash memory capaci- In particular, it provides a 16-bit RISC crypto processor for
ty. The other great performance is the availability of this out- The AT90SC6464C-USB-I targets eTokens used in PC-based very efficient execution of the highest-level encryption algo-
standing product for the smart card market with deliveries in secure applications. This package solution can also be rithms, RSA, AES 128/128, SHA-256. In addition, a hard-
module form. For example the ITSO's (Interoperable embedded in peripherals, set-top boxes, modems, PDAs ware T-DES (Triple Data Encryption Standard) coprocessor, a
Transport Smartcard Organization) secure (Personal Digital Assistants), copyright protection devices true RNG (Random Number Generator) and support for ECC
access module has been developed with and other equipment. Wherever data needs to be protected, (Elliptic Curve Cryptography) enhance the high cryptography
the AT903232CS-F32M in a standard the AT90SC6464C-USB-I can provide highly secure and cost- performance of this device.
SIM format". The AT90SC3232CS- effective solutions in applications such as transactional secu-
F32M is available in engineer- rity, e-mail and network encryption, software and file pro- The AT90SC6464C-USB-I in PQFP44 package is available
ing samples. The price for tection, MP3 and digital camera data storage protection. now in engineering samples. Production quantities are also
1000 units is $20. The AT90SC6464C-USB-I features a dual communication available at a price of US $4.00 in quantities of 200.000
❑ interface, including both USB V2.0 Full-Speed (12 Mbps) units. ❑
www.atmel.com
page 3
A T M E L A P P L I C A T I O N S J O U R N A L
www.atmel.com
page 4
A T M E L A P P L I C A T I O N S J O U R N A L
Background being measured is static, though it may be static at any point over a range of
Altitude is most commonly measured by its non-linear relationship to air pres- 2.3 to 4.6 volts. If the voltage were scaled to the point where the required 4
sure (Figure 1). At sea level, air pressure is approximately 30 in. Hg (100 millivolt resolution were measurable with the AVR ADC, it would be out of
kPa), decreasing to approximately 13 in. Hg (45 kPa) at an altitude of range for other altitudes.
18,000 feet (5500 m). Traditionally altimetry is performed by mechani-
cal means – a sealed air bellows is subject to atmospheric pressure; its The problem was solved by implementing a 4-bit resistor ladder Digital to
dimensional changes are geared to move indicators on a mechanical Analog Converter driven by the AVR controller. The output of this DAC was used
display, or to operate a Gray-coded encoder wheel providing the infor- to control the offset of the gain stage between the pressure sensor and the
mation in electronic form. Cost and size limitations would not permit ADC. (Figure 2) This permitted a step selection to be made by the AVR
such a solution for this project; instead a monolithic piezoresistive pres- firmware, insuring that the voltage being measured was within the ADC rails.
sure sensor was used. The device is comprised of a sealed vessel con- Since only a delta measurement was being made, the DAC could be con-
taining a known air pressure, one wall of which is a silicon die incorporating structed with relatively low-precision resistors (1%). By choosing offset and
a micromachined strain gauge and amplification stage. The package design gain stage values appropriately, the steps were overlapped, permitting any
permits air pressure to be introduced to the other side of the die, causing it to voltage over the input range to be offset to a point in the center 80% of the
deflect due to the pressure differential. A buffered voltage proportional to the ADC range.
Overview pressure differential is provided as output.
A complex and expensive When a stable altitude is reached a button press initiates a search for the DAC
output step that will cause the ADC input to fall near the center of its range.
regulatory approval process Based on the step selected, the firmware can compensate for the non-lineari-
for avionics equipment in ty of the relationship between altitude and air pressure. The deviation alert is
the US and other countries generated both by LED indicator and an audio tone introduced into the aircraft
has created a market for intercom system. The tone is generated with one of the AVR programmable
accessories and devices that, timers, with a second timer used for both system timing and control of the tone
cadence. Different tones indicating climb, descent, return to proper altitude,
since not connected directly and low battery (detected by another ADC channel) are generated while the
to the aircraft, are exempt processor spends approximately 99% of its time asleep, saving power.
from the approval process.
Such devices are expected The application firmware was developed using Atmel AVR Studio, the ICE200,
to be substantially less and the Imagecraft AVR Compiler. The AVR's complier-friendliness allowed the
application to be implemented in C with code size being only a minor factor.
expensive than panel- Source-level debugging simplified the development effort and later bug fixes.
mounted equipment, Figure 1
During debugging, software state and ADC input values were reported to the
yet the pilot-user's Our goal was to sound an alert upon a deviation as small as 100-200 feet. AVR serial port, simplifying the development process.
expectation of low cost is This required a resolution of 4 millivolts over a range of 2.3 volts, correspon-
still accompanied by one for ding to an Analog-to-Digital Converter resolution of 10 bits, before allowing for A 0.050" (1.27 mm) PCB card-edge pattern was included in the PCB design
granularity, hysteresis, or low-order-bit ADC noise. Ideally, a resolution of 13- for the AVR in-system programming connections. The connector also included
high reliability, ease of power and ground connections, permitting one-step production programming
14 bits would be needed to accomplish our goal.
operation, and the small of the AVR in-situ, without bed-of-nails ICT fixturing, and with zero additional
size expected of a portable Design Strategy component cost.
device. Our challenge was Our processor selection was the Atmel AVR at90s4433, chosen for size, cost,
to provide an altitude and low power consumption. The part includes an excellent low-power ADC, Conclusion
deviation alarm that but with a resolution of only 10 bits. There are numerous serial ADC devices By re-examining our design goals, we were able to utilize the ADC in the
available in the market, but costs tend to rise above 10-12 bits. With cost, at90s4433, where at first this did not seem possible. With the exception of a
would alert the pilot to buffer, the AVR was the only digital part in our design, keeping both cost and
size, and power consumption all factors, we decided to re-examine our design
an inadvertent climb or requirements. In normal operation the voltage corresponding to the altitude size to a minimum. (PCB dimension was 2x2" (50x50 mm) including con-
descent, possibly into nectors and the pressure transducer) With a remaining code space of 50%, as
restricted airspace. Given well as a pin-compatible growth path in the Mega8, we have an ample growth
Air
recent global events, such Pressure Gain AVR
path for new features. ❑
Transducer and Audio
at90s4433
deviations are subject to offset
stage microcontroller
to Intercom
www.atmel.com
page 5
A T M E L A P P L I C A T I O N S J O U R N A L
knowledge. Assembly Sample Code This file contains the Assembly Sample code
The difference between these devices lies in the available features. The
tinyAVR µC are usually devices with lower pin-count or reduced feature set
(~1kB) you will need to complete this guide.
compared to the megaAVR's . All AVR devices have the same instruction set
and memory organization, so migrating from one device to another AVR is
easy.
By Arild Rødland, AT90S8515 Datasheet This is the Datasheet for the AT90S8515 AVR
AVRFreaks (~4MB) Microcontroller. This is a convenient "Getting Some AVR's contain SRAM, EEPROM, External SRAM interface, Analog to
Started" device. For now you don't have to worry
Digital Converters, Hardware Multiplier, UART, USART and the list goes on.
about the different types of AVR micros. You'll see
that they are very much alike, and if you learn
how to use one (eg. 8515), you will be able to If you take a tinyAVR and a megaAVR and strip off all the peripheral mod-
use any other AVR without any problems. ules mentioned above, you will be left with the AVR Core. This Core is the
Starting with a new µC same for all AVR devices. (Think of Hamburgers: They all contain the same slab
architecture can be quite Instruction Set Manual This is the Instruction Set Manual. This document of meat, the difference is the additional styling in the form of tripled-cheese
(~2MB) is very useful if you want detailed information and pickles :)
fustrating. The most dif- about a specific instruction.
ficult task seems to be Selecting the "correct" AVR
how to get the informa- The morale is that the tinyAVR, AVR (Classic AVR) and megaAVR does not real-
When you have downloaded the files, it is time to install the software you ly reflect performance, but is more an indication of the "complexity" of the
tion and documentation need. device: Lot's of features = megaAVR, reduced feature set = tinyAVR . The "AVR
to get the first AVR pro- (Classic AVR)" is somewhere in between these, and the distinctions between
gram up running. Step 2. Installing AVR Studio 4 these groups are becoming more and more vague.
AVR Studio is also available in a version 3. We will use AVR Studio 4 since this
This tutorial assumes is the version that will eventually replace version 3. So for your project you should select an AVR that only includes the features
that you do not yet own that you need if you are on a strict budget. If you run your own budget you
any AVR devices or AVR Important note for people using Windows NT/2000/XP: should of course go for the biggest AVR possible, since eh... because!
You must be logged in with administrator rights to be able to successfully
development tools. It install AVR Studio. The reason is that these Windows systems have restrictions Learning to write code on the AVR
also assumes that you regarding who can install new device drivers! Learning new stuff is fun, but can be a bit frustrating. Although it is fully possi-
have no prior knowledge ble to learn the AVR by only reading the datasheet this is a complicated and time-
Installation: consuming approach. We will take the quick and easy approach, which is:
of the AVR architecture 1) Double click on the AVRSTUDIO.EXE file you downloaded. This file is a self
or instruction set. All you extracting file, and will ask where you want to extract the files. The default 1. Find some pre-written, working code
need to complete this path points to your "default" temp folder, and could be quite well "hidden" on 2. Understand how this code works
your hard disk, so make sure to read and remember this path, or enter a new 3. Modify it to suite our needs
tutorial is a computer
path to where you want the files placed (e.g. c:\temp ) The device we will use is the AT90S8515 which is an AVR with a good blend
running some flavour of of peripherals. Take a few minutes to browse through the Datasheet.
the Windows operating 2) Once all the files are extracted, open the temp folder, and double click on
system, and an internet the SETUP.EXE file. Just follow the installation, and use the default install path. Learning to use the AVR Datasheets
NB: You can use another path, but this tutorial assumes that you install it to It is easy to get scared when looking at the AVR Datasheets. E.g. the
connection to download the default path. ATmega128(L) datasheet is almost 350 pages long, and reading it start to fin-
documents and files. ish - and remembering the contents, is quite a task. Luckily you are not sup-
That's it. Now you have installed all the software you'll need to write code and posed to do that, either. The datasheets are complete technical documents that
run programs for all available AVR devices! Keep the Datasheet and Instruction you should use as a reference when you are in doubt how a given peripheral
set Manual in a place you remember. or feature works.
www.atmel.com
page 6
A T M E L A P P L I C A T I O N S J O U R N A L
When you open an AVR Datasheet you will discover that it can be divided into This is done in four steps:
these groups: 1. Click on this to let the program know you want to create an Assembly
1. First Page Containing Key information and Feature List program
2. Architectural Overview 2. This is the name of the project. It could be anything, but "Leds" is quite
OK! You have now installed 3. Peripheral Descriptions descriptive of what this program is going to do
the software, you have a 4. Memory Programming 3. Here you can specify if AVR Studio should automatically create a initial
5. Characteristics assembly file. We want to do this. The filename could be anything, but use
vague knowledge of the 6. Register Summary "Leds" to be compatible with this tutorial!
7. Instruction Set Summary 4. Select the path where you want your files stored
different types of AVRs, 5. Verify everything once more, and make sure both check-boxes are checked.
8. Packaging Information
and know that there is a When you are satisfied, press the "Next >>" button
This is quite convenient. When you are familiar with how to use the Step 3: Selecting Debug Platform
lot of information in the AT90S8515 Datasheet, migrating to another Datasheet should be a breeze. The AVR Studio 4 Software can be used as a frontend software for a wide
datasheet that you don't After completing this tutorial you should take some time and read through the range of debugging tools.
Architectural Overview sections of the datasheets (At the beginning of the
yet know anything about! Datasheets). These sections contain a lot of useful information about AVR
memories, Addressing modes and other useful information.
Good, now it's time to get
developing! Click "Next" Another useful page to look at is the Instruction Set Summary. This is a nice
reference when you start developing code on your own. If you want in-depth
to advance to the next information about an instruction, simply look it up in the Instruction Set
Manual you previously downloaded!
part of this tutorial.
OK! You have now installed the software, you have a vague knowledge of the
different types of AVRs, and know that there is a lot of information in the
datasheet that you don't yet know anything about! Good, now it's time to get 1. AVR Studio 4 supports a wide range of emulation and debugging tools.
developing! Click "Next" to advance to the next part of this tutorial. Since we have not purchased any of these yet, we will use the built in
simulator functionality.
AVR Studio 4 GUI 2. ..and we want to develop for the AT90S8515 device
Note: If you have not yet installed AVR Studio you should go to the Preparing 3. Verify all settings once more, then press "Finish" to create project and go
your PC for AVR Development section of this tutorial before continuing. to the assembly file
Step 1: Creating a New Project Step 4: Writing your very first line of code
Start AVR Studio 4 by launching AVR Studio 4 located at [START] | [Programs] AVR Studio will start and open an empty file named Leds.asm. We will take a
| [Atmel AVR Tools]. AVR Studio will start up, and you will get this dialog box. closer look at the AVR Studio GUI in the next lesson. For now note that the
Leds.asm is not listed in the "Assembler" folder in the left column. This is
because the file is not saved yet. Write in this line: "; My Very First AVR
Project" as shown in the figure below. The semicolon ; indicates that the rest
of the line should be treated as a comment by the assembler.
We want to create a new Project so press the "Create New Project Button"
To save the line press - S or select [Save] on the [File] menu. The Leds.asm
will now show up in the Left Column as shown below.
www.atmel.com
page 7
A T M E L A P P L I C A T I O N S J O U R N A L
OK, Now that we have AVR Studio up and running, it's time to take a closer Sample Code (~1kB)
look at the AVR Studio GUI..
Let's take a closer look at the AVR Studio Graphical User Interface (GUI). .include "8515def.inc" ;Includes the 8515
definitions file
1. The first line here is the "Menus" Here you will find standard windows Note that the source code changes color when written in the editor window.
menus like save and load file, Cut & Paste, and other Studio specific menus This is known as syntax highlighting and is very useful make the code more
like Emulation options and stuff. readable. Once the Source code is entered, press CTRL + F7 or select [Build
2. The next lines are Toolbars, which are "shortcuts" to commonly used and Run] from the [Project] Menu.
functions. These functions can be saving files, opening new views, setting
breakpoints and such.
3. The Workspace contains Information about files in your Project, IO view,
and Info about the selected AVR
4. This is the Editor window. Here you write your assembly code. It is also
possible to integrate a C-Compiler with AVR Studio, but this is a topic for
the more advanced user
At this point you 5. Output Window. Status information is displayed here.
6. The System Tray displays information about which mode AVR Studio is
should have installed running in. Since we are using AT90S8515 in simulator mode, this will be
the software, and started displayed here
it. If you can answer "Yes" Writing your First AVR Program
At this point you should have installed the software, and started up the a new
to both these questions, project called "Leds" You should also have the AT90S8515 Datasheet, stored
you are ready to continue somewhere you can easily find it. If you can answer "Yes" to both these ques-
tions, you are ready to continue writing some AVR Code. Congratulations!! You have now successfully written your first AVR program,
writing some AVR Code. and we will now take a closer look at what it does!
In the Editor view in AVR Studio, continue your program (which at this point
only consists of the first line below) by adding the text top of next colum. Note: If your program does not compile, check your assembly file for typing
(Cheaters can simply cut & paste the source below into AVR Studio...) errors. If you have placed the include files (8515def.inc) in a different folder
than the default, you may have to enter the complete path to the file in the
.include "c:\complete path\8515def.inc" statement. When it compiles we will
continue explaining and then debugging the code.
www.atmel.com
page 8
A T M E L A P P L I C A T I O N S J O U R N A L
www.atmel.com
page 9
A T M E L A P P L I C A T I O N S J O U R N A L
Press [ F11 ]. 0xFF is now written to PORTB register, and the arrows points
to the DEC instruction. Note that PORTB is equal to 0xFF. Note also that the
PINB register is still 0x00!
In our tools section we have also linked up all Atmel AVR Application Notes.
These are also very useful reading.
❑
Press [ F11 ]. DDRB is now 0xFF, As shown in the IO View above this is rep-
resented as black squares in the IO View. So, a white square represents logi-
cal low "0" and black squares are logical high "1". By setting DDRB high, all
bits of PORTB is configured as outputs.
www.atmel.com
page 10
A T M E L A P P L I C A T I O N S J O U R N A L
to interrupts and take the necessary action. Afterwards, normal program execution is
resumed.
and I/O with An interrupt service in other words is just like a subroutine; except that it is not
anticipated by the processor to occur at a particular time, since there are no
What's in a name?
When reading this article you will from time to time get the feeling that you
Eivind, AVRfreaks.net, are confronting a term possibly denoting an actual physical entity or an entity
By Eivind Sivertsen, in some sense relevant to the current activity; namely playing around or build-
We're gonna start out with some simple counting controlled by external inter- ing serious applications with the AVR...: INT0, INT1, GIMSK, PORTB,
AVRFreaks
rupts and exposed on the nice LEDs of the STK500. Then we'll add a speaker PB7 etc...
(Oh yeah!), and before we know it we'll have a miniature amusement park
on our desks; with lights AND noise and buttons to push! Perhaps fire as well, You are sure to come across such names in any assembly code, Atmel app-
Oct.2002 if something REALLY goes wrong. note, AVRfreaks Design Note or any posting in the AVRforum.
This is what we'll use:
One might think these are just common names used by individuals accustomed
1. AVRstudio 3 or 4 to the jargon, but we will try to use them consciously - in the sense that these
This article is a small project 2. STK500 development kit, all set up with your computer and ready to go names actually denote actual memory locations in the AVR you will be pro-
for you people who are just 3. An AT90s8515 microcontroller (usually comes with the STK500) gramming.
getting into the AVR, and 4. Some small speaker that works, including wires soldered in place
The mapping of these name to actual memory locations is in the part's def
perhaps even microcontrollers
The setup is based on a Windows configuration, but it is very possible use file (*def cacros vn unknown term:
in general.
some other software as well, since we won't concentrate much on the use of
AVRstudio besides assembling the project. If you are a Linux user, you could 8515def.inc Example snippet; only a few lines are shown
use: ;***** I/O Register Definitions
.equ SREG =$3f
.equ SPH =$3e
* avr-gcc (i.e. avrasm) for the assembly .equ SPL =$3d
* uisp for programming (~6kB) .equ GIMSK =$3b
.. .. ..
.. .. ..
The program will be written in assembly, because:
* assembly is very "machine-near" and provides a very educative approach When including this file in the assembly program file, all I/O register names
to what goes on inside the processor during our program and I/O register bit names appearing in the data book will be known to the
* high-level languages and different compilers all have different notations assembler and can be used in the program.
and routines for doing the same thing. Learning a compiler and the
respective C-style (e.g.) is a story of itself. Note that some high-level language compilers may use proprietary terms
other than these. But they will have files similar to this def file, defining the
The code for this project is something we found among leftovers from O'Guru memory space of the AVRs. As previously stated; this is another story.
Sean Ellis; which we brutally and without due respect ripped apart. Shame on
us. Another document that will prove very useful to anyone working with the AVR,
is this document:Manual you previously downloaded!
Basic interrupts
An interrupt is a flow control mechanism that is implemented on most con- 8515 datasheet
trollers, among them the AVR. In an MCU application interacting with the out- The datasheet.
side world, many things are happening at the same time, i.e. not in a syn- (~2MB)
chronized manner, that are to be handled by the microcontroller. The datasheet is the ultimate reference for any
AVR microcontroller. It even includes an instruc-
Examples: a switch pressed by the user, a data read on the UART (serial port), tion set summary; look up every instruction you
a sample taken by the ADC, or a timer calling to say that "time is up!". All don't know when you come across it!
these events neeeds to be handled by the MCU.
www.atmel.com
page 11
A T M E L A P P L I C A T I O N S J O U R N A L
www.atmel.com
page 12
A T M E L A P P L I C A T I O N S J O U R N A L
We are going to use the external interrupts INT0 and INT1 for the switches on
the STK500. These interrupts are enabled by setting INT0 and INT1 in GIMSK;
i.e. bits 6 and 7.
We will be using bits 0,1,2 and 3 in this register to control the interrupt from
INT0 and INT1. These bits control how to sense the external interrupts; either Just remember to couple the switches with the appropriate inputs on the
by level, falling edge on pin, or rising edge of pin: 8515; namely PORTD input pins PD2 and PD3. Use any two switches on the
STK500 you like; on the picture to the right I used switches SW0 and SW1.
ISCx1 ISCx0 Description Also connect the LEDs to PORTB with a 10-pin ISP connector cable.
0 0 Low level on INTx pin generates interrupt
0 1 Reserved When running this code on the STK500, at first all LEDs will be off. Press the
1 0 Falling edge on INTx pin generates interrupt switches a few times, and you will realize one of them counts something up,
1 1 Rising edge on INTx pin generates interrupt the other one down, and the results are reflected on the LEDs.
Let's have an overview of the program. Here's an example snapshot, after ini-
We will use the rising edge of the switch- tialization:
es on the STK500 to trig the interrupt; so
the 8515 must be programmed to trig
external interrupts on rising edges of each
pin PD2 and PD3. Hence; all the ISCx bits
must, for our program, be set to "1".
Real code part 1 OK, here is the entire program code, with some excessive comments removed
(these are still left in the available file). Look up any unknown instruction for
OK, let's start with the real code. Assuming you're already able to assemble
full understanding while you read through it. You can click each code block
your own code and even program the part in the STK500 - we'll just dig
label to jump to their respective comments next page.
through the code.
www.atmel.com
page 13
A T M E L A P P L I C A T I O N S J O U R N A L
.org $0000
removed (these are still rjmp Reset ; Reset vector
.org INT0addr
left in the available file). rjmp IntV0
.org INT1addr
; INT0 vector (ext. interrupt from pin D2)
Look up any unknown rjmp IntV1 ; INT1 vector (ext. interrupt from pin D3)
;------------------------------------------------------------------------------------
instruction for full under- ;
; Register defines for main loop
standing while you read .def TIME=r16
.def TEMP=r17
through it. You can click .def BEEP=r18
comments Reset:
ldi TEMP,low(RAMEND) ; Set stackptr to ram end
out SPL,TEMP
ldi TEMP, high(RAMEND)
out SPH, TEMP
ser TEMP ; Set TEMP to $FF to...
out DDRB,TEMP ; ...set data direction to "out"
out PORTB,TEMP ; ...all lights off!
out PORTD,TEMP ; ...all high for pullup on inputs
ldi TEMP,(1<<DDD6) ; bit D6 only configured as output,
out DDRD,TEMP ; ...output for piezo buzzer on pin D6
; set up int0 and int1
ldi TEMP,(1<<INT0)+(1<<INT1) ; int masks 0 and 1 set
out GIMSK,TEMP
ldi TEMP,$0f ; interrupt t0 and t1 on rising edge only
out MCUCR,TEMP
ldi TIME,$00 ; Start from 0
loop:
rjmp loop ; Infinite loop - never terminates
;----------------------------------------------------------------------------------
;
; Int0 vector - decrease count
IntV0:
dec TIME
rjmp Int01 ; jump to common code to display new count
;----------------------------------------------------------------------------------
;
; Int1 vector - increase count
IntV1:
inc TIME ; drop to common code to display new count
Int01:
mov r0,TIME ; display on LEDs
com r0
out PORTB,r0
reti
OK, lets go through the code step by step, though at a pace. It may be easi- vector table is defined. At $0000, the reset vector is set up. This is where
er if you have the source printed out next to you while reading the following the 8515 wakes up in the morning - everything is supposed to start from here.
comments: Also, the INT0 and INT1 vectors are set up, and their handling routines
The first lines includes the define file for the 8515; thus making all register named IntV0 and IntV1, respectively. Look up their labels down the code,
and I/O names known to the assembler. What happens next is the Interrupt and you can see where they are declared.
www.atmel.com
page 14
A T M E L A P P L I C A T I O N S J O U R N A L
Following this, registers r16, r17 and r18 have labels put onto them. This is no jump or return instruction. We could just as well have put in an
a way to make variables in assembly - only we also get to decide where rjmp Int01
they are placed in memory. Where? In registers r16, r17 and r18... hence;
they are all one byte wide. here as well. But we don't need it. Though it may be good common practice
to be consequent with this :-)
The reset label
Py-haa! The reset label contains all initialization code; this block is run at start- Now, take a last
up. The first 4 lines sets up the stack pointer, as mentioned earlier. Note how look at this figure
the ldi(load immediate) instruction is used to hold any value temporarily to recollect,
before writing to the actual location by out. low() and high() are macros before moving.
returning the immediate values of their arguments, which are memory loca-
tions defined in the .def file.
The next six lines sets the Data Direction Registers of ports PORTB (used for
LEDs) and PORTD (switches). Please check the datasheet under "I/O Ports"
for functional descriptions of these registers.
Now, notice this line: The timer overflow interrupt
ldi TEMP,(1<<DDD6) After stating our success with the
previous experiment, we are
This line of code simply (!) means: going to ameliorate this little
design a little more. We are going
"Load TEMP register with a byte value of 1 shifted DDD6 places leftwards". to add another interrupt into the
application; a Timer Overflow
Ok. Then what is DDD6? From the .def file, we find that this value is 6, and interrupt for the timer/counter
it is meant to point to the 6th bit of the PORTD Data Direction Register. The
0 of the 8515. Also, we're going
value loaded into TEMP and then into DDRB, becomes 01000000 in
to supply a small speaker to make
binary. Hence, the bit in this position in the DDRB register is set.
some noise.
So what happens? That pin (pin PD6) is to be used for a special twist in the
If you think the hardware requirements for this project are getting too demand-
Py-haa! next stage of the program, so that particular pin is set as an output; the oth-
ing now, you don't have to hook up the speaker. It is for illustrative purpos-
ers will be inputs. For now, just notice the notation.
The reset label contains es only, and your code will work perfectly well without it.
all initialization code; You can probably imagine what happens if you combine such notation in an Every which way; you will see how to set up the timer overflow interrupt and
addition? Well, this is what happens next, when the GIMSK register is write handling code for it.
this block is run at start-up. loaded, and then the MCUCR. Please refer to the previous section or the
The first 4 lines sets up datasheet for a description of these registers and why they are set this way. Timer overflow 0
The 8515 has two timer/counters; one 8 bits wide and one 16 bits wide.
the stack pointer, as Only thing remaining in the reset block now, is to call our friend the sei This means that they are capable of counting from any value you set, until they
instruction for enabling the interrupts we have just set up. reach their limit which is determined by the number of bits available (256 or
mentioned earlier.
65535, respectively). Then they will issue an interrupt, if you have set it up
The loop label to do so.
The loop label simply contains nothing but a call to itself. It's an equivalent
of writing while(1); in C. After reset is run, the program pointer falls through Upon overflow; the Timer/Counter just keeps counting "around" the range...
to the loop block and it will run forever only interrupted by - interrupts. so if you have set the timer to start from some special value and want it to
start from there again; you will have to reset it to that value. What we need
The IntV0 label to do in the code, is to add three little blocks of code more. These are (could
This label comtains the handling code for the INT0 interrupt. Whenever that you guess them?):
interrupt calls, this code will be run. It will simply decrement the TIME register.
Then it just jumps to a common block called...: 1. Another interrupt vector, for the TimerOverflow 0 interrupt: OVF0addr
2. Initialization code for timer/counter 0: TIMSK, TCCR0,TCNT0
The Int01 label 3. The interrupt handling subroutine.
This block consists of common code that displays the value of TIME (r16) on
the LEDs connected to PORTB. Note that the value is inverted by 1's comple- OVF0addr
ment (com instruction) before written to PORTB, since a low value means no This is the name set in the 8515def.inc file for the location where this inter-
light and vice versa. This block then performs a return to wherever it was called rupt vector should reside (check it, I may be pulling your leg). We add these
from through the reti instruction - which was from the loop label. two lines of code to the vector block:
www.atmel.com
page 15
A T M E L A P P L I C A T I O N S J O U R N A L
You are very able to read this now, and realize that it is just like the previ- CLK/2*Prescale*(256-TIME)
ous .org's in this program. Let's move on!
where TIME is the current value in the TIME register (r16).
...and again; the only TIMSK, TCCR0,TCNT0
Together, these 3 registers are all we need consider to have timing interrupts Also, the two switches affecting the value in TIME will make the buzz fre-
thing you really need to in an application on the AVR. quency waver up or down.
know for this little tutorial; TCCR0 controls the operation of Timer/counter 0. The count is incremented
is the position of one for every clock signal at the input of the timer. But the clock input can be
selected, and prescaled by N. We'll just consider the 3 lowest bits of this
special little bit: this one is register:
called "Timer/Counter0 TCCR0 Timer/Counter0 register
Overflow Interrupt enable", Bit 7 6 5 4 3 2 1 0
- - - - - CS02 CS01 CS00
abbreviated "TOIE0" and Read/write R R R R R R/W R/W R/W
Init. value 0 0 0 0 0 0 0 0
found in bit postition
Note that bits 7-3 are reserved, and always read as zero
1 of this register.
This table shows the different settings of these 3 control bits:
CS02 CS01 CS00 Description
0 0 0 Stop the timer/counter
0 0 1 CK
0 1 0 CK/8
0 1 1 CK/64
1 0 0 CK/256
1 0 1 CK/1024
1 1 0 Ext. pin T0, falling edge
1 1 1 Ext. pin T0, rising edge
...and again; the only thing you really need to know for this little tutorial; is Huh? Why is that the formula for the base frequency?
the position of one special little bit: this one is called "Timer/Counter0
Overflow Interrupt enable", abbreviated "TOIE0" and found in bit
? The Timer/counter counts up from some value
every clock cycle until it overflows. Then
postition 1 of this register. To enable our Timer interrupt; set this bit (to "1"). we reset it, to repeat the drill.
TCNT0 is the actual "Timer/Counter" register. This is where the timing and Let's say the timer can only count to 1
counting is done, in accordance with the settings in TCCR0. This is simply a before overflow. Flipping the pin every
time, will give us one cycle of a square-
register for storing a counter value; there are no special bits in it. It is entirely wave like waveform every 2 flips, right?
readable/writable; so you can load it with any desired starting value for your (up a while, then down a while, repeat...).
counting if you like. Note that it does not reset itself automatically, even if Hence, the base frequency would be:
an interrupt is issued. CLK/2
This is already becoming old news to you now, since it's just more or less Now; the Timer/Counter register is 8 bits
another instance of registers controlling similar functions that you have already wide, and can count from any value it is
set (TIME) to 255. The formula becomes:
heard about regarding the external interrupts... So let's go right to the code>.
CLK/2*(256-TIME)
Real code part 2
Besides; we have a prescaler which, when
For illustrating the Timer0 Overflow interrupt; we connect a small speaker to set to N, makes the Timer count just every
an output pin of the 8515. Each Timer0 overflow interrupt will toggle the pin. Nth cycle...
The result is that the speaker will buzz with a base frequency proportional to
CLK/2*N*(256-TIME)
the frequency with which the pin is toggled. I.e. the base frequency will be:
www.atmel.com
page 16
A T M E L A P P L I C A T I O N S J O U R N A L
These are the three snippets of code to insert. Please consult the complete ing every bit in BEEP (r18) with the com instruction, and then OR'ing it with
source code (INTs_2.asm, available below) to where the snippets are insert- this value 0xbf = 10111111 b (note the 6th position is '0').
ed:
.
.
Resetting Timer/Counter is obviously done by loading the value of TIME (r16) Good luck!
into TCNT0, and returning from the interrupt routine is done by issuing a reti
instruction.
Flipping the beep pin (PD6) is a little curious, however: This is done by invert- ❑
www.atmel.com
page 17
A T M E L A P P L I C A T I O N S J O U R N A L
Using the built-in power of the microcontroller bit needs to be set or cleared in a register before a bit in the corresponding reg-
A modern microcontroller has a lot of peripherals, and it is a time-consuming ister can be read or updated.
part of each embedded project to write the code needed to use that built-
in power and flexibility. It is a tedious work to read the hardware man- Get your product to the market quickly
ual and understand how peripheral modules like I/O, timers, USART, IAR MakeApp for Atmel megaAVR is a tool that guides you through the special
etc are implemented, and how the software is to get access to the function register hell, and helps you with the writing of device drivers. This new
hardware. Each peripheral is controlled via a number of special func- low-cost product from IAR Systems includes property dialog boxes which make
tion registers where each bit has a special meaning, and many of it easy to configure the megaAVR microcontroller to suit your needs. IAR
these bits need to be written and read using a specific protocol. MakeApp warns you if you try to make a setting that will occupy an already
used resource, e.g. the same I/O pin. The product also presents a visual view
Atmel megaAVR of the microcontroller and how the pins are configured. Special function regis-
The Atmel megaAVR devices are designed for flexible use with a lot of ter values are calculated automatically according to your settings, and a com-
powerful peripherals which limit the need of external components. These plete set of device drivers can be generated. The product also includes a com-
devices are well designed, and the peripherals can be set-up in many dif- ponent browser and a project report generation function that helps you with
ferent ways to support many different application needs. Because of the the design and documentation.
flexibility in the microcontroller, it is necessary to set up the pins in the way
your specific board is designed, and also to set the operation of the peripher- Device drivers generated by IAR MakeApp
als according to your product needs. For instance, the I/O input/output pins IAR MakeApp contains a powerful code generation technology, and generates
The Atmel megaAVR are multiplexed with peripheral pins, and need to be initialized according to a complete set of customized device driver functions according to your project
devices are designed for the hardware implementation. settings. The code generation engine uses the component database informa-
tion, and automatically calculates the special function register values according
flexible use with a lot of Application notes to the current property settings. ANSI C source code is generated for each
powerful peripherals One way to speed up the set up and coding is to use software application peripheral, and the files are well commented and easy to follow. The drivers
which limit the need of notes, which help to use the peripheral. The drawback with application notes include initialization, run-time control, and interrupt handling functions. The
external components. is that you do not have the same requirements for your product as the engi- functions are ready to be used by your application software and tested with
These devices are well neer who wrote the application note. Therefore, you need to update the spe- IAR Embedded Workbench for AVR and the Atmel STK500 starter kit. Use IAR
cial function register settings manually, and you might also need to modify the MakeApp from Idea to Target. “Click & Go” for driver variants during all phas-
designed, and the es of your embedded project.
application note source code to suit your needs.
peripherals can be
set-up in many different Software analysis Example: IAR MakeApp USART configuration, code generation, and usage
ways to support many If device driver software written for different products is analysed, you will see ATmega128 includes two USART channels for serial communication.
that most of these drivers are written in much the same way. The reason for
different application 1. Open the USART property dialog box in IAR MakeApp.
this is that the microcontroller is designed in a particular way, and therefore
needs. Because of the access to the special function register bits, such as control/status and data 2. Make the settings for the channel your hardware is designed for, and
the flexibility in the bits, needs to be done in a certain way. This actually means that a lot of engi- make the following minimum selection: Select operating mode,
activate USART receive/transmit pins, set baud rate, and define your
microcontroller, it is neers are writing the same kind of software for different products over and
over again. Writing the same kind of software at different places will also need protocol (number of data bits, parity, and stop bits). Finally, choose if
necessary to set up the you want to use interrupts.
a lot of extra testing to verify that the code runs correctly in the hardware.
pins in the way your 3. At any time you can view the special function register settings by
specific board is The special function register Hell clicking the Registers button in the property dialog box.
designed, and also to 4. The output generation tab in the USART property dialog box includes
Microcontrollers include hundreds of special function registers placed at certain
the device driver functions for USART that will be generated according
set the operation of the addresses in the address space, and it is common that a register is made up
to your current settings. The device drivers (APIs) for channel 0
peripherals according of many bitfields or bits. This means that the application needs to access or
normally include the following functions: MA_InitCh0_USART(),
to your product needs. control thousands of bits, and the access needs to be performed in the way
MA_ResetCh0_USART(), MA_PutCharCh0_USART(),
the microcontroller is designed for. Therefore, the productivity for modelling
MA_PutStringCh0_USART(), MA_GetCharCh0_USART(),
and writing device driver software is normally four times lower than ordinary
MA_GetStringCh0_USART(), MA_IntHandler_RX0_USART(),
software coding.
MA_IntHandler_TX0_USART(), MA_IntHandler_UDRE0_USART().
Some registers or bits are both read- and write-accessible, while others are only If your application software will only use some of these functions, you
accessible via read, write, set, or clear. It is also common that registers need can choose to have only these ones generated by the tool.
to be accessed via a specific protocol. Sometimes the register or bit needs to 5. Click OK to save the settings.
be read by the software before it can be updated with a write, set, or clear
instruction. Some registers are also related to each other, so that one register continued on page 40
www.atmel.com
page 18
A T M E L A P P L I C A T I O N S J O U R N A L
www.atmel.com
page 19
A T M E L A P P L I C A T I O N S J O U R N A L
With today’s stand-alone global position system (GPS) receivers, you are able GPS module receives the
What’s the more to pinpoint your own position. But, what’s more useful about stand-alone GPS
receivers is that they can transmit your position information to other receivers.
GPS signals and outputs the
data to the AT90S8515
laudable engineering We decided to use both of these features to create a wireless vehicle tracking
and control system for the Design Logic 2001 Contest, sponsored by Atmel
microcontroller via a TTL-level
asynchronous serial (UART)
feat, designing a and Circuit Cellar. interface. The microcontroller
works with the GSM module
navigation system To design the Port Navigation System, we combined the GPS’s ability to pin-
point location along with the ability of the Global System for Mobile
by communicating with the
GSM network. The interface
capable of tracking Communications (GSM) to communicate with a control center in a wireless
fashion. The system includes many GPS-GSM Mobile Navigators and a base
between the GSM module
and AT90S8515 is also TTL
ships in Shanghai station called the control center. async serial. An RS-232
interface is used to exchange
Port or placing at Let us briefly explain how it works. In order to monitor ships around a port,
each ship is equipped with a GPS-GSM Mobile Navigator. The navigator on
data with the PC.
the top of a compet- each ship receives GPS signals from satellites, computes the location informa-
tion, and then sends it to the control center. With the ship location informa-
Because the AT90S8151
has only one UART, a three-
itive design contest? tion, the control center displays all of the ships’ positions on an electronic map
in order to easily monitor and control their routes. Besides tracking control, the
channel multiplexer is used
to switch among three work-
With the award-win- control center can also maintain wireless communication with the GPS units to
provide other services such as alarms, status control, and system updates.
ing modes. The location
information and other data is
ning GPS-GSM Mobile Hardware
stored in the 2-Mb serial
data flash memory of the
Navigator, Ma and GPS became available in 1978 with the successful launch of NAVSSTAR 1. AT45D021. The flash mem- Photo 1—On the front side of the main board,
ory stores up to 2160 pieces you can see an LCD, four programmable keys, a
Later, in May of 2000, the U.S. government ended selective availability (SA);
Lin accomplished as a result, the GPS accuracy is now within 10 to 30 m in the horizontal plane of location information in 12 GSM module, an RS-232 connector, and some
h, because the GPS-GSM other components.
and slightly more in the vertical plane. For more information on GPS and its
both. accuracy, read Jeff Stefan’s article, “Navigating with GPS” (Circuit Cellar Mobile Navigator saves GPS
signals every 20 s. Four buttons, an LCD, and a buzzer enable you to display
123).
the system status and information and control the navigator.
The GPS-GSM Mobile Navigator is the main part of the Port Navigation
System. The design takes into consideration important factors regarding both Button
Ma Chao is a professor of LCD
control
position and data communication. Thus, the project integrates location deter-
Electronic Engineering at East mination (GPS) and cellular (GSM)—two distinct and powerful technolo-
China Normal University in gies—in a single handset (see Photo 1).
Shanghai, China. He is a spe- SPI
AT45D021
cialist in digital image com- The navigator is based on a microcontroller-based system equipped with a GPS Flash
AT90S8515
Alarm
Microcontroller
pression and processing, receiver and a GSM module operating in the 900-MHz band. We housed the memory
embedded control systems, parts in one small plastic unit, which was then mounted on the ships and con-
and computer network sys- nected to GPS and GSM antennas. The position, identity, heading, and speed
UART
tems. You may reach Ma at are transmitted either automatically at user-defined time intervals or when a
certain event occurs with an assigned message (e.g., accident, alert, or leav- Power
ma-chao@online.sh.cn. supply 3:1
ing/entering an admissible geographical area). Mux
Lin Ming is a graduate stu- This information is received by the system in the dispatching or operations cen-
dent completing a Master’s ter, where it is presented as a Short Message Service (SMS) message on a PC GPS RS-232 GSM
module module
degree in Electronic monitor. SMS is a bidirectional service for sending short alphanumeric (up to Interface
Engineering at East China 160 bytes) messages in a store√and√forward fashion. If the only data
received is time and position, then the data can be displayed on a digitized Figure 1—The AT90S8515 microcontroller is the basis for the GPS-GSM Mobile
Normal University. He works
map and also recorded in a database file; the recorded information can be Navigator.
primarily with embedded sys-
tems and microcontroller- replayed later for debriefing or evaluation of a mission.
System Features
based applications. You may
The hardware block diagram is shown in Figure 1. The AT90S8515 microcon- As we explained, the GPS module outputs the ship location information such
reach him at troller assures that all of the components work well together; it controls all as longitude, latitude, and Greenwich Time every 2 s. The location information
lmcrr@online.sh.cn. incoming and outgoing messages as well as the I/O channels, serial interfaces is then stored every 20 s in flash memory, which has enough power to mem-
(RS-232), peripheral devices (e.g., LCD and buttons), and all other parts. The orize the track of a ship even when the power is off.
www.atmel.com
page 20
A T M E L A P P L I C A T I O N S J O U R N A L
Table 1—The NMEA RMC data values are based on the following example: $GPRMC,161229.487,A,3723.2475,N,12158.3146,W,0.13,309.62,120598,,*10.
Note that the GSM wireless communications function is based on a GSM net- it then transmits the data in some standard format—normally in NMEA-0183
work established in a valid region and with a valid service provider. Via the format. When you’re building this project, it’s nice to be able to buy stand-
SMS provided by the GSM network, the location information and the status of alone GPS OEM modules. Just check the pages of Circuit Cellar for manufac-
the GPS-GSM Mobile Navigator are sent to the control center. Meanwhile, the turers. We used a Sandpiper GPS receiver from Axiom for this project. The
mobile navigator receives the control information from the control center via Sandpiper is intended as a component for an OEM product that continuously
the same SMS. Next, the GPS-GSM Mobile Navigator sends the information tracks all satellites in view and provides accurate satellite positioning data.
stored in flash memory to the PC via an RS-232 interface. (Note that you can With differential GPS signal input, the accuracy ranges from 1 to 5 m; howev-
set up the navigator using an RS-232 interface.) er, without differential input, the accuracy can be 25 m.
There are two ways to use the mobile navigator’s alarm function, which can The Sandpiper has two full-duplex TTL-level asynchronous serial data interfaces
be signified by either a buzzer or presented on the LCD. The first way is to (ports A and B). Both binary and NMEA initialization and configuration data
receive the command from the control center; the second way is to manually messages are transmitted and received through port A. Port B is configured to
send the alarm information to the control center with the push of a button. receive RTCM DGPS correction data messages, which enable the GPS unit to
Reprinted with permission provide more accurate positioning information. But, we didn’t require the use
of Circuit Cellar® - The GPS-GSM Mobile Navigator is powered by either a rechargeable battery or of port B for this project.
DC input.
Issue 151 About 45 s after the GPS module is cold booted it begins to output a set of
February 2003 Getting GPS Data data (according to the NMEA format) through port A once every second at
After the GPS module computes the positioning and other useful information, 9600 bps, 8 data bits, 1 stop bit, and no parity. NMEA GPS messages include
Table 2—Take a look at the 42-byte data package format and the following example ready to be saved: :10019999E121263457N311864290742160030000#.
www.atmel.com
page 21
A T M E L A P P L I C A T I O N S J O U R N A L
Figure 2—Jack port JP1 is the 20-pin GPS socket header. Jack port JP2 is the 40-pin GSM socket header. U2 is the dual four-channel multiplexer controlled by PA2 through
PA3. All of the data traffic runs at 9600 bps.
six groups of data sets: GGA, GLL, GSA, GSV, RMC, and VTG. We use only the and by 1993 there were 36 GSM networks in 22 countries, with 25 additional
most useful RMC message—Recommended Minimum Specific GNSS Data— countries looking to participate. Furthermore, the standard spread quickly
which contains all of the basic information required to build a navigation sys- beyond Europe to South Africa, Australia, and many Middle and Far Eastern
tem. Table 1 lists the RMC data format. countries. By the beginning of 1994, there were 1.3 million subscribers world-
wide. Today, GSM is also the most widely used communications standard in
We only need position and time data, so the UTC position, longitude with China, and covers almost all of the country. So, we didn’t need to set up a
east/west indicator, and latitude with north/south indicator are picked out communications base station for our system; this, of course, significantly
from the RMC message. All of this data will be formatted into a standard fixed- reduced the total cost of the project. The most basic teleservice supported by
length packet with some other helpful information. Next, this data packet will GSM is telephony. Group 3 fax, an analog method described in ITU√T recom-
be transmitted to the control center and stored in the AT45D021’s flash mem- mendation T.30, is also supported by the use of an appropriate fax adapter.
ory. SMS is one of the unique features of GSM compared to older analog systems.
For point√to√point SMS, a message can be sent to another subscriber to the
The data packet is a 42-byte long ASCII string, which includes the package ID, service, and an acknowledgment of receipt is sent to the sender. SMS also can
system password, terminal ID, position data, UTC, and other operational infor- be used in Cell Broadcast mode to send messages such as traffic or news
mation. Table 2 shows the definition of a reforming data packet and an exam- updates. Messages can be stored on the SIM card for later retrieval.
ple ready to be saved or transmitted.
SMS is effective because it can transmit short messages within 3 to 5 s via
GSM TRANSMITS DATA the GSM network and doesn’t occupy a telephony channel. Moreover, the cost
A committee of telecom vendors and manufacturers in Europe—the European savings makes it a worthwhile choice (i.e., in China, each message sent costs
Telecommunications Standards Institute (ETSI)—designed GSM as a digital $ 0.01 and receiving messages is free). With SMS transmitting, gathering
wireless communications system. Commercial service began in mid√1991, position data is easy and convenient.
Command Definition
PROJECT FILES
AT+CSCA Set the SMS center address. Mobile-originated messages are transmitted through this s
To download the pin assignments and ervice center.
source code, go to ftp.circuit AT+CMGS Send short message to the SMS center
cellar.com/pub/Circuit_Cellar/ AT+CMGR Read one message from the SIM card storage
2003/151/. AT+CMGD Delete a message from the SIM card storage
AT+CMGF Select format for incoming and outgoing messages: zero for PDU mode, one for Text mode
AT+CSMP Set additional parameters for Text mode messages
Table 3—To send SMS messages, you can use these (mainly) AT commands. For more details, you may want to read the GSM 07.07 protocol on the ETSI web site.
www.atmel.com
page 22
A T M E L A P P L I C A T I O N S J O U R N A L
www.atmel.com
page 23
A T M E L A P P L I C A T I O N S J O U R N A L
Mode = 1
One MAX202 chip accomplishes the conversion between TTL/CMOS level and
RS-232 level, which is necessary for the RS-232 interface between the navi-
To set gator and PC. Using the RS-232 port, the system can backup the data in flash
GSM module
work mode memory to the PC. Also, you can change some system parameters through the
PC via the RS-232 port.
To set
a 1-s timer
With two control pins and four data pins, the AVR gives the LCD specific infor-
mation to display. Port pins PC2 through PC4 individually sense the three push-
The time button switches. There is a Menu button to select the work mode, and an Enter
is even second
Even
or odd second
Odd
button to confirm the selection. The third is an SOS button used to send an
alarm message to the control center.
Read
Else The time GPS information
12, 16, 18 s
is what? from GPS
module
Software Description
We used the powerful BASCOM-AVR to develop the software. An IDE is pro-
Check Save GPS Check if
there is a short
N vided with an internal assembler. You can also generate Atmel OBJ code.
GSM status data to
flash memory message Additionally, the BASCOM-AVR has a built-in STK200/300 programmer and
Y terminal emulator. Other notable features include: structured BASIC with
Let GSM module
Display short labels; fast machine code instead of interpreted code; special commands for
send GPS data out
according to given
message for
4 s, and then clear
LCDs; I2C; one wire; PC keyboard and matrix keyboard; RC5 reception; and
interval
RS-232 communications. The BASCOM-AVR has an integrated terminal emula-
tor with download option, an integrated simulator for testing, and an integrat-
ed ISP programmer.
Display messages or
alarm according to
the process done above
You can easily write the firmware for this project using the BASCOM-AVR. And
with the ISP benefit of AVR, on-line emulation is almost unnecessary, so you
Count to Y Clear can program and test with ease. The flow charts in Figures 3 and 4 describe
20 s counter to 0
the AT90S8515 program that controls the devices. The software handles a
N
number of key functions, such as initializing the system and starting the GPS
and GSM modules. The software also selects the working mode. Additionally,
Figure 4—The main function is mode 1. The AT90S8515 microcontroller receives it checks and sets the system parameters in mode 0, backs up the trace data
the ship location data every 2 s from the GPS module, and then saves the data in
stored in flash memory to the PC in mode 2, and resets the system parame-
flash memory every 20 s. At a user-defined time interval, the AT90S8515 sends
ters in mode 3.
the location data to the control center, and then receives the control information
from the control center via the GSM module.
Our system is now being used Mode 1 is the standard working mode during which many tasks are complet-
ed. During mode 1, the GPS signals are read every 2 s from a satellite; the
in Shanghai Port, China for flash memory to backup to PC. Up to 2160 pieces of information can be stored location information is saved in flash memory every 20 s; and the GSM mod-
in flash memory. Because the AT90S8515 has only one UART port, another ule sends location data to the control center according to the given interval
navigation and monitoring of chip is used to expand the serial port for three kinds of different functions. The time. Meanwhile, the navigator receives the control information from the con-
digitally controlled MC14052B analog switch is a dual four-channel multiplex- trol center from the GSM module.
ships. Aside from tracking er. With two I/O pins, the AVR controls it to switch among three channels, all
ships, the GPS-GSM Mobile of which are UART serial interfaces. ❑
www.atmel.com
page 24
A T M E L A P P L I C A T I O N S J O U R N A L
AT86RF401
Reference Design
By Jim Goings, Applications Manager, Atmel, North American RF&A
It seems that many systems are requiring a radio frequency (RF) wireless link. PLL. The PLL contains an internal divider fixed to 24 so the RF carrier will
AT86RF401 We don’t like standing on a chair to adjust the ceiling fan speed, we don’t like
climbing out of our car to open the garage door, and we certainly don’t like
always be 24 times the frequency of X1 (24*13.125MHz = 315MHz). The
VCO requires L2 to put its output in a controllable range enabling the PLL to
Reference walking outside on an early winter morning to see just how cold it is. Whether
we’re driven by cost, convenience, or performance, low cost RF wireless
closely track the reference frequency X1. All that’s left to finish the design is
to attach a tuned antenna to the chip and your hardware is ready. The com-
designs are here to stay. So, if you’re not an expert in manipulating Maxwell’s plete Parts List is shown in table 1 below.
Design equations… is there an easy way to add RF to your design?
To minimize cost (while not the most efficient way to radiate RF), a tuned loop
Fortunately, the answer is an emphatic YES. Atmel made your work much eas- PCB trace antenna can be used. A reasonable impedance match between the
ier by recently introducing the AT86RF401, an RF wireless data micro-trans- output of the AT86RF401 and the PCB trace antenna AND assurance of an
mitter. By developing a chip that integrates the mysterious part of the RF Federal Communications Commission (FCC) compliant design can be obtained
transmitter design (normally reserved for an RF expert) and throwing in an using the component placement and geometry of the traces as shown in Figure
AVR® microcontroller, your life just got a little bit simpler. 1a (top side PCB artwork including antenna) and Figure 1b (bottom side PCB
artwork). Complete PCB design and fabrication documentation is available
The heart of this chip is an AVR® microcontroller that’s been given supervisory upon request. See contact information at the conclusion of this article.
responsibility over a narrowband Phase-Locked-Loop (PLL) RF transmitter.
What sets this device apart from many on the market today is that the solu- In this design, peak resonance of the tuned loop antenna occurs with a non-
tion is a true System On a Chip (SOC). It isn’t a multi-chip package where standard capacitance value. So, three capacitors, C2-C4, are required to be
each chip was designed by different teams having different priorities. Rather, connected in series to achieve this equivalent capacitance. This isn’t neces-
it is a SINGLE chip resulting from the cooperative efforts of a cross-functional sarily a bad thing as a benefit to a series connection of three capacitors is a
design team where the RF and control logic were designed to work togeth- reduction in the overall variation of the equivalent capacitance.
er… from the beginning. With access to key RF control parameters such as
ATMEL REMOTE KEYLESS ENTRY TRANSMITTER 315MHz version (REV B1 APRIL 15, 2003)
Item Moose Qty Ref Designator Description Manufacturer Part Number Value Tolerance Rating PCB Decal
1 2 C2 C4 0603 SIZE SMT CERAMIC CAPACITOR Any 6p8F +-.25pF 50V NPO 603
2 1 C3 0603 SIZE SMT CERAMIC CAPACITOR Any 33pF 5% 50V NPO 603
3 2 C1 C8 0603 SIZE SMT CERAMIC CAPACITOR Any 100pF 5% 50V NPO 603
4 1 C7 0603 SIZE SMT CERAMIC CAPACITOR Any 10nF 10% 50V X7R 603
5 1 J1 2032 COIN CELL HOLDER SMT KEYSTONE 1061 KEYSTONE-1061
6 1 J2 3X2 PIN 0.1" RIGHT ANGLE HEADER 3M 929838-04-03 RTHEAD-2X3
7 1 L2 0603 SIZE CHIP INDUCTOR COILCRAFT 0603CS-82NXJB 82nH 5% 603
8 4 R1 R2 R3 R4 0603 SURFACE MOUNT RESISTOR Any 1k 5% 1/16 W 603
9 4 S1 S2 S3 S4 LIGHT TOUCH SWITCH PANASONIC EVQ-PPDA25 PANASONIC-EVQ-PP
10 X 1 U1 "SMARTRF" WIRELESS DATA ATMEL AT86RF401U TSSOP20
11 X 1 X1 CSM-7 STYLE SMT CRYSTAL CRYSTEK 16757 13.125MHz +/-20ppm CL 20pF ECS-CSM-7
12 1 PCB 1 PRINTED CIRCUIT BOARD JET AT0308 rev B
output power attenuation, voltage controlled oscillator tuning, RF modulation Software development for this device can be done using AVRStudio. A recent
and PLL lock/unlock criteria, the AVR core takes much of the headache out of upgrade, AVR Studio4, now includes drop down menus unique to the
getting your RF link’s performance up to where you’d like it. AT86RF401. When used with an AVR Starter Kit, STK500, a complete soft-
ware development environment including editing, assembly, simulation, and
The AT86RF401 (see Figues A; page 40) is designed to operate down to serial flash programming can be realized.
2.0V. C1, C7, and C8 provide an attenuation path to ground for unwanted
high frequency transients. J2 provides an interface to the software develop- But, if you’re anxious to start playing with the hardware in the lab, try using
ment tools and allows you to flash the AVR®’s memory while it’s still soldered the SPI Controller software (included with the AT86RF401U-EK1 Evaluation
onto the PCB. Switches, S1 – S4, along with the current limiting resistors, R1 Kit). The SPI Controller gives you real time access to the key registers within
– R4, trigger an event that awakens the device from a very low current sleep the AT86RF401 that control the RF transmitter using a graphical user interface
mode (typically less than 100 nA) and initiates the RF transmission. (GUI) as shown in Figure 2. By connecting the cable & dongle assembly (pro-
vided in AT86RF401U-EK1) between the parallel port of your PC and the pro-
The rest of the parts on the PCB support the RF transmitter. While X1 provides gramming header on the reference design, you'll be ready to go! Once you’ve
a clock source for the AVR®, it also is used as the reference frequency for the connected your hardware and initialized the software, you can toggle the
www.atmel.com
page 25
A T M E L A P P L I C A T I O N S J O U R N A L
• initialization of digital logic (e.g. AVR clock divide, stack pointer, I/O
definition, etc.) and RF control registers (e.g. fine tuning the VCO, defining
the PLL lock detector criteria, selecting output power, etc.)
• controlling the RF signal
• entering the sleep mode after RF transmission is complete
Upon power up, the program counter is reset to 0x0000 and execution begins
at the “Reset” label. Initialization starts with establishing the AVR clock divider
ratio and defining the stack pointer address. After these tasks are completed
the “VCO” subroutine is called. This subroutine steps through an internal VCO
tuning capacitor array to determine the optimal setting for the tuning capacitor
array. This tuning process monitors both the PLL’s ability to lock (TX_CNTL,
Bit[2]) and the value of the VCO’s control voltage window comparator (VCO-
Figure 1a Figure 1b
appropriate bits in various registers to do things like change the output power
of the RF signal (PWR_ATTEN[5:0) or activate the RF power amplifier
(TX_CNTL[6:4,2]. Be sure to check out some of the canned routines located
under the tool button labeled “PRESET FUNCTIONS” as shown in Figure 3.
There are quite a few helpful programs that will allow you to evaluate many
aspects of the RF transmitter without having to write any software.
Now that you’ve had a chance to try out the ‘401 in the lab using the SPI
Controller tool, it’s time to understand a sample software program that was
developed to demonstrate the generation of a constant RF carrier whenever
any of the switches S1 through S4 are pressed.
Figure 4
Using the AVRStudio4 and file CW Mode.asm as an example (see Figure 4),
the essential elements of the software are:
TUNE, Bits[7:6]). When both of these conditions are determined to be accept-
able, the value of the tuning capacitor is retained in VCOTUNE, Bits[4:0].
This design was successfully tested for FCC compliance and yielded an
output field strength of 85.8 dBuV/m. The FCC limit at 315MHz is
75.62dBuV/m but up to 20dB of relaxation on this limit is allowed if
the RF is modulated. This raises the FCC limit to 95.62dBuV/m. This
Figure 3
www.atmel.com
page 26
A T M E L A P P L I C A T I O N S J O U R N A L
means the design has a margin of 9.8dB. Results of FCC compliance testing ited by the AT86RF401) for a duration of 61.8 mS and still meet the limits of
for the fundamental and harmonics of interest are shown in Figures 5 and 6. the FCC requirements for intermittent operation as defined in FCC part
15.231, “Periodic operation above 70 MHz”. Under these conditions, 618
The formula to calculate the relaxation factor is: bits of data could be sent at a data rate of 10Kb/S and the transmitter would
dBrelaxation = 20log(100mS/mS the RF is “on” time during 100mS) still be FCC compliant!
Based on the margin of 9.8dB measured in the lab, we can calculate the max- As you can see, the AT86RF401 can make adding an RF link to your system
imum amount of RF is "on" during 100mS interval to determine the theoreti- easy and economical priced at only $1.36 in quantities of 100K. To get your
cal boundary of our modulation scheme. Using the equation above we can design to market faster, try ordering an evaluation kit that contains the hard-
solve for RF “on” time as follows: ware and software described in this article. Your local Atmel distributor can
provide this for $199. Use the order number AT86RF401U-EK1 for a 315MHz
20dB - 9.8dB = 20log(100/tRF”on” ) design or AT86RF401E-EK1 for a 433.92MHz. Both are available in stock
tRF”on” ≤ 30.90mS today!
continued on page 40
For more information on this product or for additional design documentation,
Based on this information, it would be possible to modulate the RF carrier
you may contact the author by phone: 719-540-6873 or email:
using On-Off-Keying with a 50% duty cycle at a data rate of up to 10KHz (lim-
jgoings@atmel.com. ❑
Figure 5
Figure 6
www.atmel.com
page 27
A T M E L A P P L I C A T I O N S J O U R N A L
An RF-Controlled
Irrigation System
With access to a By Brian Millier
steady water supply, When I sat down to write this article last fall, the leaves on the trees had not
yet turned their autumn colors, but the beauty of the flowers in our garden
Brian’s garden beds was certainly on the wane. It was a dry summer, particularly punishing and
for farmers, and our gardens weren’t particularly splendid last year. Not that I then for-
should flourish in didn’t try to keep them well watered, it’s just that it’s hard to beat a steady get to return to the
dose of rainwater. basement to turn off the pump. One
even the driest of year I damaged the pump by leaving it on for sev-
We’re fortunate to have built a home on a large lake. Twelve years ago, we eral days! Also I was getting lazy; I didn’t like the trouble
times. Having caught chose the lot based mainly on recreational concerns—swimming, canoeing, of hooking up a hose, unraveling 100 feet of it into the desired position,
and such. I became seriously interested in gardening about five years back, attaching a sprinkler head, and then having to walk all of the way back to the
wireless fever, he and decided to install an irrigation system to make use of the unlimited sup- other end to turn on the water valve.
ply of “free” water.
set out to use an I decided what I needed was a controller that allows me to program specific
Our lot is about 25 feet above the lake’s level. As any mechanical engineer watering times and durations. Units like this are commercially available, of
AVR and some RF will tell you, it’s a lot easier to “push” water than it is to “pull” it, so I installed course, but I also wanted to be able to control the water using a small keyfob
a 0.75-hp jet pump at the water’s edge. I decided against using a pressure transmitter while I puttered around in the gardens.
products to man the tank and switch, as the water would be needed only when the pump was
switched on, and the maximum continuous flow rate was desirable. In my last article, I described a wireless MP3 player, which used low-cost UHF
pump and close the transmitter/receiver modules from Abacom Technologies (“Listen
Because most of the rough landscaping had been done when the house was Everywhere,” Circuit Cellar 134). I was pleased with their performance and
valves. Now, water- built, I decided it would be too much effort and expense to bury irrigation lines technical support from Abacom, so I decided to check out Abacom’s products
throughout the 0.75 acre of lawn and gardens that I have. Instead, I ran 1.5≈ again.
ing only takes a plastic pipe on the surface, along the side border of my property. Six
valves/garden hose fittings are spaced along the 400 foot length. I wanted the transmitter to fit in a keyfob, so I chose the AT-MT1-418 AM
press of the green transmitter module, which is about the size of a penny. I also chose Abacom’s
For a number of years, I was content to run down to the electrical panel in the keyfob transmitter case, which comes in various switch cutout configurations.
thumb. basement to switch on the pump when I wanted to do some watering. Besides I decided to use a sensitive receiver because I anticipated a low transmitted
being inconvenient, occasionally I’d shut off the water valves when finished signal level given such a small transmitter. The QMR1 Quasi AM/FM superhet
receiver module fit my needs. I particularly like this module because its 1-
square-inch SIP mounts easily on a circuit board by pins on 0.1≈ cen-
Author’s Note: I want to ters. I like one-stop shopping, so of course I was pleased to be able to
thank John Barclay of get Holtek encoder/ decoder chips from Abacom, as well. I’ll describe
Abacom Technologies for the the chips in more detail later in the article.
support and samples that
helped out significantly while Controller/Receiver
I was putting this article If you’ve read my recent articles, it should come as no surprise that I
used an Atmel AVR controller chip, the AT90S8535-8PC (40-pin DIP
together.
package), for this project. This device contains four 8-bit ports, eight 10-
bit ADC channels, 8 KB of flash memory, and 512 bytes each of data
Brian Millier is an instrumen- EEPROM and RAM. Like most AVR devices, this one is easily serially pro-
tation engineer in the grammable in-circuit. You may want to refer to my article, “My
Chemistry Department of fAVRorite Family of Micros” (Circuit Cellar 133) for an overview of this
Dalhousie University, Halifax, family, along with the details of a free ISP programmer for these chips.
Canada. He also runs
Computer Interface I must admit up front that I probably could have done this project with
Consultants. You may reach the smaller AT90S2313 by multiplexing some of the I/O pins and writ-
ing the program in assembly language. I decided it was more produc-
him at brian.millier@dal.ca.
tive for me to spend the extra dollars (Can $) on the ’8535, whose
larger flash memory would allow me to program in BASIC, using the
Photo 1—Here’s the actual controller/receiver sitting in my family room. Just visible in the
BASCOM AVR compiler.
background is a glimpse of the lake—the source of water for the gardens. Not visible is the
AC adapter used for power or the power relay, which is located at the electrical panel in the
basement.
www.atmel.com
page 28
A T M E L A P P L I C A T I O N S J O U R N A L
Figure 1 is a schematic of the controller/receiver. Let’s start by looking at the nect the 32,768-Hz watch crystal between the TOSC pins 1 and 2 with no
user interface. The user interface consists of a 4 ˘ 20 LCD and four push but- capacitors to ground. [1]
tons. The display is operated in the common 4-bit mode; in this case, because
it saved some wiring, not because of a shortage of I/O pins. When I did this, I could see a reasonable 32,768-Hz sine wave signal on either
crystal pin with my oscilloscope using a 10˘ probe. I soon discovered, though,
The four push-button switches are individually strobed by port pins PC0–3 and that my clock was losing about 1 min./h. After troubleshooting, I found that
sensed by the INT1 input of the ’8535. I hooked up the switches this way the crystal oscillator waveform contained serious glitches coinciding with LCD
because I originally drove the LCD using the same four port C lines. I had been screen refreshes.
saving the ADC inputs of port A for future use, but later changed my mind and
switched the LCD over to port A, leaving this switch circuit intact. At that point, I was using the port pin adjacent to TOSC1 to drive the LCD
ENABLE pin. Moving the LCD ENABLE pin over to port A eliminated the glitch-
The four push-button switches operate this unit the same way that many small es, but the clock was still slow. This was odd because I could not see anything
electronic devices work. There is a Menu button to scroll through several wrong with the crystal waveform with my oscilloscope, and the built-in fre-
menus as well as a Select/Cursor button. The buttons are used to position the quency counter in the oscilloscope indicated that the frequency was “bang-on.”
cursor within a time field for adjustment purposes or to select a particular value So next, I contacted Mark at MCS Electronics to see if he had run into the prob-
when finished changing it. Finally, there are plus sign and negative sign but- lem. He mentioned capacitors, which made me think that capacitance to
tons used to increment or decrement the current parameter. ground was probably needed (contrary to the datasheet). It turns out that my
oscilloscope was providing the necessary capacitance, but only when it was
I chose to implement the real-time clock in the software. One reason I initial- hooked up. Adding 22-pF capacitors to ground cured the problem, at least with
ly picked the ’8535 over the slightly less expensive ’8515 is because it the particular crystal I was using. However, for this project, I decided to play it
Reprinted with permission includes a third timer, which may be driven by a 32,768-Hz watch crystal. I
must say that my attempts to implement the RTC using this feature gave me
safe and implement the RTC using Timer0 of the ’8535 clocked by the
4.194304-MHz crystal of the CPU, which works perfectly. A side effect of this
of Circuit Cellar® - some problems! Atmel’s datasheet for the ’8535 advises you to merely con- was that I couldn’t use BASCOM’s intrinsic real-time clock function and instead
had to write my own routine.
Issue 138
January 2002
Figure 1—The Atmel 8535 AVR controller is at the center of the action of the irrigation controller. An Abacom QMR1 receiver takes care of the wireless reception func-
tions. The LCD operates in 4-bit mode.
www.atmel.com
page 29
A T M E L A P P L I C A T I O N S J O U R N A L
My pump draws about 10 A when running (much more when starting), so I that cover in depth the theory of reliable RF data communication; An
chose a Potter & Brumfield T9AP5D52-12, which is inexpensive and rated for Introduction to Low Power Radio by Peter Birnie and John Fairall is a good
20-A continuous current. A small 2N3904 transistor is all that is needed to starting point for those of you starting out in this area. [2]
handle the 200 mA that its coil requires. This sealed relay is small. I haven’t
used it long enough to know how well it will hold up, so the jury is still out on Encoder/decoder
this component choice. To address these concerns, it made sense to use the inexpensive line of
encoder/ decoder devices from Holtek (HT12D/E) rather than roll my own.
The controller/receiver is powered by a 9-VDC adapter followed by a 78L05 These matching chips address the concerns, at least for applications that need
regulator. The actual output of the adapter is closer to 12-V, and is enough to only to transmit the status of a small number of switches.
operate the relay coil. Photo 1 shows the controller in place in my family room.
The wireless part of the controller consists of an Abacom QMR1 receiver fol- There are a number of good reasons for choosing this device. The HT12E
lowed by a Holtek HT12D decoder chip. This receiver is one of the choices rec- encoder chip consumes only about 0.1 µA in Standby mode, so it can be left
ommended for use with the AT-MT1 AM transmitter that I use. The datasheet permanently connected across the small transmitter battery. It comes in a
that comes with the package (available soon on www.abacom-tech.com) calls small, 20-pin SOP and fits in a small transmitter case (the same could be said
the QMR1 a quasi-AM/FM receiver module. The datasheet doesn’t spell out if for the Atmel ATiny and smaller PIC processors). To reduce parts count and
it also works with FM transmitters, but it sounds like it would. cost, it uses a single resistor to set its internal RC clock. RC clocks are not
known for their frequency stability; the design of this encoder/ decoder pair
In any AM transmitter/receiver link, one thing for certain is that the receiver allows the receiver to be able to lock onto the transmitter’s data clock fre-
will spit out a stream of noisy data during much of the time when its com- quency even though it may vary considerably over time or temperature. Refer
panion transmitter is not transmitting. The QMR1 is sensitive (RF sensitivity to Figure 2 for the schematic of the transmitter module.
specification is –110 dBm) and it has no squelch circuitry to suppress spuri-
ous output signals arising from any RF interference that it might receive. With Both the encoder and decoder sample eight lines (A0 through A7), which act
cell phone towers cropping up all over the countryside, even my rural home is as device address inputs. That is to say, a given encoder/decoder pair can be
probably not “RF-quiet” anymore. I definitely see lots of noise output from the set to operate at one of 256 discrete addresses. This strategy, for example, pre-
QRM1 receiver module. vents your neighbor’s remote control from operating your garage door opener.
My intention is to emphasize the need for some form of error detection/ data Addressing can be done with a dip switch, jumpers, or by cutting traces on a
formatting in any AM RF link. What I haven’t mentioned is that the circuitry in PCB. Modern encoder/decoder chipsets used in remote car starters use, by
the receiver that recovers the data from the RF signal (called the data slicer) necessity, a much more complex addressing scheme because there’s a much
is choosy about the form of data modulation that it will accept. greater chance of false triggering by other, unintended transmitters in the vicin-
ity. Obviously, this leads to worse repercussions.
For example, most data slicers work reliably only if there is a roughly even dis-
tribution of zeros and ones in the datastream, even within the short-term such The data packet sent by the HT12E consists of the 8-bit address followed by a
as the time taken to send 1 byte of data. This means that you cannot, for 4-bit data field corresponding to the state of up to four switches connected to
example, just feed in the signal from a UART
to an AM transmitter, and expect to hook up
SOFTWARE a UART to the receiver output.
To download the code, go to
ftp.circuitcellar.com/pub/Circuit_ Instead, Manchester encoding is generally
Cellar/2001/138/. used because it guarantees an equal number
of zeros and ones in the datastream, regard-
REFERENCES less of the particular data being sent.
[1] Atmel Corp., “8-bit AVR Furthermore, it is good practice to send the
Microcontroller with 8K Bytes same data several times and check that it
In-System Programmable matches when it comes out of the receiver. A
Flash—AT90S8535 final precaution could include some form of
checksum or better still, a CRC byte in the
AT90LS8535,” rev. 1041GS, data packet to further verify the integrity of
September 2001. the received data.
[2] P. Birnie and J. Fairall, An
Another concern is the amount of time it
Introduction to Low Power
takes the receiver to adjust itself to the
Radio, Character Press Ltd., UK,
strength of the incoming signal or wake up
1999.
from an idle state if that feature is present in
[3] Holtek Semiconductor Inc., “212 Series
your receiver module. To allow for this, the
of Decoders,” July 12, 1999.
transmitter must send out a short stream of
known data, called a preamble, to allow the
[4] ———, “HT12A/HT12E 212 Series receiver to get ready for data reception, so to
of Encoders,” April 11, 2000. speak.
This is a lot tougher than your average RS- Figure 2—There isn’t too much to the schematic diagram of the keyfob transmitter. However, getting it to fit into the
232 serial data link! There are many books small keyfob was another matter!
www.atmel.com
page 30
A T M E L A P P L I C A T I O N S J O U R N A L
www.atmel.com
page 31
A T M E L A P P L I C A T I O N S J O U R N A L
Designer’s
Corner:
Again life was good. But I had learned my lesson and remembered the con-
cept of flexibility. What if I were to need more space? More holes to put extra
components that the microcontroller needs to fully work as intended in the
desired application. The ProtoXP (from Prototype Expander) gives new added
flexibility as even more holes with the same architectural pattern can now be
plugged into one of the PBMB slots.
Figure 1
www.atmel.com
page 32
A T M E L A P P L I C A T I O N S J O U R N A L
To allow the board to be pro- Finally, but equally important, each board contains a female DB9 meant for RS-
grammed, the MINIPB includes an 232 communications. The board does not include the RS-232 driver, but there
ISP connector per chip, compatible is enough space to interface such device if needed.
with the ATAVRISP cable.
AT90S15PB and AT90S35PB boards These projects boards can be used as a stand alone unit, but in the case more
include the same ISP connector plus than one are to be interconnected the PBMB offers such capability. The PBMB
the JTAG connector that allows in cir- does contain the fully functional RS-232 standard driver and is ready to work.
cuit debugging, as well as program- Just patch the RS-232 Rx and Tx to the microcontroller through the edge con-
ming, with the ATJTAG-ICE cable. The nector bus and the application has PC compliant serial communications. The
boards also include a good set of pins PBMB also offers voltage regulation to generate 12V and 5V.
Figure 3
and pads that connect to the micro-
The last board is the ProtoXP. Its middle name is expandability and it is noth-
controller ports. This is the place were the microcontroller is connected to the
ing more than an extended prototyping area to add more and more compo-
external peripherals localized on the huge prototyping area. The prototyping
nents to the embedded system application. It has the same edge connector so
area is not a bunch of independent holes as in other prototyping boards. There
that it can be connected on the PBMB along with other Project Boards.
are spaces were the holes are connected to other holes, but there are as well
patches of independent holes and power planes holes. Conclusion:
The ideas behind Avayan Electronics’ Project Boards are modularity, flexibility
and general purpose design. Users will find that a project based on a mother
board is desirable as it allows for the different modules to be worked upon.
Obviously this implies expandability as well. Because the boards are not set in
stone and simply include all the necessary circuitry for the microcontroller to
work, as well as a good amount of prototyping area, any application can be
designed. Some designers may argue that the boards are too simple and that
some important components are missing like LED’s, drivers, etc. Because not
everybody needs the same features, the boards were designed as general pur-
pose as possible. The huge prototyping area should be enough to accommo-
date such needed features. For more information visit www.avayanelectron-
Figure 4
ics.com or contact Avayan@avayanelectronics.com. ❑
www.atmel.com
page 33
A T M E L A P P L I C A T I O N S J O U R N A L
www.atmel.com
page 34
A T M E L A P P L I C A T I O N S J O U R N A L
www.atmel.com
page 35
A T M E L A P P L I C A T I O N S J O U R N A L
www.avrfreaks.com
www.atmel.com
page 36
A T M E L A P P L I C A T I O N S J O U R N A L
STK500
The STK500 is a starter kit and development system for Atmel’s
tinyAVR, megaAVR and LCD AVR devices. It gives designers a quick
start to develop code on the AVR combined with features for using
the starter kit to develop prototypes and test new designs. The
STK500 interfaces with AVR Studio for code writing and debugging.
JTAGICE
The JTAGICE is an In-Circuit Emulator for Atmel’s megaAVR and LCD
AVR devices with 16K or more program memory. The JTAGICE com-
municates to the On-Chip debug module on the AVR which provides
the most accurate emulation possible. The Emulator assists devel-
opers in identifying software bugs significantly reducing the devel-
opment time. The JTAGICE interfaces with AVR Studio for code
development and debugging.
JTAGICE
www.atmel.com
page 37
A T M E L A P P L I C A T I O N S J O U R N A L
86RF401E/U-EK1
STK94
The STK94 is a low-cost development kit for the designer who wish-
es to begin working with the FPGA AVR devices. A comprehensive
tutorial takes designers through the complete FPGA AVR develop-
ment process. The starter kit, which runs on PC Windows-based plat-
forms, has everything needed to get started, including all software,
boards, parts, cable, and documentation. ❑
43DK355
ATV1-90SC
43DK355 ATV1-90SC
The 43DK355 development kit has everything you need to devel- The ATV1 provides a flexible emulation platform to support current
op your full-featured USB application using AT43USB355. It comes and future Secure AVR devices. For maximum flexibility, the system
complete as a working hub with a programmable embedded USB has been designed to be upgraded easily. Switching to support
function and up to four USB downstream ports. USB source code
for an embedded function and a USB library for the HUB are pro-
other devices within a given core family is done simply by running
a software utility that guides the user through the device update
Next Issue:
vided, thus relieving the user from the tedious task of developing Third-Party AVR Emulators,
process - there is no need to change PCBs or jumper settings.
such code on their own.
Programmers, Consultants,
and More!
www.atmel.com
page 38
A T M E L A P P L I C A T I O N S J O U R N A L
Variable Message Sign Development with AVR and ImageCraft continued from page 19
10 bytes of 0x0AA (b10101010). This allows the receiving radio address 0 selected it entered a test mode and just cycled through A-Z and 0-9
to synchronize with the incoming signal and stopped the first few without the need for a controller. This made basic testing of the expansion
bytes in the radio packet sometimes being lost. Another problem boards and characters very simple. It was decided that the character bit pat-
was noise on the output of the radio. Random radio output, for terns required for the LEDs would be stored as bitmaps within the expansion
example, from the local taxi firm, could under some circumstances boards’ 8535 flash memory. This would allow for custom characters or differ-
look like the start of a radio packet. This caused the radio receiv- ent languages to be stored, or even for creating a bigger image from a num-
ing software function to get confused; it would see the start of a ber of characters working together in panels. Unfortunately this meant the rel-
packet, shove the received data into a buffer, and then expect the atively small 8 K bytes of flash in the 8535 was being pushed to the limit.
remainder of the packet to arrive, which of course it never did. Again ICCAVR came to the rescue, with yet another feature that had not been
When a valid radio packet arrived the buffer was already half full needed so far, the ICCAVR code compressor. This allowed around a 7-9% reduc-
of junk so the software went haywire. Although it was not so easy tion in code space, which prevented the need for a bigger and more expensive
to track down this problem, it was fairly easy to fix. Since we know how long AVR device.
our maximum packet length is, and from the baud rate we could calculate how
long the maximum packet should take to arrive from start to finish. By adding The initial development for the expansion board was all done on the STK500,
a simple timer that was started when the radio preamble and sync bytes were and indeed, if there had been two STK500s available, a lot more system
detected, we could delete the erroneous data from the buffer if the data did development could have been done. At this point it was decided to make some
not arrive within the allotted time period. prototype PCBs, starting with the controller card. The first board was built;
given some power (on a current limited PSU!!), and plugged into the ISP lead.
Other functionality was added to the user diagnostic interface that We pressed the ISP button on ICCAVR, and then just happily watched the pro-
allowed testing of various radio functions, which made develop- gramming progress bar work its way across the screen, to the customers’
ment easier and has proven to be very helpful in fieldwork. amusement. The PCBs work perfectly the first time! Perhaps the gremlins had
taken a vacation elsewhere.
Sometimes Extensions Are Useful
So now we had our user terminal driven configuration interface, Even 8-Bit Embedded Systems
which was starting to have quite large, but well structured menu Can Speak TCP/IP and HTML
pages. Initially the standard C function, printf, was used to output The final and possibly the most complex part of the project was implementing
the menu text. To preserve the semantics of the C language, a TCP/IP interface serving up embedded HTML pages giving the status and
ICCAVR by default allocates quoted literal strings (e.g. “HIGHWAY control of remote devices. The embedded web server is a separate box resid-
CLOSED”) in the RAM space. With the large amount of strings in ing in the control room attached to the customer’s local network. Given its own
the menu system, the 4K bytes of RAM in the Mega128 were rap- IP and MAC address, it receives data over a TCP interface converts the data into
idly being used up. Fortunately, the Mega128 has a lot of flash the radio packet and sends the relevant packet data over the radio network to
(128K bytes). ICCAVR allows literal strings to be placed in the flash the receiving node. The HTML interface allows anyone with correct passwords
as an option. This means that some of the standard C functions will no longer to view the status of remote outstations, and reconfigure certain parameters.
operate on literal strings. This is a side effect of the Atmel AVR using a Harvard
architecture: code and data are in separate address spaces (in flash and RAM The TCP interface was implemented using a Mega128 with an external 32K
respectively). While this allows the CPU core to run faster, it makes some com- RAM chip and a RTL8019AS Ethernet driver. The TCP stack is a trimmed down
mon C usage slightly less convenient. Again ICCAVR came to the rescue by pro- implementation, but supports ARP, ICMP, UDP and TCP communications. It also
viding variants of the standard C functions that are compatible with flash based has a dynamic HTML interface on the application layer. The dynamic aspect of
literal strings. For example, cprintf is used in place of the printf function. Again, the interface is that each web page is generated on the fly when requested,
we see that it is important to have the right extensions to C without polluting rather than being a static page retrieved from the Flash of some external EEP-
the source code unduly. Our radio communications were now operating quite ROM. This allows for up-to-date system information to be displayed, such as
happily and reliably with our user interface, and so far we were still using the temperature, radio / GSM signal strength, number of radio / GSM packets
STK500 and only 18% of the Mega128 memory. processed, TCP status for received, sent and lost / corrupt packets, etc.
Down the Home Stretch Even though a limited TCP stack was implemented, it was still possible to
achieve, the TCP sliding window, detection of lost packets, and automatic
Next was the expansion board that would interface between the characters and
retries, with adaptive timeouts to cater for different roundtrip delays across dif-
main controller. This used the 8535, and again the ICCAVR
ferent faster or slower networks. The HTML pages as generated by the AVR sup-
Applications Builder was used to generate all the code required for
port buttons, tick boxes and radio buttons, and text fields where user infor-
setting up the peripherals.
mation can be entered. It also supports GIF, animated GIF and JPEG images,
A simple SPI bus interface was used for communication between and colour bar graphs. The complete TCP interface with a large quantity of
the controller and expansion boards with one slight change: the HTML web pages including graphics still only takes less than 45% of the
drive from the expansion board to the controller needed to be tri- Mega128 memory.
state, as there would be more than one expansion board on the SPI
bus. This was simply achieved by the use of an open collector tran- Conclusion
sistor and some simple buffer circuits at the controller end. Each All in all, from the start of nothing more than a rough drawing to equipment
board needed to be addressable so a simple thumb-operated rotary being signed off and in use on the UK highways, the whole project was com-
HEX switch was added which gave 16 address ranges. It was decid- pleted in 6 months. This would not have been possible without quality devel-
ed that 0 would never be a valid address, so a handy little test func- opment tools at reasonable prices like the STK500 / 501 and ImageCraft’s
tion was added where if the expansion board was powered up with ICCAVR C compiler with ImageCraft’s fantastic after-sales support. ❑
www.atmel.com
page 39
A T M E L A P P L I C A T I O N S J O U R N A L
Device Drivers and the Special Function Register Hell continued from page 18
6. If you want to view the files generated for USART, you can find the • I/O - I/O ports
USART module in the project explorer. Here you can open the • TMR - Timers, counters
<ma_usart.c> or <ma_usart.h> files, and see the device driver source • SPI - Serial peripheral interface
code. • USART - Universal synchronous/asynchronous serial communication
7. To generate source code and header files to disk, click the code • TWI - Two-wire serial interface
generation button in the toolbar. • ACOMP - Analog comparator
8. Add the generated MakeApp files to your application project, and, with • ADC - Analog to digital converter
out having to read or understand the special function register
implementation for the USART, you are now ready to use the USART in General IAR MakeApp features:
your product. Let your application call the MA_InitCh0_USART() func- • CAD-like drawing editor - As devices are configured, their pin usage is
tion. Once the USART is initialized, the MA_PutStringCh0_USART() displayed graphically.
function will be ready to output your “Hello world” message. • Project explorer – Gives a tree view of the current project.
• Component library – Contains the necessary information about the
Product development and product life cycle components that can be configured.
• Property dialogues – Organized as a set of tabs with headings and
IAR MakeApp can be used at all stages in a product, from the first idea, eval-
property lists.
uation, and design, to the final test and maintenance of the product. It also
• Code generation engine – Contains a powerful code generation technology.
becomes easy to tune system parameters throughout the entire life cycle of
It automatically calculates the special function register values, and
your key products. So not only do you get to market sooner, but, once there,
modifies/optimizes the generated source code according to the property
you can easily and cost-effectively refine and improve your product offering. It
settings.
is never too late to start using IAR MakeApp.
• Component browser - Gives extensive information on chip-internals, such as
IAR MakeApp for Atmel megaAVR SFR bits, port pins, interrupts, memory maps, etc.
The current product supports: ATmega128(L), ATmega64(L), ATmega32(L), • Data book browser – Lists all known hardware manuals in PDF format in the
ATmega16(L), and ATmega8(L). databook catalog.
• Report generation and report viewer – The project report contains detailed
The property dialog boxes support the configuration of: information on chip resources (such as SFRs, pins, and interrupts), as well
• CPU - Bus control and memory as the project settings (such as configuration, generated device driver
• INTC - Interrupt controller functions, and function dependencies).
• WDT - Watchdog timer • Low product price! ❑
Figure A
www.atmel.com
page 40
IAR-IQ#3-AD 6/30/03 4:17 PM Page 1
Make the
most of Atmel
AVR power
with IAR
tools
Visit us at www.iar.com
Don’t worry about your upgrade path!
IAR development tools also support
the Atmel ARM 32-bit processor
From Idea to Target
LIT#3362A-CORP-VOL.1-20M