Вы находитесь на странице: 1из 56

SOFCON INDIA PVT. LTD.

TRAINING REPORT
On

AVR MICROCONTROLLER
Submitted to Kurukshetra University in partial fulfillment of the requirement for the award of the degree of

BACHELOR OF TECHNOLOGY
ELECTRONICS & COMMUNICATION ENGINEERING

Submitted By PRASHANT SETHI Roll No. 4110253

DEPTT. OF ELECTRONICS & COMMUNICATION ENGINEERING

YAMUNA INSTITUTE OF ENGINEERING & TECHNOLOGY GADHOLI, YAMUNANAGAR-135003


2013-14

PREFACE
Training is an integral part of B.Tech and each and every student has to undergo the training for 6 weeks in a company.

This record is concerned about our practical training during the Summer Vacations of 3rd year. I have taken my Practical training in AVR MICROCONTROLLER.

During this training, we got to learn many new things about the industry and the current requirements of companies. This training proved to be a milestone in our knowledge of present industry scenario and developing business of software in the giant economic field of computers. Every say and every moment was an experience in itself, an experience which theoretical study cant provide.

ACKNOWLEDGEMENT
It is my pleasure to be indebted to various people, who directly or indirectly contributed in the development of this work and who influenced my thinking, behaviour and acts during the course of study. I express my sincere gratitude to Dr. Rajiv Khanduja worthy Principal for providing me an opportunity to undergo summer training at SOFCON INDIA PVT. LTD I am thankful to Er. Manpreet Singh, H.O.D., ECE Deptt for his support, cooperation, and motivation provided to me during for constant inspiration, presence and blessings. I also extend my sincere appreciation to Er. Lalitesh Sehgal , Coordinator who provided his valuable suggestions and precious time in accomplishing my training report.

Prashant Sethi (4110253)

DECLARATION

I, Prashant Sethi, Roll No. 4110253, B.Tech (Semester- VII) of the Yamuna Institute of Engg. & Technology, Gadholi (Yamuna Nagar) hereby declare that the Training Report entitled AVR MICROCONTROLLERS is an original work and data provided in the study is authentic to the best of my knowledge. This report has not been submitted to any other Institute for the award of any other degree.

Place: Date:

Prashant Sethi (4110253)

This is to certify that above statement made by the candidate is correct to the best of my knowledge.

Approved by:

Er. Lalitesh Sehgal ( Coordinator )

Er. Manpreet Singh ( H.O.D., ECE Deptt. )

Contents
CHAPTER 2 :ATMEL AVR: ........................................................................................... 16 2.1 Introduction ................................................................................................................. 18 2.2 Brief history ................................................................................................................ 18 2.3 Device overview ......................................................................................................... 19 2.4 Basic families .............................................................................................................. 19 2.5 Device architecture ..................................................................................................... 20 2.9 Program execution ...................................................................................................... 22 2.10 Instruction set ............................................................................................................ 22 2.11 MCU speed ............................................................................................................... 23 2.12 Development ............................................................................................................. 24 2.13 Features ..................................................................................................................... 24
CHAPTER 3

3.6 Interfacing LCD with AVR ........................................................................................ 37 Types of stepper motor ..................................................................................................... 46 Driving Stepper Motor with AVR MCU .......................................................................... 46 ADC Interfacing of AVR (ATmega32) ............................................................................ 47

LIST OF FIGURES

Figure
1.1.1 1.1.2 3.1.1 3.1.2 3.1.3

Title

Page No

Basic diagram of embedded system..................................................8 Influence of embedded system on ubiquitous computing................11 Seven Segment Display....................................................35 LCD......................................................................................38 Pin Description of lcd....................................................................39

Chapter 1
INTRODUCTION TO EMBEDDED SYSTEM

1.1 Embedded system

Figure1.1.1 Basic diagram of embedded system

Until the late eighties, information processing was associated with large mainframe computers and huge tape drives. During the nineties, this shifted towards information processing being associated with personal computers, PCs. The trend towards miniaturization continues and the majority of information processing devices will be small portable computers integrated into larger products. Their presence in these larger products, such as telecommunication equipment will be less obvious than for the PC. Hence, the new trend has also been called the disappearing computer. However, with this new trend, the computer will actually not disappear, it will be everywhere. Embedded systems provide a major part of the necessary technology. Embedded systems are information processing systems that are embedded into a larger product and that are normally not directly visible to the user. Examples of embedded systems include

information processing systems in telecommunication equipment, in transportation systems, in fabrication equipment and in consumer electronics.

1.2 Common characteristics of embedded system

Frequently, embedded systems are connected to the physical environment through sensors collecting information about that environment and actuators1 controlling that environment. Embedded systems have to be dependable. Many embedded systems are safety-critical and therefore have to be dependable. Nuclear power plants are an example of extremely safety-critical systems that are at least partially controlled by software. Dependability is, however, also important in other systems, such as cars, trains, airplanes etc. A key reason for being safety-critical is that these systems are directly connected to the environment and have an immediate impact on the environment. Dependability encompasses the following aspects of a system: 1. 2. Reliability: Reliability is the probability that a system will not fail. Maintainability: Maintainability is the probability that a failing system can be repaired within a certain time-frame. 3. Availability: Availability is the probability that the system is available. Both the reliability and the maintainability must be high in order to achieve a high availability. 4. Safety: This term describes the property that a failing system will not cause any harm. 5. Security: This term describes the property that confidential data remains confidential and that authentic communication is guaranteed. Embedded systems have to be efficient. The following metrics can be used for evaluating the efficiency of embedded systems:

1.

Energy: Many embedded systems are mobile systems obtaining their energy through batteries. According to forecasts [SEMATECH, 2003], battery technology will improve only at a very slow rate. However, computational requirements are increasing at a rapid rate (especially for multimedia applications) and customers are expecting long run-times from their batteries. Therefore, the available electrical energy must be used very efficiently.

2.

Code-size: All the code to be run on an embedded system has to be stored with the system. Typically, there are no hard discs on which code can be stored. Dynamically adding additional code is still an exception and limited to cases such as Java-phones and set-top boxes. Due to all the other constraints, this means that the code-size should be as small as possible for the intended application. If the instruction memory is to be integrated onto this chip, it should be used very efficiently.

3.

Run-time efficiency: The minimum amount of resources should be used for implementing the required functionality. We should be able to meet time constraints using the least amount of hardware resources and energy. In order to reduce the energy consumption, clock frequencies and supply voltages should be as small as possible. Also, only the necessary hardware components should be present.

4.

Weight: All portable systems must be of low weight. Low weight is frequently an important argument for buying a certain system.

5.

Cost: For high-volume embedded systems, especially in consumer electronics, competitiveness on the market is an extremely crucial issue, and efficient use of hardware components and the software development budget are required. These systems are dedicated towards a certain application. For example, processors running control software in a car or a train will always run that software, and there will be no attempt to run a computer game or spreadsheet program on the same processor. There are mainly two reasons for this:

1. 2.

Running additional programs would make those systems less dependable. Running additional programs is only feasible if resources such as memory are unused. No unused resources should be present in an efficient system.
10

Most embedded systems do not use keyboards, mice and large computer monitors for their user-interface. Instead, there is a dedicated user-interface consisting of push-buttons, steering wheels, pedals etc. Because of this, the user hardly recognizes that information processing is involved. Due to this, the new era of computing has also been characterized by the disappearing computer. Many embedded systems must meet real-time constraints. Not completing computations within a given time-frame can result in a serious loss of the quality provided by the system (for example, if the audio or video quality is affected) or may cause harm to the user (for example, if cars, trains or planes do not operate in the predicted way). Many of todays information processing systems are using techniques for speeding-up information processing on the average. For example, caches improve the average performance of a system. In other cases, reliable communication is achieved by repeating certain transmissions. For example, Internet protocols typically rely on resending messages in case the original messages have been lost. On the average, such repetitions result in a small loss of performance, even though for a certain message the communication delay can be orders of magnitude larger than the normal delay. Many embedded systems are hybrid systems in the sense that they include analog and digital parts. Analog parts use continuous signal values in continuous time, whereas digital parts use discrete signal values in discrete time. Typically, embedded systems are reactive systems. They can be defined as follows: A reactive system is one that is in continual interaction with its environment and executes at a pace determined by that environment. Real embedded systems are very complex and hence difficult to teach. Due to this set of common characteristics, it does make sense to analyze common approaches for designing embedded systems, instead of looking at the different application areas only in isolation. Embedded system is Information processing system meeting most of the characteristics listed above. Most of the characteristics of embedded systems can also be found in a recently introduced type of computing: pervasive computing, also called ambient intelligence. The key goal of this type of computing is to make information available anytime, anywhere.

11

Figure 1.1.2 Influence of embedded systems on ubiquitous computing

1.3 Application areas


The following list comprises key areas in which embedded systems are used: 1. Automotive electronics: Modern cars can be sold only if they contain a significant amount of electronics. These include air bag control systems, engine control systems, anti-braking systems (ABS), air-conditioning, GPS systems, safety features, etc 2. Aircraft electronics: A significant amount of the total value of airplanes is due to the information processing equipment, including flight control systems, anticollision systems, pilot information systems, and others. 3. Trains: For trains, the situation is similar to cars and airplanes. Safety features contribute significantly to the total value of trains, and dependability is extremely important. 4. Telecommunication: Mobile phones have been one of the fastest growing markets in the recent years. For mobile phones, radio frequency (RF) design, digital signal processing and low power design are key aspects. 5. Medical systems: There is a huge potential for improving the medical service by taking advantage of information processing taking place within medical equipment.

12

6. Military applications: Information processing has been used in military equipment for many years. Some of the very first computers analyzed military radar signals. 7. Authentication systems: Embedded systems can be used for authentication purposes. For example, advanced payment systems can provide more security than classical systems. The SMART pen is an example of such an advanced payment system. The SMART pen is a pen-like instrument analyzing physical parameters while its user is signing. Physical parameters include the tilt, force and acceleration. These values are transmitted to a host PC and compared with information available about the user. As a result, it can be checked if both the image of the signature as well as the way it has been produced coincide with the stored information. Other authentication systems include finger print sensors or face recognition systems. Consumer electronics: Video and audio equipment is a very important sector of the electronics industry. The information processing integrated into such equipment is steadily growing. New services and better quality are implemented using advanced digital signal processing techniques Many TV sets, multimedia phones, and game consoles comprise high performance processors and memory systems. They represent special cases of embedded systems. Fabrication equipment: Fabrication equipment is a very traditional area in which embedded systems have been employed for decades. Safety is very important for such systems, the energy consumption is less a problem. As an example, fig. 1.3 (taken from Kopetz [Kopetz, 1997]) shows a container connected to a pipe. The pipe includes a valve and a sensor. Using the readout from the sensor, a computer may have to control the amount of liquid leaving the pipe. Figure1.3. Controlling a valve. The valve is an example of an actuator. Smart buildings: Information processing can be used to increase the comfort level in buildings, can reduce the energy consumption within buildings, and can improve safety and security. Subsystems which traditionally were unrelated have to be connected for this purpose. There is a trend towards integrating air-conditioning, lighting, access control, accounting and distribution

13

of information into a single system. For example, energy can be saved on cooling, heating and lighting of rooms which are empty. Available ooms can be displayed at appropriate places, simplifying ad-hoc meetings and cleaning. Air condition noise can be reduced to a level required for the actual operating conditions. Intelligent usage of blinds can optimize lighting and air-conditioning. Tolerance levels of air conditioning subsystems can be increased for empty rooms, and the lighting can be automatically reduced. Lists of non-empty rooms can be displayed at the entrance of the building in emergency situations. Initially, such systems will mostly be present only in high-tech office buildings. Robotics: Robotics is also a traditional area in which embedded systems have been used. Mechanical aspects are very important for robots. Most of the characteristics described above also apply to robotics. Recently, some new kinds of robots, modeled after animals or human beings, have been designed. This set of examples demonstrates the huge variety of embedded systems. Why does it make sense to consider all these types of embedded systems in one book? It makes sense because information processing in these systems has many common characteristics, despite being physically so different. Fig 1.3 Growing importance of embedded systems The size of the embedded system market can be analyzed from a variety of perspectives. Looking at the number of processors that are currently used, it has been estimated that about 79% of all the processors are used in embedded systems2. Many of the embedded processors are 8-bit processors, but despite this, 75% of all 32-bit processors are integrated into embedded systems [Stiller, 2000]. Already in 1996, it was estimated that the average American came into contact with 60 microprocessors per day [Camposano and Wolf, 1996]. Some high-end cars contain more than 100 processors3. These numbers are much larger than what is typically expected, since most people do not realize that they are using processors. The importance of embedded systems was also stated by journalist Mary Ryan [Ryan, 1995]: ...embedded chips form the backbone of the electronics driven world in which we live. ...they are part of almost everything that runs on electricity According to quite a number of forecasts, the embedded system market will soon be much larger than the market for PC-like systems. Also, the amount of software used in embedded systems is expected to
14

increase. According to Vaandrager, for many products in the area of consumer electronics the amount of code is doubling every two years [Vaandrager, 1998] Embedded systems form the basis of the so-called post-PC era, in which information processing is more and more moving away from just PCs to embedded systems. The growing number of applications results in the need for design technologies supporting the design of embedded systems. Currently available technologies and tools still have important limitations. For example, there is still a need for better specification languages, tools generating implementations from specifications, timing verifiers, realtime operating systems, low-power design techniques, and design techniques for dependable systems. Now a days electronics have developed at very fast rate. It plays a major role in the life of human being and makes it very easy and comfortable. Electronics circuits are designed to obtain a particular function. For this purpose a no of electronic component are suitably connected. Embedded systems have proved changing face of today's industrial scenario. An embedded system is a system is a special-purpose computer system designed to perform one or a few dedicated functions often with real-time computing constraints. It is usually embedded as part of a complete device including hardware and mechanical parts. In contrast, a general-purpose computer, such as a personal computer, can do many different tasks depending on programming. Embedded systems control many of the common devices in use today. Fuelling in unbridled power into industrial computers to tackle the most complex applications, they have made quite an impression with a lot of the leading industrial sectors. Backed with the most durable components and peripherals sticking to the highest quality standards, the next generation embedded computers have what it takes to endure highly trying and harsh work environments. Multifunctional ability is the highlight of these systems even as they comprise a uniquely designed combination of software and hardware to perform highly challenging tasks that are a far cry for the common personal computers. This combination happens to be a programmed platform that is assigned with specific applications for the task and goes through various tests to make sure the systems offer long-life performance. Embedded systems range from portable devices such as digital watches and MP3 players, to large stationary installations like traffic lights, factory controllers, or be a crucial
15

contributor systems controlling nuclear power plants. Complexity varies from low, with a single microcontroller chip, to very high with multiple units, peripherals and networks mounted inside a large chassis or enclosure. Embedded computers serve their purpose in a variety of areas, like the gaming industry, military, security and surveillance, and infotainment. Talking of their abilities and efficiency, a look into the highly popular CorBrick855E embedded computer will offer a good insight into what is possible at their behest

EXAMPLES OF EMBEDDED SYSTEM:

Automated tiller machines (ATMS). Cellular telephones and telephonic switches. Computer network equipment, including routers timeservers and firewalls Computer printers, Copiers. Disk drives (floppy disk drive and hard disk drive) Engine controllers and antilock brake controllers for automobiles. Home automation products like thermostat, air conditioners sprinkles and security monitoring system. House hold appliances including microwave ovens, washing machines, TV sets DVD players/recorders. Medical equipment. Measurement equipment such as digital storage oscilloscopes, logic analyzers and spectrum analyzers. Multimedia appliances: internet radio receivers, TV set top boxes. Stationary video game controllers.

16

Chapter 2
ATMEL AVR

17

2.1 Introduction

The AVR is a modified Harvard architecture 8-bit RISC single chip microcontroller which was developed by Atmel in 1996. The AVR was one of the first microcontroller families to use on-chip flash memory for program storage, as opposed to one-time programmable ROM, EPROM, or EEPROM used by other microcontrollers at the time.

2.2 Brief history

The AVR architecture was conceived by two students at the Norwegian Institute of Technology (NTH) Alf-Egil Bogen Blog (www.alfbogen.com) and Vegard Wollan. The original AVR MCU was developed at a local ASIC house in Trondheim, Norway called Nordic VLSI at the time, now Nordic Semiconductor, where Bogen and Wollan were working as students. It was known as a RISC (Micro RISC) and was available as silicon IP/building block from Nordic VLSI. When the technology was sold to Atmel from Nordic VLSI, the internal architecture was further developed by Bogen and Wollan at Atmel Norway, a subsidiary of Atmel. The designers worked closely with compiler writers at IAR Systems to ensure that the instruction set provided for more efficient compilation of high-level languages. Atmel says that the name AVR is not an acronym and does not stand for anything in particular. The creators of the AVR give no definitive answer as to what the term "AVR" stands for. However, it is commonly accepted that AVR stands for Alf (Egil Bogen) andVegard (Wollan)'s RISC processor. Note that the use of "AVR" in this article generally refers to the 8-bit RISC line of Atmel AVR Microcontrollers. Among the first of the AVR line was the AT90S8515, which in a 40-pin DIP package has the same pinout as an 8051 microcontroller, including the external multiplexed address and data bus. The polarity of the RESET line was opposite (8051's having an active-high RESET, while the AVR has an active-low RESET), but other than that, the pinout was identical.

18

2.3 Device overview


The AVR is a modified Harvard architecture machine where program and data are stored in separate physical memory systems that appear in different address spaces, but having the ability to read data items from program memory using special instructions.

2.4 Basic families

AVRs are generally classified into six broad groups:

tinyAVR the ATtiny series


0.516 kB program memory 632-pin package Limited peripheral set

megaAVR the ATmega series


4512 kB program memory 28100-pin package Extended instruction set (multiply instructions and instructions for handling larger program memories) Extensive peripheral set

XMEGA the ATxmega series


16384 kB program memory 4464100-pin package (A4, A3, A1) Extended performance features, such as DMA, "Event System", and cryptography support. Extensive peripheral set with ADCs

Application-specific AVR

megaAVRs with special features not found on the other members of the AVR family, such as LCD controller, USB controller, advanced PWM, CAN, etc.

FPSLIC (AVR with FPGA)

FPGA 5K to 40K gates


19

SRAM for the AVR program code, unlike all other AVRs AVR core can run at up to 50 MHz

32-bit AVRs In 2006 Atmel released microcontrollers based on the new, 32bit, AVR32 architecture. They include SIMD and DSP instructions, along with other audio and video processing features. This 32-bit family of devices is intended to compete with the ARM based processors. The instruction set is similar to other RISC cores, but it is not compatible with the original AVR or any of the various ARM cores.

2.5 Device architecture

Flash, EEPROM, and SRAM are all integrated onto a single chip, removing the need for external memory in most applications. Some devices have a parallel external bus option to allow adding additional data memory or memory-mapped devices. Almost all devices (except the smallest TinyAVR chips) have serial interfaces, which can be used to connect larger serial EEPROMs or flash chips.

2.6 Program memory

Program instructions are stored in non-volatile flash memory. Although the MCUs are 8-bit, each instruction takes one or two 16-bit words. The size of the program memory is usually indicated in the naming of the device itself (e.g., the ATmega64x line has 64 kB of flash while the ATmega32x line has 32 kB). There is no provision for off-chip program memory; all code executed by the AVR core must reside in the on-chip flash. However, this limitation does not apply to the AT94 FPSLIC AVR/FPGA chips.

20

2.7 Internal data memory

The data address space consists of the register file, I/O registers, and SRAM. The AVRs have 32 single-byte registers and are classified as 8-bit RISC devices. In most variants of the AVR architecture, the working registers are mapped in as the first 32 memory addresses (000016001F16) followed by the 64 I/O registers (002016 005F16). Actual SRAM starts after these register sections (address 006016). (Note that the I/O register space may be larger on some more extensive devices, in which case the memory mapped I/O registers will occupy a portion of the SRAM address space.) Even though there are separate addressing schemes and optimized opcodes for register file and I/O register access, all can still be addressed and manipulated as if they were in SRAM. In the XMEGA variant, the working register file is not mapped into the data address space; as such, it is not possible to treat any of the XMEGA's working registers as though they were SRAM. Instead, the I/O registers are mapped into the data address space starting at the very beginning of the address space. Additionally, the amount of data address space dedicated to I/O registers has grown substantially to 4096 bytes (0000160FFF16). As with previous generations, however, the fast I/O manipulation instructions can only reach the first 64 I/O register locations (the first 32 locations for bitwise instructions). Following the I/O registers, the XMEGA series sets aside a 4096 byte range of the data address space which can be used optionally for mapping the internal EEPROM to the data address space (1000161FFF16). The actual SRAM is located after these ranges, starting at 200016.

2.8 EEPROM

Almost all AVR microcontrollers have internal EEPROM for semi-permanent data storage. Like flash memory, EEPROM can maintain its contents when electrical power is removed.
21

In most variants of the AVR architecture, this internal EEPROM memory is not mapped into the MCU's addressable memory space. It can only be accessed the same way an external peripheral device is, using special pointer registers and read/write instructions which makes EEPROM access much slower than other internal RAM. However, some devices in the SecureAVR (AT90SC) family use a special EEPROM mapping to the data or program memory depending on the configuration. The XMEGA family also allows the EEPROM to be mapped into the data address space. Since the number of writes to EEPROM is not unlimited Atmel specifies 100,000 write cycles in their datasheets a well designed EEPROM write routine should compare the contents of an EEPROM address with desired contents and only perform an actual write if the contents need to be changed. Note that erase and write can be performed separately in many cases, byte-by-byte, which may also help prolong life when bits only need to be set to all 1s (erase) or selectively cleared to 0s (write).

2.9 Program execution

Atmel's AVRs have a two stage, single level pipeline design. This means the next machine instruction is fetched as the current one is executing. Most instructions take just one or two clock cycles, making AVRs relatively fast among the eightbit microcontrollers. The AVR processors were designed with the efficient execution of compiled C code in mind and have several built-in pointers for the task.

2.10 Instruction set

The AVR instruction set is more orthogonal than those of most eight-bit microcontrollers, in particular the 8051 clones and PIC microcontrollers with which AVR competes today. However, it is not completely regular:

Pointer registers X, Y, and Z have addressing capabilities that are different from each other.
22

Register locations R0 to R15 have different addressing capabilities than register locations R16 to R31. I/O ports 0 to 31 have different addressing capabilities than I/O ports 32 to 63. CLR affects flags, while SER does not, even though they are complementary instructions. CLR set all bits to zero and SER sets them to one. (Note that CLR is pseudo-op for EOR R, R; and SER is short for LDI R,$FF. Math operations such as EOR modify flags while moves/loads/stores/branches such as LDI do not.) Accessing read-only data stored in the program memory (flash) requires special LPM instructions; the flash bus is otherwise reserved for instruction memory.

Additionally, some chip-specific differences affect code generation. Code pointers (including return addresses on the stack) are two bytes long on chips with up to 128 kBytes of flash memory, but three bytes long on larger chips; not all chips have hardware multipliers; chips with over 8 kBytes of flash have branch and call instructions with longer ranges; and so forth. The mostly regular instruction set makes programming it using C (or even Ada) compilers fairly straightforward. GCC has included AVR support for quite some time, and that support is widely used. In fact, Atmel solicited input from major developers of compilers for small microcontrollers, to determine the instruction set features that were most useful in a compiler for high-level languages.

2.11 MCU speed

The AVR line can normally support clock speeds from 0 to 20 MHz, with some devices reaching 32 MHz. Lower powered operation usually requires a reduced clock speed. All recent (Tiny, Mega, and Xmega, but not 90S) AVRs feature an on-chip oscillator, removing the need for external clocks or resonator circuitry. Some AVRs also have a system clock prescaler that can divide down the system clock by up to 1024. This prescaler can be reconfigured by software during run-time, allowing the clock speed to be optimized. Since all operations (excluding literals) on registers R0 - R31 are single cycle, the AVR can achieve up to 1 MIPS per MHz, i.e. an 8 MHz processor can achieve up to 8 MIPS. Loads and stores to/from memory take two cycles, branching takes two

23

cycles. Branches in the latest "3-byte PC" parts such as ATmega2560 are one cycle slower than on previous devices.

2.12 Development

AVRs have a large following due to the free and inexpensive development tools available, including reasonably priced development boards and free development software. The AVRs are sold under various names that share the same basic core, but with different peripheral and memory combinations. Compatibility between chips in each family is fairly good, although I/O controller features may vary. See external links for sites relating to AVR development.

2.13 Features

Current AVRs offer a wide range of features:

Multifunction, bi-directional general-purpose I/O ports with configurable, builtin pull-up resistors Multiple internal oscillators, including RC oscillator without external parts Internal, self-programmable instruction flash memory up to 256 kB (384 kB on XMega)

In-system programmable using serial/parallel low-voltage proprietary interfaces or JTAG Optional boot code section with independent lock bits for protection

On-chip debugging (OCD) support through JTAG or debugWIRE on most devices

The JTAG signals (TMS, TDI, TDO, and TCK) are multiplexed on GPIOs. These pins can be configured to function as JTAG or GPIO depending on the setting of a fuse bit, which can be programmed via ISP or HVSP. By default, AVRs with JTAG come with the JTAG interface enabled. debugWIRE uses the /RESET pin as a bi-directional communication channel to access on-chip debug circuitry. It is present on devices with lower pin counts, as it only requires one pin.
24

Internal data EEPROM up to 4 kB Internal SRAM up to 16 kB (32 kB on XMega) External 64 kB little endian data space on certain models, including the Mega8515 and Mega162.

The external data space is overlaid with the internal data space, such that the full 64 kB address space does not appear on the external bus and accesses to e.g. address 010016 will access internal RAM, not the external bus. In certain members of the XMega series, the external data space has been enhanced to support both SRAM and SDRAM. As well, the data addressing modes have been expanded to allow up to 16 MB of data memory to be directly addressed.

AVRs generally do not support executing code from external memory. Some ASSPs using the AVR core do support external program memory. PWM output (some devices have an enhanced PWM peripheral which includes a dead-time generator) Input capture that record a time stamp triggered by a signal edge

8-bit and 16-bit timers

Analog comparator 10 or 12-bit A/D converters, with multiplex of up to 16 channels 12-bit D/A converters A variety of serial interfaces, including

IC compatible Two-Wire Interface (TWI) Synchronous/asynchronous serial peripherals (UART/USART) (used with RS-232, RS-485, and more) Serial Peripheral Interface Bus (SPI) Universal Serial Interface (USI) for two or three-wire synchronous data transfer

Brownout detection Watchdog timer (WDT) Multiple power-saving sleep modes Lighting and motor control (PWM-specific) controller models CAN controller support USB controller support

25

Proper full-speed (12 Mbit/s) hardware & Hub controller with embedded AVR. Also freely available low-speed (1.5 Mbit/s) (HID) bitbanging software emulations

Ethernet controller support LCD controller support Low-voltage devices operating down to 1.8 V (to 0.7 V for parts with built-in DCDC upconverter) picoPower devices DMA controllers and "event system" peripheral communication. Fast cryptography support for AES and DES

26

2.14 Advantages

The Performance, Features, and Tools You Need to Succeed Maximizing Power Efficiency To meet the tough requirements of today's applications, Atmel has built upon more than a decade of low power research to develop Atmel picoPower technology. picoPower enables AVR microcontrollers to reduce power consumption in both sleep and active mode, and achieve the industry's lowest power consumption, with 500nA @ 1.8V with RTC running and 9 nA in power-down sleep mode. A Complete Set of Tools to Streamline Development Atmel offers a high quality, easy-to-use tool chain for the full range of AVR families. Available for free, the Atmel AVR Studio development environment enables code development in C or assembly, simulation, and integrates seamlessly with Atmel starter kits, programmers, debuggers, evaluation kits, and reference designs. The result is faster development, a more productive development team, and rapid time to market. Software Made Easy Atmel offers AVR software framework, a complete library of drivers and middleware needed to build an application. A common Application Protocol Interface (API) is provided making it easy to port your software between different AVR microcontrollers. In addition, a large collection of application notes explains how to use all on-chip peripherals in an application. Capacitive Touch Atmel QTouch Library makes it simple for developers to embed capacitive-touch button, slider, and wheel functionality into general-purpose AVR microcontroller applications. The royalty-free QTouch Library provides several library files for each device and supports different numbers of touch channels, enabling both flexibility and efficiency in touch applications. By selecting the library file supporting the exact number of channels needed, developers can achieve a more compact and efficient code using less RAM. A Perfect Fit for Your Application Atmel compliments its broad range of standard AVR microcontrollers with a growing portfolio of derivatives tailored to specific applications. Our expanding portfolio enables you to support a wide range of applications and functions, including automotive, LCD drivers, CAN networking, USB connectivity, motor control, lighting applications, battery management single-chip, IEEE 802.15.4, ZigBee, Remote Access Control and more. Removing Data Transfer Bottlenecks The DMA controller found in Atmel AVR XMEGA and Atmel AVR UC3 sets a new standard for data transfer efficiency in microcontrollers. It allows efficient data transfers between peripherals and memories with minimal CPU intervention. The result is data
27

transfer rates of up to 33MBit/s per SPI and USART portwith only a 15% load on the CPU. Peripheral Intelligence Atmel SleepWalking technology in AVR XMEGA, AVR UC3, and Atmel megaAVR devices adds intelligence to peripherals, enabling them to perform a basic range check before they generate an interrupt to the CPU. Combined with power save modes, the automatic range check can be applied to remove the need to wake up the CPU at regular intervals to check the environment. The intelligent peripherals will monitor the environment on their own, and only wake the CPU when there is a need for action. Because the CPU draws far more energy than a single peripheral, SleepWalking can dramatically reduce power consumption. Peripheral Cooperation Inefficient peripheral management can impact performance and increase power consumption. To overcome these issues, our peripheral event system lets peripherals send signals (events) directly to other peripherals, bypassing the CPU. The result is short, predictable response times, reduced number of wakeups from sleep, and CPU resources freed up for other tasks. The peripheral event system can also replace interrupt-driven data transfer with event-triggered data transfer, to help reduce application power consumption and increase system performance. Advanced Arithmetic Performance For applications that demand high-end arithmetic performance, selected AVR microcontrollers feature an IEEE754 compliant Floating Point Unit (FPU). This integrated component lets the microcontrollers perform arithmetic calculations on decimal numbers in fewer clock cycles, with higher precision. The FPU helps enhance a wide range of applications. Sensor data can be filtered or analyzed to suppress noise and capture better-quality information, and audio data processed without loss of fidelity. Integrated Security To help safeguard sensitive information, some AVR microcontrollers include a highperformance encryption and decryption engine that supports 128-, 192- and 256-bit key lengths for AES and 56-bit key lengths for DES. These products are ideal for applications that require on-the-fly encryption of high-speed communication streams. Flash Security To safeguard sensitive data, Atmel FlashVault code protection enables on-chip flash to be partially programmed and locked, for secure on-chip storage of software intellectual property. FlashVault code protection can carry software such as a math library or an encryption algorithm to potentially untrustworthy environments where the rest of the source code can be developed and debugged. All AVR microcontrollers contain lock mechanisms to prevent reading and copying the program stored in on-chip Flash. The Power of Self-Programming Flash For flexibility and scalability, support for self-programming Flash enables field upgrades
28

via any communication interface. It also lets customers perform encrypted field programming, reducing or completely eliminating risk of programming the wrong binary. Read-while-Write Flash support lets customers continue to run applications while an upgrade is in progress, to minimize downtime.

29

Chapter 3
Interfacing

30

3.1 Interfacing With The Real World Devices


(Computer Science) a program that controls a display for the user (usually on a computer) and that allows the user to interact with the system part of a system exposed to a user. In general, the system can be any kind of system with which a user may interact at will, such as a mechanical system or a computer system. (Fluid, Electronic, Optic) One of the important issues in micro-fluidics is the interfacing of all the elements. How to align optical fibers? How to connect wires to the micro-device? How to introduce a sample into the fluid channel? These are some of the questions, which have to be solved. An interface is a set of commands or menus through which a user Communicates with a program. A command-driven interface is one in which you enter commands. A menu-driven interface is one in which you select command choices from various menus displayed on the screen. Interfacing is a common term for a variety of materials used on the unseen or "wrong" side of fabrics in sewing. Interfacings can be used to stiffen or add body to fabric, such as the interfacing used in shirt collars; to strengthen a certain area of the fabric, for instance where buttonholes will be sewn; or to keep fabrics, particularly knit fabrics, from stretching out of shape. Interfacings come in a variety of weights and stiffnesses

to suit different purposes.

3.2 User Interface


The user interface is the aggregate of means by which people (the users) Interact with a particular machine, device, computer program or other complex tool (the system). The user interface provides means of: * Input, allowing the users to control the system* & Output, allowing the system to inform the users (also referred to as feedback). A good user interface makes it easy for users to do what they want to do. The junction between a user and a computer program. An interface is a set of A

commands or menus through which a user communicates with a program.

command driven interface is one in which you enter commands. A menu-driven interface is one in which you select command choices from various menus displayed on the screen. The user interface is one of the most important parts of any program because it
31

determines how easily you can make the program do what we want to. It is widely accepted that the user interface can make a critical difference in the perceived utility of a system regardless of the system's performance. In other words, the physical means of communication between a person and a software program or operating system. At its most basic, this is the exchange of typed statements in English or a program-like set of commands. It is the method by which the human operator communicates with the various database, system, and applications modules.

3.3 Efficiency of User Interface Design


Many technological innovations rely upon User Interface Design to elevate their technical complexity to a usable product. Technology alone may not win user

acceptance and subsequent marketability. The User Experience, or how the user experiences the end product, is the key to acceptance. And at is where User Interface Design enters the design the process. While product engineers focus on the technology, usability specialists focus on the user interface. For greatest efficiency and cost effectiveness, this working relationship should be maintained from the start of a project to its rollout. When applied to computer software, User Interface Design is also known as

Human-Computer Interaction or HCI. While people often think of Interface Design in terms of computers, it also refers to many products where the user interacts with controls or displays. Military aircraft, vehicles, airports, audio equipment, and computer

peripherals, are a few products that extensively apply User Interface Design. Optimized User Interface Design requires a systematic approach to the design process. But, to ensure optimum performance, Usability testing is required. This testing empirical

permits nave users to provide data about what does work as anticipated and

what does not work. Only after the resulting repairs are made can a product be deemed to have a user optimized interface. The importance of good User Interface Design can be the difference between product acceptance and rejection in the

marketplace. If end-users feel it is not easy to learn, not easy to use, or too cumbersome, an otherwise excellent product could fail. Good User Interface Design
32

can make a product easy to understand and use, which results in greater user acceptance.

3.4 Interfacing LED With AVR


This AVR tutorial will discuss interfacing Light Emitting Diodes with Atmel's AVR series of Microcontrollers. A LED is an acronym for Light Emitting Diode and is basically a electronic device which emits light when an electric current flows through it. General purpose LEDs used in digital circuits require around 75mA or less and so we usually use resistors to limit the current flowing through the LED when it is connected within a circuit as shown below. The resistance of the resistor is calculated using the well known formula V=IR.

Interfacing a LED with a Microcontroller AVR microcontrollers such as the ATMega8515 only supply a current of about 20mA and so we can drive an LED directly from the microcontroller port eliminating the resistor. In fact if a resistor is added the intensity of the LED will be low. The figure below shows 8-LEDs connected to an ATMega8515 microcontroller. The code that follows if downloaded to the microcontroller will blink the LEDs continuously. Note that this code could work with other AVR microcontrollers such as the ATMega16, ATmega32, ATTiny2313, etc. Note: In order for the circuit to operate as describe the internal oscillator of the ATMega8515 microcontroller must be program to run at 4MHz. /* * * * * */

Written in AVR Studio 5 Compiler: AVR GNU C Compiler (GCC) Author: AVR Tutorials Website: www.AVR-Tutorials.com

#include <avr/io.h>
33

#define F_CPU 4000000UL #include <util/delay.h> int main() { DDRC = 0xFF;

// Configure port C as output

while(1) { PORTC = 0xFF; // Turn ON LEDs _delay_ms(250); // Wait 250ms PORTC = 0x00; // Turn OFF LEDs _delay_ms(250); // Wail 250ms } return 0; }

3.5 SEVEN SEGMENT DISPLAY:


The Light Emitting Diode (LED), finds its place in many applications in this modern electronic fields. One of them is the Seven Segment Display. Seven-segment displays contains the arrangement of the LEDs in Eight (8) passion, and a Dot (.) with a common electrode, lead (Anode or Cathode). The purpose of arranging it in that passion is that we can make any number out of that by switching ON and OFF the particular LED's. Here is the block diagram of the Seven Segment LED arrangement.

34

LEDs are basically of two types: Common Cathode (CC): All the 8 anode legs uses only one cathode, which is common. Common Anode (CA): The common leg for all the cathode is of Anode type.We are using common anode(CA) 7-segment display.

Input: Common anode is connected to the high voltage = 5 Volts This AVR tutorial will discuss interfacing a Seven Segment Display with the AVR 8-bits microcontrollers . A Seven Segment Display is just seven LEDs arranged and packaged in a configuration shown in Fig 1 and it is therefore recommended to complete the tutorial on Interfacing LEDs with the AVR Microcontrollers before going through this tutorial.

The seven LEDs in the seven segment display are labelled with the letters A, B, C, D, E. F and G as indicated in Fig 2 below. Some seven segment display may include 1 or 2 additional LEDs which are used as decimal point(s).

35

Seven Segment Displays are mainly used to display numerical digits. The figure below shows which LEDs to turn ONto display the digits 1, 2, 3, 4, 5 and 6. Other numbers can be displayed by turning ON the appropriate LEDs. A Seven Segment Display can also be used to display certain letters of the alphabet. The figure below gives the LEDs to turn ON to display A, F, H, L and P. Interfacing a Seven Segment Display with a Microcontroller The figure below shows a Seven Segment Display (LDS-C305RI) connected to an ATMega16 microcontroller. Since the seven segment display consists of LEDs it can be connected directly to the ATMega16 or other AVR microcontrollers as shown in the schematic below and as discussed in the Interfacing LEDs with the AVR Microcontrollers tutorial. Important Note: In order for the circuit to operate as describe the internal oscillator of the microcontroller must be program to run at 4MHz. The code that follows if downloaded to the microcontroller will display continuously the sequence 1, 2, 3, 4, A, C, E, F. Note that other microcontrollers such as the ATMega8515 can be used to replace the ATMega16 but the connections would have to be adjusted. For connection information for this seven segment display please see theLDS-C305RI DataSheet. The video at the end of this page shows the circuit in operation when the code is downloaded to the ATMega16 microcontroller. /* * numbers_letters.c * Written in AVR Studio 5 * Compiler: AVR GNU C Compiler (GCC) * * Created: 10/06/2011 05:31:57 PM * Author: AVR Tutorials * Website: www.AVR-Tutorials.com */ #include <avr/io.h> #define F_CPU 4000000UL #include <util/delay.h>

36

int main(void) { DDRA = 0xFF; // Configure port B as output while(1) { //TODO:: Please write your application code PORTA = 0b00110000; _delay_ms(1000); PORTA = 0b01011011; _delay_ms(1000); PORTA = 0b01001111; _delay_ms(1000); PORTA = 0b01100110; _delay_ms(1000); PORTA = 0b01110111; _delay_ms(1000); PORTA = 0b00111001; _delay_ms(1000); PORTA = 0b01111001; _delay_ms(1000); PORTA = 0b01110001; _delay_ms(1000); } return 0; } // // // // // // // // // // // // // // // // Display Number Wait for 1s Display Number Wait for 1s Display Number Wait for 1s Display Number Wait for 1s Display Letter Wait for 1s Display Letter Wait for 1s Display Letter Wait for 1s Display Letter Wait for 1s 1 2 3 4 A C E F

3.6 Interfacing LCD with AVR

A liquid crystal display (LCD) is a thin, flat panel used for electronically displaying information such as text, images, and moving pictures. Its uses include monitors for computers, televisions, instrument panels, and other devices ranging from aircraft cockpit displays, to every-day consumer devices such as video players, gaming devices, clocks, watches, calculators, and telephones. Among its major features are its
37

lightweight construction, its portability, and its ability to be produced in much larger screen sizes than are practical for the construction of cathode ray tube (CRT) display technology. Its low electrical power consumption enables it to be used in batterypowered electronic equipment. It is an electronically-modulated optical device made up of any number of pixels filled with liquid crystals and arrayed in front of a light source (backlight) or reflector to produce images in color or monochrome. The earliest discoveries leading to the development of LCD technology date from 1888. By 2008, worldwide sales of televisions with LCD screens had surpassed the sale of CRT units.

Fig3.1.2 Liquid crystal display (LCD) The most commonly used LCDs found in the market today are 1 line,2 lines or 4 lines LCDs which have only one controller and support at most 80 characters , whereas LCDs supporting more than 80 characters make use of 2 HD44780 controllers. Most LCDs with 1 controller has 14 pins and LCDs with 2 controllers have 16 pins. LCD pin descriptions: The LCD discussed in this section has 14 pins. The function of each pin is given in table.

38

Figure3.1.3 Pin description 1) Vcc & VEE: While Vcc provide +5V and ground, respectively, VEE is used for controlling LCD contrast. 2) RS register select: There are two very important registers inside the LCD. The RS pin is used for their selection as follows: If RS = 0, the instruction command code register is selected, allowing the user to send a command such as clear display, cursor at home, etc. If RS = 1 the data register is selected, allowing the user to send data to be displayed on the LCD. 3) R/W input allows the user to write information to the LCD or read information from it. R/W = 1 when reading; R/W =0 when writing. 4) E Enable: The enable pin is used by the LCD to latch information presented to its data pins. When data is supplied to data pins, a high to low pulse must be applied to this pin in order for the LCD to latch in the data present at the data pins. This pulse must be a minimum of 450 ns wide. 5) D0 D7: The 8 bit data pins, D0 D7, are used to send information to the LCD or read the contents of the LCDs internal registers. To display letters and numbers, we send ASCII codes for the letters A Z, a z, and numbers 0 9 to these pins while making RS = 1.There are also instructions command codes that can be sent to the LCD to clear the display or force the cursor to the home position or blink the cursor.

39

We also use RS = 0 to check the busy flag bit to see if the LCD is ready to receive information. The busy flag is D7 and can be read when R/W =1 and RS = 0, as follows: if R/W =1, RS =0. When D7 = 1(busy flag = 1), the LCD busy taking care of internal operations and will not accept any new information. When D7 = 0, the LCD is ready to receive new information. Note: It is recommended to check the busy flag before writing any data to the LCD. Data display: In LCD, one can put data at any location. The following shows address locations and how they are accessed: RS 0 R/W 0 DB7 1 DB6 A DB5 A DB4 A DB3 A DB2 A DB1 A DB0 A

LCD addressing DB7 Line 1(max.) Line 1(min.) Line 2(max.) Line 2(min.) 1 1 1 1 DB6 0 0 1 1 DB5 0 1 0 1 DB4 0 0 0 0 DB3 0 0 0 0 DB2 0 1 0 1 DB1 0 1 0 1 DB0 0 1 0 1

The upper address range can go as high as 0100111 for 40 character-wide LCD while for the 20 character-wide LCD it goes up to 010011 (19 decimal = 10011 binary). Notice that the upper range 0100111 (binary) = 39 decimal which corresponds to locations 0 to 39 for the LCDs of 40*2 size.

40

Program: #include "mega32.h" #define rs 2 // defined portc.3 as register select pin #define en 3 // defined portc.2 as enable pin void delay(unsigned int ms); void msdelay(unsigned int ms); void lcd_cmd(unsigned char cmd); void lcd_char(unsigned char data); void lcd_string(unsigned char *dat); void lcd_init(); void main(void) { DDRC = 0xff; lcd_init(); lcd_cmd(080); lcd_string(EmbeddedTutorials); while (1) { } } void delay(unsigned int ms) // small delay function { unsigned int i,j; for(i=0;i<=ms;i++) for(j=0;j<=5;j++); } void msdelay(unsigned int ms) // medium delay function { unsigned int i,j; for(i=0;i<=ms;i++) for(j=0;j<=122;j++);
41

} void lcd_cmd(unsigned char cmd) // command function { unsigned char temp; temp = cmd & 0xF0; PORTC&=0x0F; PORTC |= temp; PORTC &= (~(1<<rs)); PORTC |= (1<<en); delay(1); PORTC &= (~(1<<en)); msdelay(5); temp = cmd; temp <<= 4; PORTC&=0x0F; PORTC |= temp; PORTC &= (~(1<<rs)); PORTC |= (1<<en); delay(1); PORTC &= (~(1<<en)); msdelay(5); } void lcd_char(unsigned char data) //character Display function { unsigned char temp; temp = data & 0xF0; PORTC&=0x0F; PORTC |= temp; PORTC |= (1<<rs); PORTC |= (1<<en);
42

delay(1); PORTC &= (~(1<<en)); msdelay(5); temp = data; temp <<= 4; PORTC&=0x0F; PORTC |= temp; PORTC |= (1<<rs); PORTC |= (1<<en); delay(1); PORTC &= (~(1<<en)); msdelay(5); } void lcd_string(unsigned char *dat) // string Display function { while(*dat != \0) { lcd_char(*dat++); } } void lcd_init() // LCD initializing function { lcd_cmd(033); lcd_cmd(032); lcd_cmd(028); //4 datalines,2line display(system set) lcd_cmd(0x0C); //Dislay on,cursor off lcd_cmd(001); //Clear lcd }

43

3.7 Interfacing of STEPPER MOTOR With AVR


Stepper motors pairs nicely with a smart device like a microcontroller to create precise digitally controlled movements that has made possible many of modern gizmos around us. For example a printer, scanner,plotters, fax, floppy drive (not so modern though!), automatic industrial machines like CNC (Computer numerically controlled) drills, laser shows etc. Though to a naked eye the motor of stepper look no other than a DC motor but the difference is that each step of a stepper motor is in control. For example a high speed desktop printer when the paper moves forward, to a novice it seems like a motor is just pushing the paper out but in reality the control board inside the printer request the motor to move the paper exactly same amount that has been printed. This precise movement keeps the next printed pixel in alignment with previously printed pixels. The thing is that the stepper motors have certain amount of steps per full 360 degree rotation (exact number depends on model) the controller can request the stepper to rotate any number of steps. For example if you are making a robot, you want it to move exactly as per your program. Like if you say go forward 100cm then rotate right 45 degrees and move forward 50 cm. You cannot do this with DC Motors, because for it you need to calculate the exact speed for DC motor and then use blind timing for movement. Say if you happen to find out the your robot moves at 5cm per second then to move 100cm it will require 20 second. So you keep the motor on for 20 second and expect that it has moved 100cm. But this can prove failure if the speed of robot changes due to drop in level of battery or some additional weight or simply due to an uneven terrain etc. So this method is not so trustworthy. epper motors pairs nicely with a smart device like a microcontroller to create precise digitally controlled movements that has made possible many of modern gizmos around us. For example a printer, scanner,plotters, fax, floppy drive (not so modern though!), automatic industrial machines like CNC (Computer numerically controlled) drills, laser shows etc. Though to a naked eye the motor of stepper look no other than a DC motor but the difference is that each step of a stepper motor is in control. For example a high speed desktop printer when the paper moves forward, to a novice it seems like a motor is just pushing the paper out but in reality the control board inside the printer request the motor to move the paper exactly same amount that has been printed. This precise movement keeps the next printed pixel in alignment with previously printed pixels. The thing is that the stepper motors have certain amount of steps per full 360 degree rotation (exact number depends on model) the controller can request the stepper to rotate any number of steps. For example if you are making a robot, you want it to move exactly as per your program. Like if you say go forward 100cm then rotate right 45 degrees and move forward 50 cm. You cannot do this with DC Motors, because for it you need to
44

calculate the exact speed for DC motor and then use blind timing for movement. Say if you happen to find out the your robot moves at 5cm per second then to move 100cm it will require 20 second. So you keep the motor on for 20 second and expect that it has moved 100cm. But this can prove failure if the speed of robot changes due to drop in level of battery or some additional weight or simply due to an uneven terrain etc. So this method is not so trustworthy. Stepper motors pairs nicely with a smart device like a microcontroller to create precise digitally controlled movements that has made possible many of modern gizmos around us. For example a printer, scanner,plotters, fax, floppy drive (not so modern though!), automatic industrial machines like CNC (Computer numerically controlled) drills, laser shows etc. Though to a naked eye the motor of stepper look no other than a DC motor but the difference is that each step of a stepper motor is in control. For example a high speed desktop printer when the paper moves forward, to a novice it seems like a motor is just pushing the paper out but in reality the control board inside the printer request the motor to move the paper exactly same amount that has been printed. This precise movement keeps the next printed pixel in alignment with previously printed pixels. The thing is that the stepper motors have certain amount of steps per full 360 degree rotation (exact number depends on model) the controller can request the stepper to rotate any number of steps. For example if you are making a robot, you want it to move exactly as per your program. Like if you say go forward 100cm then rotate right 45 degrees and move forward 50 cm. You cannot do this with DC Motors, because for it you need to calculate the exact speed for DC motor and then use blind timing for movement. Say if you happen to find out the your robot moves at 5cm per second then to move 100cm it will require 20 second. So you keep the motor on for 20 second and expect that it has moved 100cm. But this can prove failure if the speed of robot changes due to drop in level of battery or some additional weight or simply due to an uneven terrain etc. So this method is not so trustworthy. The second method is the use of stepper motors. Say you have a stepper motor of 7.5 degree per step (that means it move 7.5 degree for single step or their are 48 step in full rotation) and their is a gear reduction of ratio of 1:75 then you can control the stepper with an accuracy of 0.1 degree per steps! wow! that's really precise! Now if we assume you have attached a wheel of radius 3.5 cm then you can control the liner motor of your robot with an accuracy of 0.00611 cm (I leave the math on you). That's pretty decent. To move the motor forward 100cm, you just need to step the motor 100/0.00611 times that is 16,366 times. Instead if you step it 16,202 times it will move 99cm. So now the bot is pretty much in your control.

45

In the same way PCBs are drilled at accurate position, SMT components placed automatically at their desired location, pixel on a paper are printed. Below are some videos that may help you get the point.

Types of stepper motor Their are many types of stepper motors available but the two most common types are

Unipolar Stepper Motor- Has simple driver requirement. Less torque at same size and weight as compared to bipolar type. Bipolar Stepper Motor - Has slightly complicated driver requirement. More torque at same size and weight as compared to unipolar type. Since the Unipolar type is simpler to drive we will start our journey with it.

Driving Stepper Motor with AVR MCU In the figure below is shown a simplified construction of a stepper motor. The center is a permanent magnet(PM) rotor. Around it are four electromagnets. One end of all four electromagnet is connected to a point called "common". The common is usually connected to the stepper supply voltage (eg. 12v). The four coils are named A,B,C and D. To rotate a stepper motor, coils are excited in turns like A,B,C,D. The rotor will try to align itself with the currently exited coil. Lets say that the white point shown on rotor is magnetic north pole. Also assume that when coils are excited, their inner end becomes magnetic south. So the white point on rotor will try to align with the currently excited coil.(As the opposite poles attract) So to drive a stepper motor from AVR MCU you just need to excite the coils A,B,C,D in turns to rotate the motor in anti clock wire direction. If you want to rotate the motor in clock wise direction simply excite the coil in reverse order that is D,C,B,A. As the port of AVR can only sink or source 20mA current approximately, they cannot be used to drive the the coils directly. So we need some thing that can boost this current. The part that fit perfectly in this scenario is ULN2003A. It is a high voltage, high current Darlington array. It can be driven directly with a TTL level input and the output can source up to 500ma. Since it is array of seven darlington pair, (of which we require only four) it is much compact. Program #include <avr/io.h>
46

#include <util/delay.h> #include "xstepper.h" void main() { //Initialize the stepper library StepperInit(); _delay_loop_2(10000); while(1) { for(uint16_t i=0;i<24*85;i++) { StepperStepCW(); //Step Clock wise _delay_loop_2(10000); } for(uint16_t i=0;i<24*85;i++) { StepperStepCCW(); //Step Counter Clock wise _delay_loop_2(10000); } } }

The sample code first runs the stepper full 360 degree in clock wise direction and then full 360 degree in counter clock wise direction. This process is repeated as long as the board is powered. The code can be compiled using WinAVR Compiler using the AVR Studio as front end. ADC Interfacing of AVR (ATmega32) The Analogue to Digital Converter of the Atmel AVR Microcontroller was one of the main reasons of me choosing it over the cheap AT89S52 microcontroller.
47

As mentioned in my previous blog post, I had recently given a workshop at the AIUB along with my friend Omee. Due to time shortage, I could not finish my presentation on ADCs. I wanted to share some of the materials that I studied here in my blog post. In short the ADC converts the voltage level measured at a ADC channel pin to a corresponding binary value. The converted value is stored in a 16 bit register ADC which is divided into two segments: ADCH and ADCL. Firstly, the ADC of the ATmega32, or most AVR microcontrollers is 10 bit. That means there are 2^10 or 1024 levels detectable by this ADC which are uniformly spaced over the region of the maximum and minimum voltage level. The minimum voltage is 0V, and maximum is either Vcc or internally generated 2.56V. Before using the ADC it must be preconfigured. The ADC has 8 channels, that can be selected from the ADMUX register. This is the structure of the ADMUX register: The ADMUX register also has a ADLAR bit, which can Left Adjust or right adjust the output of the ADC. This shows the effect of changing ADLAR bit value in ADC: So depending on operation, if the least significant bits can be discarded, and not much accuracy is needed, ADLAR=1 can be used and ADCH value can just be taken readily. Also the reference voltage of ADC is selected by the REFS1 and REFS0 bits. It can be used to select an externally generated Vref, as well as the 2.56V internally generated voltage. For some other control of the ADCs, there are some extra registers: ADC Control and Status Register. Funny thing is, the register structure is different in ATmega8 and ATmega32, so while this post highlights only ATmega32 microcontroller, it is suggested that you should always consult datasheet before writing your code for a specific microcontroller. The ADC can be configured to fire up automatically, so that it converts the value and at the end of conversion, generates an interrupt. These settings are also in the control and status register ADATE - ADC Auto Trigger Enable, if set it will automatically do the conversion based on the triggering condition (discussed later) ADIF - ADC Interrupt Flag
48

ADIE - ADC Interrupt Enable - Triggers Interrupt on completed conversion, works when global interrupt is enabled. ADPS2-0 - these select the clock frequency of the trigger after which the ADC is triggered. SFIOR Register (Also termed as ADCSRB in some microcontrollers) has the function of setting the condition on which the ADC is triggered. For free running mode, it always trigger at the specified clock cycle. For other modes, it can be configured to be triggered at a particular hardware condition or timer or counter condition. It is easy to avoid the division in ADC by using the internal 2.56 V. By using this value we can calculate that ADC = Vin * 400. So Vin = ADC / 400. To further illustrate the example, the voltage from a temperature sensor LM35 is sensed with the ADC. The LM35 gives a voltage of 10mV per degree celsius. So the voltage output = 0.01 V * temperature. So if we measure the value of the ADC, we know that Vin = ADC/400, and again Vin = 0.01 * Temp So 0.01 * Temp = ADC/400, or Temp = ADC / 400 / 0.01 = ADC / 4 So the temperature is just the measured value of the ADC divided by 4. Since division by 4 can be accomplished by a right shift of 2 binary digits, it can be done quite computationally efficiently. This is the model of LM35 IC in proteus. The Temperature is set in the model with the up and down arrows.

Program

#include <avr/io.h> #include <util/delay.h>

49

#include <avr/interrupt.h>

/* Code for single pin addressing */ typedef struct { unsigned char bit0:1; unsigned char bit1:1; unsigned char bit2:1; unsigned char bit3:1; unsigned char bit4:1; unsigned char bit5:1; unsigned char bit6:1; unsigned char bit7:1; }io_reg;

#define D0 >bit4 #define D1 >bit5

((volatile io_reg*)_SFR_MEM_ADDR(PORTA))((volatile io_reg*)_SFR_MEM_ADDR(PORTA))-

/* Code for 7 seg display */ static unsigned 0x3F, 0x06, 0x5B, char SEVEN_SEG[] = {

50

0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71};

volatile int temperature; volatile char garbage;

ISR(ADC_vect) { temperature = ADCL>>2; /*collect sample from ADC */ garbage = ADCL; garbage= ADCH;

51

int main (void) {

int delay = 1000; int i=0; DDRB = 0xFF; DDRA |= 0b11110000;

DDRD &= 0x00; DDRC = 0xFF; PORTC = 0x00; //DDRD = 0x00;

/* adc initialization */ ADCSRA |= (1 << ADPS1) | (1 << ADPS0); ADMUX |= (1 << REFS1) | (1 << REFS0);

//Set ADC to free run mode SFIOR &= ~((1 << ADTS2) | (1 << ADTS1) | (1 << ADTS0));

// Enables ADC for use ADCSRA |= (1 << ADEN);

52

// Enable ADC Interrupt ADCSRA |= (1 << ADIE);

// ADC Auto Trigger Enable ADCSRA |= (1 << ADATE);

// Enable Global Interrupts sei();

// Starts ADC conversion ADCSRA |= (1 << ADSC);

while (1) {

//show number in decimal

D0 = 0; D1 = 0; PORTB = SEVEN_SEG[temperature/10]; D0 = 0; D1 = 1; while (++i < delay);

53

D0 = 0; D1 = 0; PORTB = SEVEN_SEG[temperature%10]; D0 = 1; D1 = 0; while (--i > 0);

} }

54

Chapter 4
REFERANCES

55

WEBSITES 1. 2. 3. 4. 5. 6. 7. www.avrtutorials.com www.engineersgarage.com www.avrbeginners.net www.alldatasheet.com www.books.google.com www.ebooks.com www.wikipedia.org

BOOKS MUHAMMAD ALI MAZIDI DHANANJAY V GADREY

56

Вам также может понравиться