Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Atmel applications journal.Spring 2004

.pdf
Скачиваний:
96
Добавлен:
23.08.2013
Размер:
2.82 Mб
Скачать

A T M E L A P P L I C A T I O N S J O U R N A L

mizing the measurement rate performance of the network and eliminating the need for and, cost of incorporating A/D and data packetization capabilities at each device. The AVR’s internal comparator is used to convert high-low current measurements into bit levels for digital signaling and communication faultdetection.

The AVR’s run-time remote self-programming feature is used to provide field software updates. With its secure boot sector, password access control is implemented, guarding against unauthorized access to the control system.

The controllers also provide slave port access via the AVR’s SPI interface, so external access is available for full diagnostics and boot sector reprogramming.

The FGI controller uses the AVR’s internal 128K FLASH for program space. An external 128K SRAM fills out 32K of fixed SRAM in the lower half of the AVR’s data address space, with an additional 100K SRAM accessible via paging in the upper half. An Atmel small-sector FLASH provides 1MB of device configuration data space, also via paging.

A smaller FGI controller design operates with the ATmega128’s self-contained memory only, minimizing the implementation cost for small dedicated applications.

One of the AVR’s dual serial ports provides host access via RS-232, RS-485, FGI slave, and SPI programming access, with the other dedicated to FGI network device communications.

FGI devices also use the AVR’s EEPROM space to store additional device specific information, such as manufacturing lot, calibration, and device configuration parameters.

Example System Configurations and Applications

The FGI Temperature and Humidity Monitoring System provides periodic monitoring of temperature, humidity, external 4-20 ma sensor measurements, and external switch states.

FGI Systems

The AVR’s internal 4K EEPROM is used for controller configuration parameters, and storing manufacturing and test history.

At 3.3V the AVR provides processing power well suited to current needs. However, having room to grow is appreciated, with a 5V AVR option available to double the controller’s horsepower while maintaining software compatibility.

Future support for direct Ethernet TCP/IP support is planned, based on the AVR’s TCP/IP development kit available from Atmel. PC-104 and modem options are also planned.

AVR Based Network Devices:

The AVR family is ideal for implementing microprocessor based FGI network devices. The wide range and variety of AVR sizes and features available allow for tailoring the features, size, power consumption, and cost to the needs of a widest possible range of devices, while retaining software language compatibility across the controller and all the devices.

Minimum size, cost, and complexity microprocessor based devices can be implemented using the tiny AVR devices. An 8-pin micro with internal RC oscillator and no external micro support components can be used for implementing a master-slave micro device, communicating with the controller via bit-banging or the SPI interface. Mid-sized and larger AVR devices can be used to implement FGI devices with full peer-to-peer communication capabilities.

The AVR’s SPI programmability via the FGI network provides capabilities for system-wide remote updates, build-in-test, manufacturing help, and fail-safe operation.

The FGI network’s philosophy of implementing minimum power devices is supported by the AVR’s power-saving idle and sleep modes. A master-slave micro device can spend most of it’s time powered down, waking only when accessed by the controller and as needed to satisfy other device-specific needs.

The FGI 4-20 ma Sensor Networking System provides a convenient means for interconnecting 4-20 ma sensors, rather than using home-run connections for each sensor. Single and multiple input devices can be provided, and control output devices can be supported on the same network.

An upcoming FGI Modular Custom Control Panel System provides a modular approach to implementing displays and control panels of varying complexity. LED driver devices can be combined with a variety of display options. Switch, keypad, and rotary encoder input devices provide for user interaction.

We are also using this technology to design an automated test system for functional testing of manufactured electronics products.

Example end-user applications include manufacturing control systems, laboratory process monitoring and control systems, refrigerator/freezer monitoring systems, and building automation systems.

Future Vision

FSD is presently giving priority to supporting industrial and commercial measurement and control system applications. In support of longer term goals, FSD is also developing application level software for using the FGI networking technology for home and commercial building automation. The FGI networking technology can provide substantially more features and functionality at lower installed cost than competing technologies, and the volume potential of these markets can drive implementation costs way down, also benefiting our industrial automation and commercial users.

To reach these larger markets, we would like to eventually partner with and/or license our technologies to semiconductor and 3rd party device suppliers, and promote the FGI networking technology as a standard OEM product device networking approach.

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

8-bit Microcontroller Drives

Battery-Powered Thermostat

By Jim Panfil

 

 

 

 

 

Microcontrollers provide many benefits to our lives, including the ability to

This AVR-based microcontroller also includes a 10-bit analog-to-digital convert-

make many of the products we use more energy efficient. Central heating and

er with differential channels, an internal analog reference, 16kbytes flash

air conditioning units is one area where microcontrollers are used to make

memory, 512 bytes EEPROM, 1kbyte SRAM, plus other features as shown in

motors run more efficiently or to provide higher quality regulation and more

Figure 1. This high level of integration allows the system footprint to fit with-

enhanced user interfaces on thermostats. When building a microcontroller-

in a 2.5 X 6 cm space, the desired size of the LCD display and hit the $5 mark

based thermostat, some of the important goals include small size, low power,

for the total system cost.

low cost, high reliability, and easy manufacturability. One of the ways to reach

Writing Power-Aware Applications

these goals is to use a highly-integrated microcontroller that supports features

directly applicable to building a thermostat.

When optimizing a design for battery-powered applications or other applica-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

tions where minimum power consumption

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

is an important goal, there are many fac-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

tors to consider. Since power increases

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

with Vcc (I = V2f; where I is current and f

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

is frequency), you can reduce power con-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

sumption without limiting the maximum

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

operating frequency by minimizing the

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

voltage of the device. For example, run-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

ning at 4.5V instead of 5.0V for a 16MHz

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

device, drops power by almost 20% with-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

out compromising the device’s perform-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

ance.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

As evidenced by the power equation,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

reducing clock frequency also plays an

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

important role in power savings. If you

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

can optimize your code to run at 10MHz

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

instead of 16MHz, current consumption is

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

reduced by 30%-40%. Furthermore, if you

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

manage to get down to 8MHz, you can

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

change to a low voltage device and reduce

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Vcc to 3V – the resulting power consump-

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 1. The high integration level of the Mega 169 simplifies system design, helps to lower power consumption, and signif-

tion will be 75% lower than what you

icantly reduces board space.

started with at 16MHz!

Many microcontroller solutions may have some of the right features integrated, but will typically rely on discrete components such as analog-to-digital converters, LCD driver, power management circuitry, temperature sensor, and crystal oscillator. The resulting thermostat will end up with a bill of materials cost greater than $8.00. Furthermore, with discrete components it is more difficult to control system power and thermostat battery life is typically limited to five years or less.

Atmel’s AVR-based Mega 169 is the first member of a low power family designed for metering and other battery-powered applications requiring an integrated LCD controller. One of the features included in the Mega 169 is a 100segment LCD controller with Automatic Contrast Control. In applications where the power supply voltage can vary, such as in battery-powered systems, maintaining a constant contrast on the LCD display is desirable. Factors such as the type of bias and voltage levels can affect LCD contrast. Automatic Contrast Control requires the matching of different voltage and temperature combinations and then automatically generates the correct voltage ranging from 2.6- 3.35V without the need for external circuitry.

For extremely low power applications, such as the thermostat where two AA batteries have to last 10 years, very low frequencies between 32kHz and 1MHz are often used. Many maintenance tasks, such as the sampling of a temperature sensor, can be accomplished at these low frequency levels. Alternatively, these same tasks can be handled at higher frequency levels, taking advantage of AVR sleep modes during idle cycles. In other words, it would be appropriate to run the AVR at high speed for a short period of time and then put it back in the very low power consumption sleep mode for the bulk of the time. This may yield an average power consumption that is much lower than the low frequency operation in active mode would give. The optimum frequency and duty cycle must be determined for each part of your application.

Hardware Considerations for Low Power Applications

Beyond writing more optimized application code, a brute force method of conserving battery life is to completely turn off the microcontroller. However, the disadvantages of using this method outweigh the benefits. For example, now the system must include some sort of external interrupt mechanism to reactivate the power supply that drives the microcontroller.

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

Another disadvantage when the power is first turned on, the supply voltage will

integrated into the Mega 169, making up the majority of the thermostat’s

not rise to Vcc immediately (Figure 2). The amount of time required to reach

electronic system, can be individually powered down when not in use. In the

Vcc will depend on factors such as the charging of the decoupling capacitors.

power down mode, all peripherals, with the exception of external interrupts,

As long as Vcc is below the minimum operating voltage, the AVR must be held

are turned off. This will drop power consumption to 500 NanoAmps. This capa-

in reset to avoid incorrect code execution. This reset delay can be set up as

bility is much more difficult when dealing with discrete components.

either a fixed startup delay or the BOD can be used to measure when Vcc is

 

 

 

 

high enough.

 

 

 

 

 

When the AVR microcontroller is coming out of power-down mode (or after a

 

 

 

 

 

 

 

 

hardware reset), the oscillator needs a startup time. This startup time depends

For most circumstances, the AVR’s programmable sleep mode avoids the need

on the type of oscillator used. If the Mega 169’s active period is relatively

to remove the microcontroller’s input voltage. Furthermore, the peripherals

short, an oscillator with short startup time will help to save a lot of power. The

 

 

 

 

 

 

 

 

 

 

 

tradeoff is a slightly less accurate oscillator, however, this is also

 

VCC rise time

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

balanced with a lower cost. For example, if the accuracy of a

VCC

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

crystal is not required, an inexpensive RC oscillator or a ceram-

VCCmin

 

 

 

 

 

 

 

 

 

 

ic resonator will give shorter startup times. Regardless of your

 

 

 

 

 

 

 

 

 

 

preference for oscillators, the reset delay, oscillator type, and

ICC

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

oscillator startup time, is selected by fuse settings on the AVR.

 

 

 

 

 

 

 

 

 

 

 

0

 

 

 

 

 

 

 

 

 

 

The performance of the Mega 169, along with its variety of

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Time

peripherals allows designers to build one thermostat to serve

V

 

 

 

 

 

 

 

 

 

 

Wakeup

 

 

 

 

multiple markets. The microcontroller’s in-system Flash program

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

memory enables simplified inventory management, just -in-

 

 

 

 

 

 

 

 

 

 

 

time delivery, and the ability to program different codes at the

Figure 2. You must hold the microcontroller in reset mode until Vcc has ramped past the minimum

end of the line.

operating voltage.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The Best User’s Forum for AVR Freaks!

www.avrfreaks.com

www.atmel.com

page 11

Photo 1—The board is clean and simple. All of the supporting capacitors and resistors are SMT parts mounted on the opposite side of the board.

A T M E L A P P L I C A T I O N S J O U R N A L

It’sI ’s about timei you had full control of your hard drivei .. The controller you’vebeen waitingi i for isis justj one projectj

away.. Thisis month,, Fred shows you how easy itit isis to buildi an ATA hard drivei con-- troller.. Amazingly,i , all you need isis a good microi and a few everyday parts..

Fred Eady has more than 20 years of experience as a systems engineer. He has worked with computers and communication systems large and small, simple and complex. His forte is embeddedsystems design and communications. Fred may be reached at fred@edtp.com.

Construct an ATA

Hard Drive Controller

By Fred Eady, EDTP Electronics

Do you remember your first computer with a hard drive? What about when 5 MB was a lot of hard drive space? Have you ever wanted to put something of your own on a hard drive without having to rely on somebody else’s expensive and proprietary hardware and driver code? Ever want to read, write, and control a hard drive with a microcontroller?

If you answered “yes” to any one of these questions, then this project is for you. I’ll show you how to build an ATA hard drive controller with a microcontroller and a few common parts. In addition, you’ll learn how to write simple code that will form the basis for deploying a stand-alone,

networkable, microcontroller-based data storage system.

Even if you aren’t interested in communicating with hard drives, there’s something here for those of you who don’t need a microcontroller-driven hard drive controller. The bonus track is in the hardware. Do you need an in-system pro- gramming-capable test stand for an Atmel ATmega128 with RS-232, Ethernet, and 64-KB of external 16-bit memory? Well, this project is for you too. Hard drives or no hard drives, let’s get started.

THE HARDWARE

Hanging a standard PC or laptop hard drive from the 40-pin connector shown

in Photo 1 is the reason why we’re gathered here today. I wanted the ATA hard drive controller’s electronics to be flexible. So, in addition to the standard RS-232 port, which is driven by a Sipex SP233ECT, I added 10-Mbps Ethernet capabilities with the RTL8019AS/ LF1S022 combination.

The ATmega128 has plenty of internal SRAM (4 KB), but I thought adding 64 KB of 16-bit external SRAM would be nice. Adding the SRAM is sort of like buying rope: you can always make the rope shorter, but it’s a pain to add rope later if you need it.

The ATmega128 has enough I/O structure to service the big SRAM with some help from a couple of 74HCT573 latches. As you can see in Figure 1, the external SRAM is attached to the ATmega128 in the standard manner. This allows those of you who aren’t interested in placing bits on a spinning piece of magnetically coated aluminum to do your thing with the big chunk of SRAM and the raw power of the ATmega128. With the SRAM in this configuration, the results of the hard drive I/O operations can be buffered by the external SRAM or operated on by the AVR directly.

The Ethernet interface, shown in Figure 2 (next page), is actually a wire-by- wire copy of the Packet Whacker microcontroller NIC. The original Packet

Figure 1—The AT90S8515 microcontroller is the basis for the GPS-GSM Mobile Navigator.

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

Listing 1—See Code Patch page 45

Whacker firmware that was written for the ATmega series of AVRs is used in the ATA hard drive controller code, as well. The Packet Whacker code already has hooks to allow for the easy transmission and reception of the hard drive data.

The RS-232 port has a dual purpose. Running at 57.6 kbps, it’s fast enough to spit out a sector’s worth of ASCII data to a terminal emulator for debugging. In addition, it can be used efficiently in an application to transfer data and commands between the AVR-based hard drive controller and a peripheral device.

Listing 2—See Code Patch page 45

pins on the AVR and power isn’t transferred within the programming cable, I was able to keep the dongle attached to the hard drive controller throughout the programming and debugging process.

The ATmega128 is clocked at 14.746 MHz to keep the data rate error percentage at a minimum for the 57.6-kbps serial port. For this project, the ATmega128 I used was a 5-V part that can run at 16 MHz. The 14.746 MHz is the closest standard crystal to the maximum clock speed that will clock the big AVR with the least amount of serial data bit error rate.

The first spin of the ATA hard drive controller used a 2-mm header that mated directly to the 44 I/O pins found on 2.5laptop drives. My experiences with the 2-mm parts were not good ones. The pins and connectors are fragile, and I really don’t like working with the 1-mm ribbon cable.

Reprinted with permission of Circuit Cellar®

Issue 150 January 2003

Figure 2—If this looks familiar, it’s because it’s actually a Packet Whacker that’s been melded into the ATA controller design. The Packet Whacker code was reused, as well; it can be found wound into the ATA controller source.

The 10-pin header makes assembling a serial cable easy, if you use 9- or 25pin IDC shell connector parts and ribbon cable.

I’ve standardized with 10-pin male headers for all of the external ports with the obvious exceptions of the Ethernet and hard drive I/O ports. As long as you put the right connector in the correct header socket, using the 10-pin headers with the keyed shrouds eliminates the possibility of inserting the ISP and serial connectors incorrectly.

The 10-pin arrangement is also standard for most of the ISP dongles that support the AVR series of ISP-capable microcontrollers. I used a Kanda AVR ISP dongle and a version of the company’s ISP software to program the hard drive controller’s ATmega128. Because the dongle interface is dedicated to certain

In the process of attempting to work at 2 mm, I purchased a gaggle of new surplus 2.5Hitachi 540-MB drives. That purchase, as it turns out, was a good thing. After junking the 2-mm idea, I purchased some surplus 850-MB, 3.5drives that turned out to be mostly junk. I never really had any inclination to put real data on them, so it’s not a total loss. At less than $10 per drive, what did I expect? When I bought the laptop drives, I also purchased some 2-mm to 0.1(or 2.5to 3.5) converter boards. The idea was to be able to attach the laptop drives to a PC for the debugging and verification of the ATA drive controller’s firmware and hardware.

The moral of the 2-mm hard drive story is that, thanks to my foresight, you’ll see how I brought the ATA hard drive controller to life with the 2.5Hitachi drives and converter boards. This may sound funny, but when I was formatting

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

the 3.5850-MB drives, I was hoping that a few of them would show some errors. I wanted to verify that the hard drive controller could detect them, and then show you what they looked like. I really didn’t expect them to be trashed so badly. So, the drive error examples will come from the 3.5drives, and the good data examples will feature the smaller Hitachi drives.

The ATA hard drive controller requires a single 5-VDC power source. Also, the Hitachi drives require only 5 VDC. However, the larger 3.5drives need 12 VDC in addition to the 5 VDC. The original spin of the hard drive controller used a 2-mm, 44-pin hard drive I/O attachment point. The extra four pins on the 2-mm connector provided 5 VDC and ground for the 2.5drives right at the hard drive I/O connector. In this spin, the 44-pin, 2-mm pin set is replaced with the standard 40-pin 0.1pin set, and there isn’t a power supply outlet at the hard drive I/O connector.

The hard drive controller is equipped with a standard 4-pin floppy drive power plug. As you might have figured out, the inclusion of a standard PC power connector on the hard drive controller allows you to power the 3.5drive and the hard drive controller’s electronics from a common OTS PC power supply.

If the 2.5drives are used, you’ll have to provide an attachment to supply power to the extra I/O-based power pins on the drive. That’s where the 2.5to 3.5drive I/O adapters come in. The adapters I purchased have a 3.5drive power connector that has only the 5-VDC lines tapped into the 44-pin, 2-mm drive connector. The drive converter board allows you to use smaller 2.5drives with the standard 40-pin 0.1cables and a PC power supply.

Although using a commodity power supply is the easiest way to go, any other suitable power supply method will work just as well. Photo 2 is a shot of an Hitachi 2.5drive and its associated converter board attached to the ATA hard drive controller.

THE FIRMWARE

I wanted the ATA hard drive controller to be capable of interfacing to any standard ATA device. With that design requirement in mind, I wrote the hard drive controller’s AVR firmware with ImageCraft’s ICCAVR C compiler and guidance from the ATA-3 specification. What I ended up with was a basic set of routines that allows you to exercise the standard ATA command set, query the hard drive register set, and exchange data with the attached ATA hard drive.

As soon as I had access to the hard drive’s register set and data, I set out to write code to move the data that was harvested from the hard drive to the outside world. The first logical choice of data transport was a serial port. After thinking it over, I decided that an Ethernet interface would be an excellent way to move data in and out of the hard drive controller. The Ethernet port would allow the hard drive controller to be networked and provide a high-speed data connection for transfer rates beyond the capabilities of a serial port. In either case (serial or Ethernet), you could use any of the Visual (e.g., Visual Basic, Visual C) or Borland compilers to build an embedded or PC interface to the ATA hard drive controller.

The first order of business as I started to develop the AVR firmware was to define all of the functions that would run against the hard drive. With respect to the software, a hard drive looks like an 8- or 16-bit I/O port that leads to an internal register set. Register I/O is normally achieved in 8-bit mode, while data transfers are typically performed in 16-bit operations.

If you review Figure 1, you’ll see that a 16-bit data bus is pinned out on the 40-pin hard drive I/O connector. The data bus signals are supported by a set of I/O read and write signals. Access to the internal hard drive register set is accomplished using the I/O read/write signals and data bus signals in conjunction with the address and select signals found on the 40-pin hard drive I/O connector. The control block is the core set of hard drive internal registers.

Photo 2—The 540-MB drive formats quickly and is easy to handle even with the converter boards attached. This made for quick turnarounds in the initial development stages when I was experimenting, debugging, and doing hard drive formatting.

PROJECT FILES

To download the code, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2003/150/.

Word F/V

Identify device information

 

Word

F/V

Identify device information

 

 

 

 

 

 

 

 

 

0

General configuration of bit-significant information:

 

1

F

Number of logical cylinders

 

F

15

0 = ATA device 1 = ATAPI device

 

2

R

Reserved

 

 

 

F

14

Obsolete

 

3

F

Number of logical heads

 

F

13

Obsolete

 

4

X

Obsolete

 

 

 

F

12

Obsolete

 

5

X

Obsolete

 

 

 

F

11

Obsolete

 

6

F

Number of logical sectors per logical track

 

F

10

Obsolete

 

7–9

X

Vendor specific

 

F

9

Obsolete

 

10–19

F

Serial number (20 ASCII characters)

 

F

8

Obsolete

 

20

X

Obsolete

 

 

 

F

7

1 = Removable media device

 

21

X

Obsolete

 

 

 

F

6

1 = Not removable controller and/or device

 

22

F

Number of vendor-specific bytes available on read/write long commands

 

F

5

Obsolete

 

23–26

F

Firmware revision (eight ASCII characters)

 

F

4

Obsolete

 

27–46

F

Model number (40 ASCII characters)

 

F

3

Obsolete

 

47

X

15–8

Vendor specific

 

F

2

Obsolete

 

 

R

7–0

00h = Reserved

 

F

1

Obsolete

 

 

F

 

01h–FFh = Maximum number of sectors that can be transferred

 

F

0

Reserved

 

 

 

 

per interrupt on read/write multiple commands

 

 

 

 

 

48

R

Reserved

 

 

 

 

 

 

 

 

 

 

 

 

Table 1—If you like to write code that parses data, then writing ATA hard drive code will keep you happy (and busy) for days. The data in Photo 3 was culled from this table of words spoken by the little Hitachi DK211A-54. F represents a fixed value, V represents a variable value, X represents a vendor-specific value, and R represents a reserved value.

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

Listing 1 is my definition of how the control block registers are addressed.

Listing 1—See Code Patch page 45

If you take a close look at the control block register definitions in Listing 1, you’ll notice that the basic components (in register form) of addressing data on a hard drive are represented. Cylinder head sector (CHS) addressing is implied in the control block register names; however, in the ATA hard drive controller firmware, I’ll use these same CHS-based registers to perform logical block address (LBA) mode addressing operations. LBA mode is a means set forth by the ATA standards to allow for the linear addressing of sectors. LBA addressing is derived from the CHS addressing format as follows:

LBA = ((cylinder ˘ heads_per_cylinder + heads) ˘ sectors_per_track) + sector – 1

For instance, cylinder 0, head 0, sector 1 is LBA address 0. Therefore, for LBA mode to function, the hard drive must support LBA mode internally, and that’s the case for the 540-MB laptop drives as well as the larger 850-MB 3.5drives.

The ultimate goal is to use LBA mode to read and write to sectors on the hard drive. To do this, you must first be able to read and write to the hard drive’s register set. A good place to start with the firmware description of this process is with the hard drive initialization routine, whose source code is included in Listing 2 (see the Code Patch page 45).

The first register access occurs when the while(!ready & busy) statement executes. Note that ready and busy are macros that call the ata_rdy(void) and ata_busy(void) functions. The ata_rdy(void) and ata_busy(void) functions are identical with the exception of the status bit they check. In both cases the AVR data bus pins are put in Input mode, the status register is addressed, the I/O read pin is toggled, and the status register data is read (8 bits). Additionally, the hard drive I/O port is put into a high-impedance state, the status condition is determined, and a return code is generated. Note that the external buffer SRAM is not used by these functions.

accurately. The easiest way to verify this was to execute an ATA Identify Device command.

Basically, the Identify Device command instructs the hard drive to divulge its factory-loaded identifiers, and 255 words are returned. All I had to do was pick up the words from the hard drive I/O port, parse them, and send the results to the serial port. All 255 words weren’t needed. As you can see in Table 1, the first 46 words tell you if things are working correctly. Photo 3 is a HyperTerminal shot showing you what the little Hitachi drive had to say about itself.

Now that you know how to get data from the hard drive, I’ll show you how to read a sector. Before the code is tested, however, there’s work to be done on the hard drive, and you’ll need a way to verify your results.

Because I plan to develop AVR firmware to manipulate FAT32 formatted drives, it would be logical to format the hard drives that will be used with MSDOS by way of Windows 98. Formatting in this way puts master boot records, partition tables, and data in predictable places on the drive. Two drives should be formatted: one is used on the ATA hard drive controller, and the other is used on a PC for verification and as an aid in debugging.

The verification program for the PC is called WinHex. Normally, WinHex is used to inspect and repair files on PC hard drives. This program does it all as far as hard drives are concerned; it understands FAT12, FAT16, FAT32, NTFS, and CDFS. In addition, WinHex includes a disk editor that allows you to become a dangerous hard drive technician. You can also use WinHex to create templates that automatically parse known data areas of the hard drive.

Photo 4 is a screen shot of an actual WinHex panel that’s aimed at the 2.5Hitachi drive attached to the PC. I’ve dialed in the MBR master boot record (MBR), which resides at cylinder 0, head 0, and sector 1 or LBA 0. If all goes well with the sector read on the hard drive controller, the data in the HyperTerminal window should be identical to the bytes found in the WinHex window. The HyperTerminal readout in Photo 5 matches the numbers picked up by WinHex from the clone drive in Photo 4. As Spock would say, “Random chance seems to have operated in our favor.” The ata_read_sector() function shown in Listing 3 works as designed. Reading a sector in LBA mode entails loading the Device/Head register with the LBA mode bit set, loading the cylinder High/Low and Sector registers, and issuing the Read Sectors command.

Photo 3—Things are good when the numbers in this photo match the numbers written on the hard drive.

After the hard drive has done its own power-on reset, the ready bit will show that the hard drive is ready for a command, and the busy bit will indicate a “not busy” status. At this point, a hard reset is toggled using the RESET pin on the hard drive I/O bus, and time is marked to allow the physical and electrical hard drive reset process to finish. Because I was attaching a single hard drive that’s strapped as master drive 0, I selected drive 0 in LBA mode using the select_drive_0 macro. The next step was to issue a recalibrate command and check the error status register. In instances like this, a “drive ready” banner is sent to the serial port if all is well.

At that point, I wasn’t ready to start reading hard drive sectors, because I needed to make sure I could address and command the hard drive interface

Photo 4—There isn’t much about a hard drive you will want to know that WinHex won’t tell you.

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

Photo 5—The format of the data may not be pretty, but the data itself is beautiful because it matches the clone drive’s MBR data read by WinHex.

Here’s where that big chunk of external 16-bit SRAM is handy. Instead of pulling the data directly into the AVR, I used the AVR to generate address information for the SRAM and manipulate the SRAM’s write enable and chip select lines to store the incoming data in the external 64 KB of SRAM.

I divided the SRAM into logical pages of 256 words each and wrote routines to read and write these pages. Each page of external SRAM holds one sector of hard drive data, allowing up to 256 sectors to be buffered. That pretty much takes care of verifying the ATA hard drive controller’s read functionality.

Writing to the hard drive is a similar process. The external SRAM is filled with a sector’s worth of data (256 words), and then that particular SRAM page is written to the hard drive I/O port’s data bus. Instead of performing an ATA I/O read, an ATA I/O write is performed when the data is presented on the external SRAM data pins. I tested the write sector code successfully on random sectors of the hard drive attached to the ATA hard drive controller. Additionally, I verified the writes by moving the hard drive to the PC and reading the sectors I wrote using WinHex.

Listing 3—See Code Patch page 46

GETTING FAT

All of the reading and writing up to this point was completed with simple C routines that were teamed together to perform a much larger and more complex task. Believe it or not, designing the ATA hard drive controller hardware and finishing the C coding for the controller I/O functions was the easy part. The

Ethernet code was just as easy, because I copied AVR code that was already written for the Packet Whacker microcontroller NIC. The next step in the process of assembling a microcontroller-based networkable mass storage system was a bit more demanding.

I completed a tremendous amount of research in preparation for writing AVR code to implement Microsoft’s FAT32 file system. Thanks to a series of Circuit Cellar articles written by our own Jeff Bachiochi (Circuit Cellar 143–146), I had a good idea about the roads I will travel and battles I will fight.

The journey starts with the bytes in Photo 4, the master boot record. Because I’m not executing instructions on a legacy x86 machine and using a PC BIOS or MSDOS, I’ll have to interpret the data and adapt it to the AVR. For instance, there’s executable code in the MBR that I don’t care about. The problem is that I have to navigate through it to find markers that either give me information about where FAT-related constants and parameters reside or point me to places where I can read and write my data.

In the case of the MBR, I’m interested only in the last 66 bytes, because that’s where the partition table resides. The fun starts at offset 0x1BE in the MBR, which is the first partition entry. Because the drives I formatted were secondary drives, the FDISK program couldn’t make their partitions active. So, the first byte at offset 0x1BE was 0x00 (inactive) on my drives.

Other interesting information resides at offset 0x1C6 in the MBR. This is the number of sectors between the MBR and the first sector of the first partition. As you can see in Photo 4, WinHex shows that number as 0x3F. I used the WinHex program to dial in 0x3F sectors beyond the MBR and, lo and behold, there was the FAT32 boot sector with additional fields of information to parse. The plan is to collect documentation and use WinHex to obtain the actual visuals concerning how data and control areas on a FAT32 hard disk are defined and laid out.

So, you see that I have my work cut out for me. The good news is that you’ll be able to share the fruits of my labor, because I will make the ATA hard drive controller hardware available to those of you who want one. The code discussed in this article is available for you to download from the Circuit Cellar ftp site. All of the basic functions necessary to read and write to an ATA hard drive can be found in the code I’m providing.

After you have all of the ImageCraft C source code, a copy of WinHex, and an ATA hard drive controller in front of you, you’ll see that everything you’ve read about in this article isn’t complicated, it’s simply embedded.

Subscribe Today! www.atmel.com

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

A solutioni presented here providesi user--controlled task schedulingi usingi an array of functioni pointers,i , withi the core control func-- tionalityi i consumingi only 386 bytes of code space..

A Compact Scheduler for AVR Microcontrollers

By Andy Gayne & Steve Duckworth, Field Application Engineers, GD Technik Ltd.

Implementing state-machine functionality on a small memory model embedded micro, such as the ATtiny26, can consume much of the valuable code space. A solution presented here provides user-controlled task scheduling using an array of function pointers, with the core control functionality consuming only 386 bytes of code space. The task scheduler enables state-machine operation to be achieved, with tasks able to create and delete other tasks, as well as being able to delete themselves.

The function pointer array size is defined at compile time, with the size of the array being limited only by available SRAM. In this example three tasks are allowed on the queue; any attempt to add a task when the queue is full will be discarded.

Three functions are used to manipulate array entries:

CreateTask

()

 

adds a task to the array, if it

is

 

 

 

not already present.

DeleteTask

()

deletes a task from the array.

FindTask ()

checks for the presence of a task

in

 

 

 

the array.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

FindTask is useful for tasks that have to check for other tasks running before deciding their course of action. CreateTask and DeleteTask are self-explanatory. Following initialization, the main program is constructed around the single program statement:

while(x[n]!=NULL) x[n++]();

This executes, in sequence, the functions referenced by the function pointers stored in the array. The simple implementation presented does not allow the task sequence order to be controlled, except by order of creation. A feature of this implementation is that there must always be at least one task on the queue, otherwise no further additions will be possible.

The example code was written to compile under IAR 2.28A, but should be easily transportable to other compilers. This demonstration contains six task functions, of which two are actually used. There is no limit on the number of tasks that can be implemented, except that imposed by available flash memory space. A complete IAR project archive, including source code, can be down-

loaded from: www.gd-technik.com/fae/schedule

 

 

 

For “The Code”–See Code Patch page 46

 

 

 

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

Atmel AVR-based Constant

Current Supply

By Jeffrey R. Skinner P.E., Chief Engineer, Controltek Inc.

I. Application Requirements:

In September of 2002, a new client approached Controltek requesting design services for a constant current power supply. This supply would receive a regulated 48-volt input and was required to generate a user adjustable constant current output in the range between 3 and 8 Amps. Current regulation including ripple was to be less then ±10% of selected output level. This circuit had to operate over a varying load range between 1_ and 16_ and drive four such independent loads switched in one at a time. In addition the constant current supply is be followed by an H-bridge that switches the direction of current flow through the load at fixed intervals. Regulatory agency approval to UL 508 and CSA 22.2 was also required. The supply had to operate over a temperature range between -20˚C to +70˚C in a NEMA 4 enclosure with no ventilation or external heat sinking.

II. Architectural Approach:

For flexibility, field upgradability, cost, minimum component count and to minimize PCB real-estate requirements, we decided to use a small footprint, low cost microcontroller, implementing current regulation in a software based algorithm rather then in analog hardware. Constant current control would be done in a buck regulator topology with current feedback. The more functions we needed in the circuit that were provided internal to the microcontroller, the fewer additional parts would be required. This would save both cost and PCB real estate. Criteria for the selection of a microcontroller were cost, packaging and an internal peripheral set matching our needs. Adding in the requirement to adjust the target output current over a range between 3 and 8 Amps drove the overall peripheral set requirements for the microcontroller. We would need a two-channel analog to digital converter and a single PWM output. Additionally, the microcontroller needed to have internal FLASH program memory, static RAM and the ability to be in circuit programmed.

Before a decision on the best-fit microcontroller for this application could be made, we needed to know the required resolution and accuracy of the analog to digital converter and the required resolution and frequency for the PWM output. PWM frequency is matched to the inductor and determines the amount of ripple current. Higher switching frequencies result in smaller inductor values and thus smaller magnetic components. Higher switching frequencies also result in greater switching losses in the pass transistor and thus greater power dissipation. Resolution and accuracy of the analog to digital converter is determined by the required current regulation and by the feedback control algorithms stability requirements.

III. Detailed Design Requirements:

A simulation model for the circuit was created in PSPICE as an aid in determining inductor size and PWM frequency. This same model was also used to verify the control algorithm. Initially a P-channel MOSFET was selected for the pass transistor to avoid the high side gate drive requirements of an N-channel device. With an input voltage of 48 volts, commercially available high side gate drive IC’s are very limited. Due to the potential switching losses a pushpull gate drive was used to speed up the turn off time. To meet the requirement of total current error less then ±10% of selected output; the total root sum squared error from all contributing sources had to be less then 90 mvolts. This corresponds to 10% of the minimum output current level of 3.0 amps based on using a 3.0 volt reference for the analog to digital converter, a 0.05_ sense resistor and a differential op-amp with a gain of 6 in the feedback path. With this set of values, and assuming an 8 bit analog to digital

converter, full scale input range to the analog to digital converter would be 10 Amps and scaling in the circuit would be as follows:

(10 Amps)(0.05_)(6) = 3.0 volts = reference voltage 1 volt = 3.33 Amps

1 bit = 3.0 volts/255 = 0.0118 volts per bit or 0.039 Amps per bit.

The Atmel ATtiny15L AVR microcontroller was selected for this project because of its small footprint, internal FLASH memory, in circuit programmability and high speed PWM. Additionally, the potential to make use of its internal voltage reference and differential amplifier was attractive. Unfortunately, the accuracy of the internal voltage reference is not very good. With ±160 mvolts of error its contribution alone would exceed the 90 mvolts allowed by the requirements. Also the differential amplifier gain setting is limited to values of only 1 and 20, neither of which fit well in this application. Using a gain of 1 would require a sense resistor of 0.3_ and at 8 Amps this would dissipate 19.2 watts, not a good choice for a sealed NEMA 4 enclosure with out any external heat sinking. A gain of 20 would require a sense resistor value of only 0.015_ which is equivalent a 1 in length of board trace using 1 oz. Copper 1/32 inch wide. At this low of an ohmic value, trace resistance would cause significant errors in the feedback signal. As a result, the decision was made to use an external voltage reference and operational amplifier. Because the Atmel ATtiny15L has a 10-bit analog to digital converter the scale factor per bit is:

1 bit = 3.0 volts/1023 = 2.9 mvolts or 0.0098 Amps per bit

The complete PSPICE simulation model is shown in figure #1 (see next page). Simulation of the control algorithm for current feedback control is done with the use of analog behavioral models which represent the microcontroller based algorithm. Analog behavioral models used include a gain block, integrator block, sum block, difference block and limiter blocks. The control algorithm is a very simple proportional plus integral loop. It’s important to keep in mind that the ATtiny15L does not have a multiply or divide instruction and has very limited storage for variables, providing only the 32 registers in the general purpose register file. This makes crafting of the control algorithm interesting as selection of the coefficients in the constant coefficient difference equation must be carefully made so that when combined with the selected sample rate the result is a value equal to 2n or 1/2n which can be implemented as bit shifts. To keep the algorithm simple enough for implementation in the ATtiny15L AVR processor, a simple proportional plus integral gain was used. Examination of the frequency response of the circuit combined with a series of transient simulations determined the initial proportional and integral gain values. Proportional gain was set at Kp = 0.5 while the integral gain was set at Ki = 500. Performance of the constant current supply with these gain values can be seen in the simulation plots of figures #2 and #3 (see next page). As can be seen, the system is over damped. This is by choice. In this system, a single constant current supply is used to drive four independent loads one at a time with the output of the supply switched between the four independent loads as discussed in the application requirements. When the load is switched, there is a momentary period when there is no load on the output of the supply. To prevent the output of the constant current supply from rising up to the 48 volt rail during the momentary no load condition the circuit is over damped. There is still a small increase in voltage at the constant current supply output but it is very manageable. When the next

www.atmel.com

page 18

Соседние файлы в предмете Электротехника