Dynamic Speed Control & Warning System Project Report
View this page in Firefox for adavanced navigation options
The basic idea behind this project is to implement the vehicle tracking which is the most interesting part of building a speed regulating system.
Cameras can be used for acquiring data, but the processing power of the processor is very high. So, here in this project, we are using ultrasonic transmitter and receiver pair with an embedded control so that the he robot will be able to determine how far the obstacle is from it and also find whether the obstacle is moving towards it, stationary or away from it. Using this information the microprocessor can take a decision.
Ultrasonic transducers will have a transmitter and receiver. The time between the start of the transmitted burst and the received burst will be proportional to the distance between the obstacle and the rangefinder. Finally, the range value is written to the LCD (if present), sent to serial interface and the PWM duty cycle is set to a value proportional to distance. According to the distance value present, the speed will also vary. This is how a microprocessor will be designed.
1.1 Problem Statement
The goal of this project is to implement the robotic eye using ultrasonic transmitter and receiver pair with an embedded control. This device will be able to determine how far the obstacle is from it and also find whether the obstacle is moving towards it, stationary or away from it. Using this information the vehicle can take a decision to move or stop.
1.2 Problem Solution
The module developed will be a robotic sensor eye with less cost using a microcontroller and ultrasonic transducers board which helps vehicles to vary its speed according to the obstacle present surrounding it rather than using cameras which uses more processing power of the processor.
1.3 Cruise Control
Cruise control (sometimes known as speed control or auto cruise) is a system that automatically controls the rate of motion of a motor vehicle. The driver sets the speed and the system will take over the throttle of the car to maintain the same speed.
Speed control with a centrifugal governor was used in automobiles as early as the 1910s, notably by Peerless. Peerless advertised that their system would "maintain speed whether up hill or down". The technology was invented by James Watt and Matthew Boulton in 1788 to control steam engines. The governor adjusts the throttle position as the speed of the engine changes with different loads.
Modern cruise control (also known as a speed stat) was invented in 1945 by the blind inventor and mechanical engineer Ralph Teetor. His idea was born out of the frustration of riding in a car driven by his lawyer, who kept speeding up and slowing down as he talked. The first car with Teetor's system was the Chrysler Imperial in 1958. This system calculated ground speed based on driveshaft rotations and used a solenoid to vary throttle position as needed.
1.4 Theory of Operation
In modern designs, the cruise control may need to be turned on before use — in some designs it is always "on" but not always enabled, others have a separate "on/off" switch, while still others just have an "on" switch that must be pressed after the vehicle has been started. Most designs have buttons for "set", "resume", "accelerate", and "coast" functions. Some also have a "cancel" button. Alternatively, tapping the brake or clutch pedal will disable the system, a required feature to prevent the vehicle from accelerating against braking as it attempts to maintain speed. The system is operated with controls easily within the driver's reach, usually with two or more buttons on the steering wheel spokes or on the edge of the hub like those on Honda vehicles, on the turn signal stalk like in some General Motors vehicles or on a dedicated stalk like those found in Toyota and Mercedes-Benz vehicles. Early designs used a dial to set speed choice.
The driver must bring the car up to speed manually and use a button to set the cruise control to the current speed. The cruise control takes its speed signal from a rotating driveshaft, speedometer cable, wheel speed sensor or from the engine's RPM. The car will maintain that speed by pulling the throttle cable with a solenoid or a vacuum driven servomechanism.
All systems must be turned off both explicitly and automatically, when the driver hits the brake or clutch. Cruise control often includes a memory feature to resume the set speed after braking and a coast feature to reset the speed lower without braking. When the cruise control is in effect, the throttle can still be used to accelerate the car, but once the accelerator is released the car will then slow down until it reaches the previously set speed.
On the latest vehicles fitted with electronic throttle control, cruise control can be easily integrated into the vehicle's engine management system. Cruise controls currently being developed include the ability to automatically reduce speed when the distance to a car in front, or the speed limit decreases. This is an advantage for those driving in unfamiliar areas.
1.5 Advantages and Disadvantages
Some of those advantages include:
Its usefulness for long drives across sparsely populated roads. This usually results in better fuel efficiency.
Some drivers use it to avoid unconsciously violating speed limits. A driver who otherwise tends to unconsciously increase speed over the course of a highway journey may avoid a speeding ticket. Such drivers should note, however, that a cruise control may go over its setting on a downhill which is steep enough to accelerate with an idling engine.
However, cruise control can also lead to accidents due to several factors, such as:
The lack of need to maintain constant pedal pressure, which can help lead to accidents caused by highway hypnosis or incapacitated drivers; future systems may include a dead man's switch to avoid this.
When used during inclement weather or while driving on wet or snow- and/or ice-covered roads, the vehicle not equipped with Electronic Stability Control could go into a skid. Stepping on the brake — such as to disengage the cruise control — often results in the driver losing control of the vehicle.
Most systems do not allow the use of the cruise control below a certain speed (normally 35 mph/55 km/h) to discourage use in city driving. Many countries establish that it is illegal to drive within city limits with the cruise control feature activated.
Driving over "rolling" terrain, with gentle up and down portions, can usually be done more economically (using less fuel) by a skilled driver viewing the approaching terrain, by maintaining a relatively constant throttle position and allowing the vehicle to accelerate on the downgrades and decelerate on upgrades, while reducing power when cresting a rise and adding a bit before an upgrade is reached. Cruise control will tend to over throttle on the upgrades and retard on the downgrades, wasting the energy storage capabilities available from the inertia of the vehicle. The inefficiencies from cruise control can be even greater relative to skilled driving in hybrid vehicles.
1.7 Adaptive cruise control
Some modern vehicles have adaptive cruise control (ACC) systems, which is a general term meaning improved cruise control. These improvements can be automatic braking or dynamic set-speed type controls
.
1.8 Automatic Braking Type:The automatic braking type use either a radar or laser setup to allow the vehicle keep pace with the car it is following, slow when closing in on the vehicle in front and accelerating again to the preset speed when traffic allows. Some systems also feature forward collision warning systems, which warns the driver if a vehicle in front - given the speed of both vehicles - gets too close (within the preset headway or braking distance).
2.1 Description of project
The basic idea behind this project is to implement the vehicle tracking which is the most interesting part of building a speed regulating system. Cameras can be used for acquiring data, but the processing power of the processor is very high. So, here in this project, we are using ultrasonic transmitter and receiver pair with an embedded control so that the he robot will be able to determine how far the obstacle is from it and also find whether the obstacle is moving towards it, stationary or away from it. Using this information the microprocessor can take a decision. Ultrasonic transducers will have a transmitter and receiver. The time between the start of the transmitted burst and the received burst will be proportional to the distance between the obstacle and the rangefinder. Finally, the range value is written to the LCD (if present), sent to serial interface and the PWM duty cycle is set to a value proportional to distance. According to the distance value present, the speed will also vary. This is how a microprocessor will be designed. According to the output received from the ultrasonic transducer, the atmega 8515 microcontroller will take the reading and process according to the coding. Here, it displays the output on the Liquid Crystal Display and also the necessary other changes like motor to be on, etc. will occur.
2.2 Block DiagramThe block diagram of the unit is as shown below.
3.1 Steps involved in completing the project
1) Assembly Level Programming has to be done on the task of the project. This coding is done in “AVR Studio 3.53.”
![]()
Figure 3.1.1
Go to menu bar→ project_new_select new project window will open
Give the project name, mention the location, and
Select the project type→AVR Assembler→0k
By this project will be created to create a file in this,
Go to project window right click→click on Create new file→ create new file window
will open→ give the file name with .asm as extension _file will be opened with the given
name where we can write a program for the controller.
2) This coding has to be loaded in hex-code in to the flash memory of the micro
Controller. This loading is done through AVRISP software.
2.4 PROCESS TO CONVERT THE CODE TO HEXA FORMAT:
Go to_project →click on project settings_we get a panel like AVR Assembler
options_go to output file format_select Intel intellect 8/MSD (Intel hex) →ok
By this the code will be converted to hexa format.
To load this hexa code into the controller the software used here is “AVR ISP”.
The software panel will be in the following manner:-
![]()
Figure 3.1.2
AT the bottom of this window we can find a green light which indicates the
device is ready. If the device is not properly connected it shows a red light. We
need to check out the light to be green before loading the program.
16
Here, the device has to be selected first as ATmega8515. Select Flash memory
button. Right click and load the flash file in hex-code. Press ‘F5’ in order to run
the program.
3) Check the output of the program on the LCD and through ‘Terminal’ software.
Terminal software is a one which is used to transmit or receive the data.
The ‘Terminal’ software panel will be in the following manner:-
Figure 3.1.3
4) LCD (Liquid Crystal Display) will show the mode whether it is in danger mode,
medium, average, above average or in out of range mode. It also shows the
distance between the obstacle and the range finder in cms.
5) Here, in this project we are using a motor which represent the speed of the robot
walk. According to the distance value, the speed will vary i.e., the motor speed
3.2 Software Flowchart![]()
Figure 3.2.1
Description of flow chart:
1) Initialize stack, usart, timer0, timer1, port, LCD and interrupts.
2) Transmit single character on to the usart
3) Check whether the obstacle is present <220 cms of distance or not.
4) If not, then display “mode: out of range”,”distance>220cms” on to the LCD.
5) If the distance is <220cms, then check the range of the distance
6) If distance<50cms, then display “mode: Danger”,”distance….cms” (respective
distance) on LCD and vary the speed of the motor.
7) If distance<100cms, then display “mode: Medium”,”distance….cms” (respective
distance) on LCD and vary the speed of the motor.
8) If distance<150cms, then display “mode: Danger”,”distance….cms” (respective
distance) on LCD and vary the speed of the motor.
9) This process has to be continued. Hence, placed in loop.
4.1 Circuit Description
When we transmit some character from the controller, the ultrasonic will start triggering. The rays from ultrasonic transmitter will start outgoing. Whenever there is an obstacle present in front, then those rays will hit back to the ultrasonic receiver. The time in between these outgoing and hitting back is proportional to the distance of the obstacle from the ultrasonic transducers.
The ultrasonic can calculate a maximum distance of 220 cms and require frequency about
40 KHz. Cypress controller is used in ultrasonic board to make frequency as 40 KHz.
The ultrasonic range finder communicates with the circuit board through a RS 232 USART. The ATMEGA 8515 is programmed to take the distance from the range finder calculate the range and vary the speed of the motor with the range and hence display the distance on a LCD display.
4.2 Circuit Diagram
4.2.1 Circuit Diagram Blocks
OPERATION:
RESET CIRCUIT:
Reset pin is used in the controller board in order to bring back the controller to the initial position. The reset circuit will be in the following manner:
Figure 4.2.2
Reset circuit contains one zener diode which operates in reverse bias, one tic-tac switch, one tantalum capacitor and one resistor.Vcc is the supply of +5V which we are giving to the controller board. This supply passes through the zener diode to the controller through pin no. 9. The reset pin here works in active low position. Active low means that whenever we are providing the supply, it will go to the controller.
When we are grounding the circuit, it shows the reset operation. Now, in this circuit, when we press the reset button (tic-tac switch), then the supply will be grounded which means that the supply has been stopped and when we release the switch the controller comes to the initial position. Tantalum capacitor is used here in order to protect the controller from the spike voltages caused due to the sudden change in the voltage when we press and release the tic-tac switch.
Figure 4.2.3
Here, 2nd pin is supply pin 4, 6,8,10 pins are ground pins. 5th pin is connected to the reset pin of the micro controller. 1st pin is connected to MOSI (master out slave in) pin of the micro controller. 9th pin is connected to MISO (master in slave out) pin of the micro controller. 7th pin is connected to the serial clock pin of the micro controller.
DB9 connector:
Figure 4.2.4This is in ‘D’ shape with 9 pins. Hence, called as DB9 connector. This is present to the both sides of RS232 cable. Out of 9 pins we are using 2,3, and5 pins only. 2nd pin is receiving pin of data. 3rd pin is transmission of data. 5th pin is ground, common for both. Through this DB9 pin, the data is transferred from PC to controller or from controller to PC. This is present on both ends of RS232 cable.
EXTERNAL CRYSTAL OSCILLATOR PINS:
These pins are used in order to supply the external frequency to the micro controller. But our micro controller has inbuilt frequency of 1MHz. For some controllers which does not have inbuilt frequency, the external frequency is provided through these pins as below:
Figure 4.2.5
LCD:
It is used to display the outputs
Figure 4.2.6
Pin configuration:
Pin2: Vcc
Pin 1, 5, and pin 16: GND
Pins 7, 8, 9, 10: no connection
Pin4: it is Rs pin which is used to vary whether data or control word to be taken
Pin 6: it is EN pin which is used to enable the LCD
Pins 11, 12, 13, 14: these are the data pins
Pin15: it is Vled+ which is used to produce background light of LCD
4.3 COMPONENT LIST
1) Step down transformer for converting voltage from 230V AC to 12V AC.
2) Power Supply boardà4diodes in bridge rectifier (1N4007), 1buffer diode (1N4007), capacitors (2200uF, 0.1uF, 1000uF), 2 resistors (10k and 1k), 1 regulator (LM 7805), 1 led.
3) Microcontroller boardàATMEGA8515 microcontroller (IC), Max232 (IC) with 4 capacitors (0.1uF), reset circuit containing 1 zener diode, 1 resistor, 1 tantalum capacitor, and 1 tic-tac switch., ISP Header (10 pin connector), 2 DB9 male connectors.
4) One RS232 cable (Serial cable) for communication between cypress micro controller and our microcontroller, ATMEGA8515.
5) Ultrasonic transducer board à ultrasonic transducer pair, cypress micro controller, DB9 connector.
6) LCD for displaying mode and the distance between vehicle and the obstacle in cms.
7) Motor to indicate speed of vehicle.
4.4 PCB Layout
![]()
Figure 4.4.1
5.1 DC Motor:
For laboratory simulation, engine of the vehicle is replaced by a 5V DC motor.
Figure 5.1.1 1
The output of the circuit was connected to a toy car as shown
Figure 5.1.2
Figure 5.1.3
In practical usage the output from the terminals have to be interfaced to the fuel injection system of the vehicle.
1) www.atmel.com ................................ ATMega8515 micro controller
2) www.senet.com.au/~cpeacock.......... RS 232
3) www.maxim-ic.com. ......................... Max 220-249
4) www.OrCAD.com/ ........................... Printed Circuit Board
5) Wikipedia................. ………………. Various articles
6) http://www.cypressmicro.com........... Cypress microcontroller
7) www.mysunrise.ch/users/pfleury/avr-circuits.html .............LCD
8) www.semiconductor.hitatchi.com/products/pdf/99rtd006d2.pdf ..LCD
For a dynamic development of any company updating new technologies is of utmost importance. The model developed by us if for the future generation cruise control which ensures more safety with less cost. “Dynamic Speed Control Automatic Warning System”
Source code, Final Report documents can be accessed after authentication from this link
BASICS OF ULTRASONICS
Ultra sonic Transducer
. Electrostatic device
.Gold plated mylar film (~1" diameter, 0.0005" thick)
. High tension with a high bias voltage (~400V).
. Computer aided design: Combine speaker/microphone
.Use capacitive transducer to send out a pulse of sound
. Measure how long it takes to return to the speaker.
Figure 6
Ø Principle of operation (1)
• Then the distance travelled
– 2d = cDt
• Dt depends on the speed of sound
– c = 341 m/s in air
– c = 1510 m/s in sea water
Ø Principle of operation (2)
Surface cannot be more than 25 degrees off perpendicular with the sensor.
Figure 7
Ultra sonic Transducer set:-
40 kHz transmitter and receiver, matched pair.
Band width: 4K Hz.
Ideal for remote control systems, burglar alarms, flow rate detectors, etc.
0.64” dia X 0.47” high.
Technical Data:
– Dimensions: Diameter: 9/16, base high: 3/8
– Radiant sensitivity: 0,1 Pa.m/V
– Receiving sensitivity: 14 mV/Pa
– Frequency: 30-35 kHz
– Voltage: 0-60 V
– View angle: 110
DRIVING TRANSMITTER
BLOCK-DIAGRAM
Figure 8
High voltage driving is present in transmitter.
Oscillator and Amplifier
• Tolerance of frequency is not so crucial.
. RC oscillator
. NE555 timer
• Amplifier is a level converter
– Operating range in distance
![]()
Figure 9
RECEIVER
BLOCK- DIAGRAM
Figure 10
.
Receiver is nothing but high gain amplifier.
…. Comparator and filters are used as detectors.
BLOCK-DIAGRAM
TRANSMITTER SECTION :
Figure 1
RECEIVER SECTION:
Figure 2
- Operating frequency: 40 kHz
- Range: 25 – 220 cm
- Resolution: 1 cm
- Supply voltage: 5 Vcc
- Current draft: 25 mA (23 mA without LCD)
- Outputs: 1 TTL level serial (9600, n, 8, 1)
An 8-bit counter drives the ultrasonic transmitter named F40kHz and a digital inverter named F40kHz_inv. The phase with the voltage to apply to the positive terminal and the negative terminal of the sensor has been 180 degree shifted, so twice of supply voltage is applied to the sensor.
The 40 kHz transmissions are enabled by an 8-bit counter named Meter that increments one step/cm. Meter input is provided from Time Base (17240 Hz).
The ultrasonic receiver negative terminal is connected to analog ground reference (AGND Pin 25, P02), provided by RefMux_1, a Reference Multiplexer allocated in ACA03 block. The ultrasonic receiver positive terminal is connected to an amplification chain based on a Programmable Gain Amplifier (PGA_1) and two Pole Band Pass Filter (BPF2_1 and BPF2_2). The BPF_2 output is sent to Programmable Threshold level, Comparator named CMPPRG_1. When a 40 kHz signal is received the CMPPRG_1 output is high logic so the software can read it. In the output section 8-bit Serial Transmitter Serial TX.
Cypress Microsystems PsoC Design
ULTRASONICS RANGE FINDER:
![]()
Figure 3 Figure 14
This project is a simple ultrasonic distance meter.
The only components required are the PSOC (Programmable System On Chip) device, two 40 kHz ultrasonic transducers, two resistors and two capacitors. Similar circuits are very complicated and expensive. Using this microcontroller family, all the digital and analog devices are supplied by Programmable System on Chip.
Typical applications include positioning for robotics, generic distance measurement and contact less liquid level measurement.
Main features
• Operating frequency: 40 kHz
• Range: 25 – 220 cm
• Resolution: 1 cm
• Supply voltage: 5 Vcc
• Current draft: 25 mA (23 mA without LCD)
• Outputs: 1 PWM, 1 TTL level serial (9600, n, 8, 1)
• Optional 16 X 2 LCD intelligent display
• Software calibration
• Dynamic receiver stage gain increment
3.4 SCHEMATIC DIAGRAM
Figure 15
SOFTWARE
The main program will first set up the analog and digital blocks and then tests for JP1 to determine normal or calibration mode.
Normal mode: the software continuously run the transmitted ultrasonic burst (+ping) and, after a blank time, waits for return ultrasonic signal (pong). The time between the start of transmitted burst and the start of received burst is proportional to distance between rangefinder and obstacle. Polling the Comparator bus register (TimeBase_int) we can measure this time and store it into a RAM location. Finally, the range value is written to the LCD (if present), sent to serial interface and the PWM duty cycle is set to a value proportional to distance.
Calibration mode: the software is similar to normal mode but the measured value is compared with the constant value 50 and the resultant offset is stored in an EEPROM non-volatile memory location and added to the measured range in normal mode.
TimeBase_int is the interrupt subroutine for TimeBase 8-bit counter. When time1 is greater than value of blank time (blank time is necessary for prevent false echoes caused by lateral receiving of transmitted 40 kHz burst) the software tests the logical value of comparator. If a pong was received the time1 is stored in 3 RAM location “range” and the TimeBase interrupt is disabled, so the value stored in range location represents the measured distance. If comparator output is equal to 0 then PGA_1 gain is dynamically incremented in 16 steps from 1 to 16 modifying the corresponding gain register, so the far echoes are much more amplified.
The Doppler-Effect-based ultrasound motion detection sensor is proposed. The sensor is primarily intended to be used in security systems for detection of moving objects, but can be effectively involved in intelligent children’s toys, automatic door opening devices, and sports training and contact-less-speed measurement equipment.
Operation:-
When we transmit some character from the controller, then the ultrasonic will start triggering. The rays from ultrasonic transmitter will start outgoing. Whenever there is an obstacle present in front, then those rays will hit back to the ultrasonic receiver. The time in between these outgoing and hitting back is proportional to the distance of the obstacle from the ultrasonic transducers. This distance is calculated using the formula 2d=cDt. This is how distance is calculated using ultrasonics.
The ultrasonic can calculate a maximum distance of 220 cms and require frequency about
40 KHz. Cypress controller is used in ultrasonic board to make frequency as 40 KHz.
Basics of Microcontroller
It is a highly integrated microprocessor, which has some inbuilt futures like USART, Flash Memory, EEPROM, ADC, DAC, Oscillators, and Timers etc. Microcontroller can provide only integer values and it can’t provide the floating values. As it has many inbuilt peripherals the circuitry with the microcontroller can be small when compared with the other processors.
There are many companies who manufacture the Microcontrollers like INTEL, ATMEL, PHILIPS, MOTOROLA, PIC etc.
Here we used ATMEL Microcontroller for the project. As ATMEL has many series of controllers like AT89C, AT90S, ATMEGA and ATCAN, ATMEGA and ATCAN are the advanced series of ATMEL. We used ATMEGA series controller. In ATMEGA also there are many different controllers like ATMEGA8, ATMEGA8515, ATMEGA 8535, ATMEGA162, ATMEGA16 and ATMEGA32 etc. From these controllers we used ATMEGA8515 for the project.
Overview:
The ATmega8515 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the ATmega8515 achieves throughputs approaching 1 MIPS per MHz allowing the system designer to optimize power consumption versus processing speed.
The AVR core combines a rich instruction set with 32 general purpose working registers. All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers.
The ATmega8515 provides the following features: 8K bytes of In-System Programmable Flash with Read-While-Write capabilities, 512 bytes EEPROM, 512 bytes SRAM, an External memory interface, 35 general purpose I/O lines, 32 general purpose working registers, two flexible Timer/Counters with compare modes, Internal and External interrupts, a Serial Programmable USART, a programmable Watchdog Timer with internal Oscillator, a SPI serial port, and three software selectable power saving modes. The Idle mode stops the CPU while allowing the SRAM, Timer/Counters, SPI port, and Interrupt system to continue functioning. The Power-down mode saves the Register contents but freezes the Oscillator, disabling all other chip functions until the next interrupt or hardware reset. In Standby mode, the crystal/resonator Oscillator is running while the rest of the device is sleeping. This allows very fast start-up combined with low-power consumption.
The device is manufactured using Atmel’s high density nonvolatile memory technology. The On-chip ISP Flash allows the Program memory to be reprogrammed In-System through an SPI serial interface, by a conventional nonvolatile memory programmer, or by an On-chip Boot program running on the AVR core. The boot program can use any interface to download the application program in the Application Flash memory. Software in the Boot Flash section will continue to run while the Application Flash section is updated, providing true Read-While-Write operation. By combining an 8-bit RISC CPU with In-System Self-programmable Flash on a monolithic chip, the Atmel ATmega8515 is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications.
The ATmega8515 is supported with a full suite of program and system development tools including: C-Compilers, Macro assemblers, Program debugger/simulators, In-circuit Emulators, and Evaluation kits.
Block diagram of ATMEGA8515
Figure 6
4.3 Pin diagram of ATMEGA8515:
Figure 7
Pin Descriptions:
Vcc: Supply voltage.
GND: Ground.
Port A (PA7..PA0):
Port A is an 8-bit bi-directional I/O port. Port pins can provide internal pull-up resistors (selected for each bit). The Port A output buffers can sink 20 mA and can drive LED displays directly. When pins PA0 to PA7 are used as inputs and are externally pulled low, they will source current if the internal pull-up resistors are activated. The Port A pins are tri-stated when a reset condition becomes active, even if the clock is not active. Port A serves as multiplexed address/data input/output when using external SRAM.
Port B (PB7..PB0):
Port B is an 8-bit bi-directional I/O port with internal pull-up resistors. The Port B output buffers can sink 20 mA. As inputs, Port B pins that are externally pulled low will source current if the pull-up resistors are activated. The Port B pins are tri-stated when a reset condition becomes active, even if the clock is not active.
Port C (PC7..PC0):
Port C is an 8-bit bi-directional I/O port with internal pull-up resistors. The Port C output buffers can sink 20 mA. As inputs, Port C pins that are externally pulled low will source current if the pull-up resistors are activated. The Port C pins are tri-stated when a reset condition becomes active, even if the clock is not active. Port C also serves as address output when using external SRAM.
Port D (PD7..PD0):
Port D is an 8-bit bi-directional I/O port with internal pull-up resistors. The Port D output buffers can sink 20 mA. As inputs, Port D pins that are externally pulled low will source current if the pull-up resistors are activated. The Port D pins are tri-stated when a reset condition becomes active, even if the clock is not active.
RESET:
Reset input. A low level on this pin for more than 50 ns will generate a reset, even if the clock is not running. Shorter pulses are not guaranteed to generate a reset.
XTAL1:
Input to the inverting oscillator amplifier and input to the internal clock operating circuit.
XTAL2:
Output from the inverting oscillator amplifier.
ICP:
ICP is the input pin for the Timer/Counter1 Input Capture function.
OC1B:
OC1B is the output pin for the Timer/Counter1 Output CompareB function.
ALE:
ALE is the Address Latch Enable used when the External Memory is enabled. The ALE strobe is used to latch the low-order address (8 bits) into an address latch during the first access cycle, and the AD0 - 7 pins are used for data during the second access cycle.
AVR CPU Core
Introduction:
This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct program execution. The CPU must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts.
Architectural Overview:
Figure 3. Block Diagram of the AVR Architecture
Figure 8
In order to maximize performance and parallelism, the AVR uses Harvard architecture – with separate memories and buses for program and data. Instructions in the Program memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the Program memory. This concept enables instructions to be executed in every clock cycle. The Program memory is In-System re programmable Flash memory
The fast-access Register File contains 32 x 8-bit general purpose working registers with a single clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical ALU operation, two operands are output from the Register File, the operation is executed, and the result is stored back in the Register File – in one clock cycle.
Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data Space addressing – enabling efficient address calculations. One of the these address pointers can also be used as an address pointer for look up tables in Flash Program memory. These added function registers are the 16-bit X-, Y-, and Z-register, described later in this section.
The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated to reflect information about the result of the operation.
Program flow is provided by conditional and unconditional jump and call instructions, able to directly address the whole address space. Most AVR instructions have a single 16-bit word format. Every Program memory address contains a 16- or 32-bit instruction.
Program Flash memory space is divided in two sections, the Boot Program section and the Application Program section. Both sections have dedicated Lock bits for write and read/write protection. The SPM instruction that writes into the Application Flash memory section must reside in the Boot Program section.
During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the total SRAM size and the usage of the SRAM. All user programs must initialize the SP in the reset routine (before subroutines or interrupts are executed). The Stack Pointer SP is read/write accessible in the I/O space. The data SRAM can easily be accessed through the five different addressing modes supported in the AVR architecture.
The memory spaces in the AVR architecture are all linear and regular memory maps.
A flexible interrupt module has its Control Registers in the I/O space with an additional Global Interrupt Enable bit in the Status Register. All interrupts have a separate interrupt vector in the Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the priority.
The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other I/O functions. The I/O Memory can be accessed directly, or as the Data Space locations following those of the Register File, $20 - $5F.
ALU – Arithmetic Logic Unit:
The high-performance AVR ALU operates in direct connection with all the 32 general purpose working registers. Within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. The ALU operations are divided into three main categories – arithmetic, logical, and bit-functions. Some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format.
Status Register
The Status Register contains information about the result of the most recently executed arithmetic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the Status Register is updated after all ALU operations, as specified in the Instruction Set Reference. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. The Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. This must be handled by software.
The AVR Status Register – SREG:
• Bit 7 – I: Global Interrupt Enable:
The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control is then performed in separate control registers. If the Global Interrupt Enable Register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The Ibit can also be set and cleared by the application with the SEI and CLI instructions, as described in the instruction set reference.
• Bit 6 – T: Bit Copy Storage:
The Bit Copy instructions BLD (Bit LoaD) and BST (Bit Store) use the T bit as source or destination for the operated bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the BLD instruction.
• Bit 5 – H: Half Carry Flag:
The Half Carry Flag H indicates a half carry in some arithmetic operations. Half Carry is useful in BCD arithmetic.
• Bit 4 – S: Sign Bit, S = N
V:
The S-bit is always an exclusive or between the Negative Flag N and the Two’s Complement Overflow Flag V.
• Bit 3 – V: Two’s Complement Overflow Flag:
The Two’s Complement Overflow Flag V supports two’s complement arithmetic’s.
• Bit 2 – N: Negative Flag:
The Negative Flag N indicates a negative result in an arithmetic or logic operation.
• Bit 1 – Z: Zero Flag:
The Zero Flag Z indicates a zero result in an arithmetic or logic operation
• Bit 0 – C: Carry Flag:
The Carry Flag C indicates a carry in an arithmetic or logic operation.
Memory Mapping of ATMEGA8515:
Memory is used to store some data or information. It is classified into three parts:
- Data Memory
- EEPROM
- Flash/Program Memory
Data Memory: This is a temporary memory. Data memory is also classified into three types like:
· General Purpose Registers
· I/O Registers
· SRAM
General Purpose Registers:
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve the required performance and flexibility, the following input/output schemes are supported by the Register File:
• One 8-bit output operand and one 8-bit result input
• Two 8-bit output operands and one 8-bit result input
• Two 8-bit output operands and one 16-bit result input
• One 16-bit output operand and one 16-bit result input
Figure 4 shows the structure of the 32 general purpose working registers in the CPU
Figure. AVR CPU General Purpose Working Registers
Most of the instructions operating on the Register File have direct access to all registers, and most of them are single cycle instructions.
As shown in Figure 4, each register is also assigned a data memory address, mapping them directly into the first 32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory organization provides great flexibility in access of the registers, as the X-, Y-, and Z-pointer registers can be set to index any register in the file.
The X-register, Y-register, and Z-register (register pairs):
The registers R26...R31 have some added functions to their general purpose usage. These registers are 16-bit address pointers for indirect addressing of the Data Space. The three indirect address registers X, Y, and Z are defined as described in Figure 5.
In the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement
I/O Registers:
The ATMEGA8515 contains 64 I/O registers. Each register can hold 8 bit of data, and their notations are given by different names. Each register is assigned a data memory location from $0020 and ends at $005f.
SRAM (Static Random Access Memory):
Figure shows how the ATmega8515 SRAM Memory is organized. The lower 608 Data Memory locations address the Register File, the I/O Memory, and the internal data SRAM. The first 96 locations address the Register File and I/O Memory, and the next 512 locations address the internal data SRAM.
An optional external data SRAM can be used with the ATmega8515. This SRAM will occupy an area in the remaining address locations in the 64K address space. This area starts at the address following the internal SRAM. The Register File, I/O, Extended I/O and Internal SRAM occupies the lowest 608 bytes in normal mode, so when using 64KB (65536 bytes) of External Memory, 64928 Bytes of External Memory are available.
When the addresses accessing the SRAM memory space exceeds the internal Data memory locations, the external data SRAM is accessed using the same instructions as for the internal Data memory access. When the internal data memories are accessed, the read and write strobe pins (PD7 and PD6) are inactive during the whole access cycle. External SRAM operation is enabled by setting the SRE bit in the MCUCR Register.
Accessing external SRAM takes one additional clock cycle per byte compared to access of the internal SRAM. This means that the commands LD, ST, LDS, STS, LDD, STD, PUSH, and POP take one additional clock cycle. If the Stack is placed in external SRAM, interrupts, subroutine calls and returns take three clock cycles extra because the two-byte Program Counter is pushed and popped, and external memory access does not take advantage of the internal pipe-line memory access. When external SRAM interface is used with wait-state, one-byte external access takes two, three, or four additional clock cycles for one, two, and three wait-states respectively. Interrupts, subroutine calls and returns will need five, seven, or nine clock cycles more than specified in the instruction set manual for one, two, and three wait-states.
The five different addressing modes for the Data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment. In the Register File, registers R26 to R31 feature the indirect addressing pointer registers.
The direct addressing reaches the entire data space.
The Indirect with Displacement mode reaches 63 address locations from the base address given by the Y- or Z-register.
When using register indirect addressing modes with automatic pre-decrement and post increment, the address registers X, Y, and Z are decremented or incremented.
The 32 general purpose working registers, 64 I/O Registers, and the 512 bytes of internal data SRAM in the ATmega8515 are all accessible through all these addressing modes.
Data Memory Mapping:
Figure 9
EEPROM (Electrically Erasable Programmable Read Only Memory)
The ATmega8515 contains 512 bytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles. The access between the EEPROM and the CPU is described in the following, specifying the EEPROM Address Registers, the EEPROM Data Register, and the EEPROM Control Register.
Figure 10
Flash /Program memory:
The ATmega8515 contains 8K bytes On-chip In-System Reprogrammable Flash memory for program storage. Since all AVR instructions are 16 or 32 bits wide, the Flash is organized as 4K x 16. For software security, the Flash Program memory space is divided into two sections, Boot Program section and Application Program section.
The Flash memory has an endurance of at least 10,000 write/erase cycles. The ATmega8515 Program Counter (PC) is 12 bits wide, thus addressing the 4K Program memory locations.
Constant tables can be allocated within the entire Program memory address space, see
the LPM – Load Program memory instruction description.
Program memory map:
Figure 11
EEPROM:
The ATmega8515 contains 512 bytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles. The access between the EEPROM and the CPU is described in the following, specifying the EEPROM Address Registers, the EEPROM Data Register, and the EEPROM Control Register.
EEPROM Read/Write Access:
The EEPROM Access Registers are accessible in the I/O space.
The write access time for the EEPROM is given in Table 1. A self timing function, however, lets the user software detect when the next byte can be written. If the user code contains instructions that write the EEPROM, some precautions must be taken. In heavily filtered power supplies, VCC is likely to rise or fall slowly on Power-up/down. This causes the device for some period of time to run at a voltage lower than specified as
minimum for the clock frequency used.
In order to prevent unintentional EEPROM writes, a specific write procedure must be followed. Refer to the description of the EEPROM Control Register for details on this.
When the EEPROM is read, the CPU is halted for four clock cycles before the next instruction is executed. When the EEPROM is written, the CPU is halted for two clock cycles before the next instruction is executed.
EEPROM Address Register:
• Bits 15...9 – Res: Reserved Bits:
These bits are reserved bits in the ATmega8515 and will always read as zero.
• Bits 8...0 – EEAR8...0: EEPROM Address:
The EEPROM Address Registers – EEARH and EEARL specify the EEPROM address in the 512 bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 511. The initial value of EEAR is undefined. A proper value must be written before the EEPROM may be accessed.
The EEPROM Data Register – EEDR:
• Bits 7..0 – EEDR7.0: EEPROM Data:
For the EEPROM write operation, the EEDR Register contains the data to be written to the EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address given by EEAR.
The EEPROM Control Register – EECR:
• Bits 7...3 – Res: Reserved Bits:
These bits are reserved bits in the ATmega8515 and will always read as zero.
• Bit 2 – EEMWE: EEPROM Master Write Enable:
The EEMWE bit determines whether setting EEWE to one cause the EEPROM to be written. When EEMWE is set, setting EEWE within four clock cycles will write data to the EEPROM at the selected address. If EEMWE is zero, setting EEWE will have no effect. When EEMWE has been written to one by software, hardware clears the bit to zero after four clock cycles. See the description of the EEWE bit for an EEPROM write procedure.
• Bit 1 – EEWE: EEPROM Write Enable:
The EEPROM Write Enable signal EEWE is the write strobe to the EEPROM. When address and data are correctly set up, the EEWE bit must be written to one to write the value into the EEPROM. The EEMWE bit must be written to one before a logical one is written to EEWE; otherwise no EEPROM write takes place. The following procedure should be followed when writing the EEPROM (the order of steps 3 and 4 is not essential):
1. Wait until EEWE becomes zero.
2. Write new EEPROM address to EEAR (optional).
3. Write new EEPROM data to EEDR (optional).
4. Set EEMWE bit while waiting for EEWE bit to be cleared.
5. Within four clock cycles after setting EEMWE, write a logical one to EEWE.
The EEPROM can not be programmed during a CPU write to the Flash memory. The software must check that the Flash programming is completed before initiating a new EEPROM write.
Caution: An interrupt between step 5 and step 6 will make the write cycle fail, since the EEPROM Master Write Enable will time-out. If an interrupt routine accessing the EEPROM is interrupting another EEPROM access, the EEAR or EEDR Register will be modified, causing the interrupted EEPROM access to fail. It is recommended to have the Global Interrupt Flag cleared during all the steps to avoid these problems.
When the write access time has elapsed, the EEWE bit is cleared by hardware. The user software can poll this bit and wait for a zero before writing the next byte. When EEWE has been set, the CPU is halted for two cycles before the next instruction is executed.
• Bit 0 – EERE: EEPROM Read Enable:
The EEPROM Read Enable Signal EERE is the read strobe to the EEPROM. When the correct address is set up in the EEAR Register, the EERE bit must be written to a logic one to trigger the EEPROM read. The EEPROM read access takes one instruction, and the requested data is available immediately. When the EEPROM is read, the CPU is halted for four cycles before the next instruction is executed. The user should poll the EEWE bit before starting the read operation. If a write operation is in progress, it is neither possible to read the EEPROM, nor to change the EEAR Register.
Preventing EEPROM Corruption:
During periods of low VCC, the EEPROM data can be corrupted because the supply voltage is too low for the CPU and the EEPROM to operate properly. These issues are the same as for board level systems using EEPROM, and the same design solutions should be applied.
An EEPROM data corruption can be caused by two situations when the voltage is too low. First, a regular write sequence to the EEPROM requires a minimum voltage to operate correctly. Secondly, the CPU itself can execute instructions incorrectly, if the supply voltage is too low. EEPROM data corruption can easily be avoided by following this design recommendation.
Keep the AVR RESET active (low) during periods of insufficient power supply voltage. This can be done by enabling the internal Brown-out Detector (BOD). If the detection level of the internal BOD does not match the needed detection level, an external low VCC Reset Protection circuit can be used. If a Reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient.
I/O Ports:
Introduction:
All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the SBI and CBI instructions. The same applies when changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input). Each output buffer has symmetrical drive characteristics with both high sink and source capability. The pin driver is strong enough to drive LED displays directly. All port pins have individually selectable pull-up resistors with a supply-voltage invariant resistance. All I/O pins have protection diodes to both VCC and Ground
Configuring the Pin:
Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. Athe DDxn bits are accessed at the DDRx I/O address, the PORTxn bits at the PORTx I/O address, and the PINxn bits at the PINx I/O address.
The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one, Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin.
If PORTxn is written a logic one when the pin is configured as an input pin, the pull-up resistor is activated. To switch the pull-up resistor off, PORTxn has to be written a logic zero or the pin has to be configured as an output pin. The port pins are tri-stated when a reset condition becomes active, even if no clocks are running.
If PORTxn is written a logic one when the pin is configured as an output pin, the port pin is driven high (one). If PORTxn is written a logic zero when the pin is configured as an output pin, the port pin is driven low (zero).
When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn} = 0b11), an intermediate state with either pull-up enabled ({DDxn, PORTxn} = 0b01) or output low ({DDxn, PORTxn} = 0b10) must occur. Normally, the pull-up enabled state is fully acceptable, as a high-impedant environment will not notice the difference between a strong high driver and a pull-up. If this is not the case, the PUD bit in the SFIOR Register can be set to disable all pull-ups in all ports.
Switching between input with pull-up and output low generates the same problem. The user must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state ({DDxn, PORTxn} = 0b11) as an intermediate step.
Five ports present in ATMEGA8515v microcontroller are:
1) PORT A
2) PORT B
3) PORT C
4) PORT D
5) PORT E
Alternate Functions of Port A:
Port A has an alternate function as the address low byte and data lines for the External Memory Interface.
Alternate Functions Of Port B: The Port B pins with alternate functions are shown in Table
The alternate pin configuration is as follows:
• SCK – Port B, Bit 7:
SCK: Master Clock output, Slave Clock input pin for SPI channel. When the SPI is enabled as a Slave, this pin is configured as an input regardless of the setting of DDB7. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB7. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB7 bit.
• MISO – Port B, Bit 6:
MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI is
enabled as a Master, this pin is configured as an input regardless of the setting of DDB6. When the SPI is enabled as a Slave, the data direction of this pin is controlled by DDB6. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB6 bit.
• MOSI – Port B, Bit 5:
MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI is enabled as a Slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB5. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit.
• SS – Port B, Bit 4:
SS: Slave Select input. When the SPI is enabled as a Slave, this pin is configured as an input regardless of the setting of DDB4. As a Slave, the SPI is activated when this pin is driven low. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB4. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB4 bit.
• AIN1 – Port B, Bit 3:
AIN1, Analog Comparator Negative input. Configure the port pin as input with the internal pull-up switched off to avoid the digital port function from interfering with the function of the Analog Comparator.
• AIN0 – Port B, Bit 2:
AIN0, Analog Comparator Positive input. Configure the port pin as input with the internal pull-up switched off to avoid the digital port function from interfering with the function of the Analog Comparator.
• T1 – Port B, Bit 1:
T1, Timer/Counter1 Counter Source.
• T0/OC0 – Port B, Bit 0:
T0, Timer/Counter0 Counter Source.
OC0, Output Compare Match output: The PB0 pin can serve as an external output for the Timer/Counter0 Compare Match. The PB0 pin has to be configured as an output (DDB0 set (one)) to serve this function. The OC0 pin is also the output pin for the PWM mode timer function.
Alternate Functions of Port C: The Port C pins with alternate functions are shown in Table
• A15 – Port C, Bit 7:
A15, External memory interface address bit 15.
• A14 – Port C, Bit 6:
A14, External memory interface address bit 14.
• A13 – Port C, Bit 5:
A13, External memory interface address bit 13.
• A12 – Port C, Bit 4:
A12, External memory interface address bit 12.
• A11 – Port C, Bit 3:
A11, External memory interface address bit 11.
• A10 – Port C, Bit 2:
A10, External memory interface address bit 10.
• A9 – Port C, Bit 1:
A9, External memory interface address bit 9.
• A8 – Port C, Bit 0:
A8, External memory interface address bit 8.
Alternate Functions of Port D: The Port D pins with alternate functions are shown in Table
The alternate pin configuration is as follows:
• RD – Port D, Bit 7:
RD is the External Data memory read control strobe.
• WR – Port D, Bit 6:
WR is the External Data memory write control strobe.
• OC1A – Port D, Bit 5:
OC1A, Output Compare Match A output: The PD5 pin can serve as an external output for the Timer/Counter1 Output Compare A. The pin has to be configured as an output (DDD5 set (one)) to serve this function. The OC1A pin is also the output pin for the PWM mode timer function.
• XCK – Port D, Bit 4:
XCK, USART External Clock. The Data Direction Register (DDD4) controls whether the clock is output (DDD4 set) or input (DDD4 cleared). The XCK pin is active only when USART operates in Synchronous mode.
• INT1 – Port D, Bit 3:
INT1, External Interrupt source 1: The PD3 pin can serve as an external interrupt source.
• INT0/XCK1 – Port D, Bit 2:
INT0, External Interrupt Source 0: The PD2 pin can serve as an external interrupt source. XCK1, External Clock. The Data Direction Register (DDD2) controls whether the clock is output (DDD2 set) or input (DDD2 cleared).
• TXD – Port D, Bit 1:
TXD, Transmit Data (Data output pin for USART). When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1.
• RXD – Port D, Bit 0:
RXD, Receive Data (Data input pin for USART). When the USART Receiver is enabled
this pin is configured as an input regardless of the value of DDD0. When USART forces
this pin to be an input, the pull-up can still be controlled by the PORTD0 bit.
Alternate Functions of Port E: The Port E pins with alternate functions are shown in Table
The alternate pin configuration is as follows:
• OC1B – Port E, Bit 2:
OC1B, Output Compare Match B output: The PE2 pin can serve as an external output for the Timer/Counter1 Output Compare B. The pin has to be configured as an output (DDE2 set (one)) to serve this function. The OC1B pin is also the output pin for the PWM mode timer function.
• ALE – Port E, Bit 1:
ALE is the external Data memory Address Latch Enable signal.
• ICP/INT2 – Port E, Bit 0:
ICP – Input Capture Pin: The PE0 pin can act as an Input Capture pin for
Timer/Counter1.
INT2, External Interrupt Source 2: The PE0 pin can serve as an external interrupt source.
USART
The Universal Synchronous and Asynchronous serial Receiver and Transmitter
(USART) is a highly flexible serial communication device.
The main features are:
• Full Duplex Operation (Independent Serial Receive and Transmit Registers)
• Master or Slave Clocked Synchronous Operation
• High Resolution Baud Rate Generator
• Supports Serial Frames with 5, 6, 7, 8, or 9 Data Bits and 1 or 2 Stop Bits
• Odd or Even Parity Generation and Parity Check Supported by Hardware
• Data over Run Detection
• Framing Error Detection
• Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter
• Three Separate Interrupts on TX Complete, TX Data Register Empty and RX Complete
• Multi-processor Communication Mode
• Double Speed Asynchronous Communication Mode
AVR USART vs. AVR UART – Compatibility:
The USART is fully compatible with the AVR UART regarding:
• Bit locations inside all USART Registers
• Baud Rate Generation
• Transmitter Operation
• Transmit Buffer Functionality
• Receiver Operation
However, the receive buffering has two improvements that will affect the compatibility in
some special cases:
• A second Buffer Register has been added. The two buffer registers operate as a circular FIFO buffer. Therefore the UDR must only be read once for each incoming data! More important is the fact that the Error Flags (FE and DOR) and the ninth data bit (RXB8) are buffered with the data in the receive buffer. Therefore the status bits must always be read before the UDR Register is read. Otherwise the error status will be lost since the buffer state is lost.
• The Receiver Shift Register can now act as a third buffer level. This is done by allowing the received data to remain in the serial Shift Register (see Figure 75) if the Buffer Registers are full, until a new start bit is detected. The USART is therefore more resistant to Data OverRun (DOR) error conditions. The following control bits have changed name, but have same functionality and register location:
• CHR9 is changed to UCSZ2.
• OR is changed to DOR.
Frame Formats:
A serial frame is defined to be one character of data bits with synchronization bits (start and stop bits), and optionally a parity bit for error checking. The USART accepts all 30 combinations of the following as valid frame formats:
• 1 start bit
• 5, 6, 7, 8, or 9 data bits
• no, even or odd parity bit
• 1 or 2 stop bits
A frame starts with the start bit followed by the least significant data bit. Then the next data bits, up to a total of nine, are succeeding, ending with the most significant bit. If
enabled, the parity bit is inserted after the data bits, before the stop bits. When a complete
frame is transmitted, it can be directly followed by a new frame, or the communication line can be set to an idle (high) state. Figure 78 illustrates the possible combinations of the frame formats. Bits inside brackets are optional.
Figure 22St: Start bit, always low.
(n): Data bits (0 to 8).
P: Parity bit. Can be odd or even.
Sp: Stop bit, always high.
(IDLE) St 0 1 2 3 4 [5] [6] [7] [8] [P] Sp1 [Sp2] (St / IDLE)
FRAME
IDLE No transfers on the communication line (RxD or TxD). An IDLE line must be
high.
The frame format used by the USART is set by the UCSZ2:0, UPM1:0 and USBS bits in
UCSRB and UCSRC. The Receiver and Transmitter use the same setting. Note that changing the setting of any of these bits will corrupt all ongoing communication for both the Receiver and Transmitter. The USART Character Size (UCSZ2:0) bits select the number of data bits in the frame. The USART Parity mode (UPM1:0) bits enable and set the type of parity bit. The selection between one or two stop bits is done by the USART Stop Bit Select (USBS) bit. The receiver ignores the second stop bit. An FE (Frame Error) will therefore only be detected in the cases where the first stop bit is zero.
Parity Bit Calculation: The parity bit is calculated by doing an exclusive-or of all the data bits. If odd parity is used, the result of the exclusive or is inverted. The relation between the parity bit and data bits is as follows:
Peven Parity bit using even parity
Podd Parity bit using odd parity
Dn Data bit n of the character
USART Initialization:
The USART has to be initialized before any communication can take place. The initialization process normally consists of setting the baud rate, setting frame format and enabling the Transmitter or the Receiver depending on the usage. For interrupt driven USART operation, the Global Interrupt Flag should be cleared (and interrupts globally disabled) when doing the initialization. Before doing a re-initialization with changed baud rate or frame format, be sure that there are no ongoing transmissions during the period the registers are changed. The TXC Flag can be used to check that the Transmitter has completed all transfers, and the RXC Flag can be used to check that there are no unread data in the receive buffer. Note that the TXC Flag must be cleared before each transmission (before UDR is written) if it is used for this purpose.
The following simple USART initialization code examples show one assembly and one C function that are equal in functionality. The examples assume asynchronous operation using polling (no interrupts enabled) and a fixed frame format. The baud rate is
given as a function parameter. For the assembly code, the baud rate parameter is assumed
to be stored in the r17:r16 Registers. When the function writes to the UCSRC Register, the URSEL bit (MSB) must be set due to the sharing of I/O location by UBRRH and UCSRC.
Baud and Control Registers, and for these types of applications the initialization code can be placed directly in the main routine, or be combined with initialization code for other I/O modules.
Data Transmission – The USART Transmitter:
The USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in the UCSRB Register. When the Transmitter is enabled, the normal port operation of the TxD pin is overridden by the USART and given the function as the transmitter’s serial output. The baud rate, mode of operation and frame format must be set up once before doing any transmissions. If synchronous operation is used, the clock on the XCK pin will be overridden and used as transmission clock.
Sending Frames with 5 to 8 Data Bit:
A data transmission is initiated by loading the transmit buffer with the data to be transmitted. The CPU can load the transmit buffer by writing to the UDR I/O location. The buffered data in the transmit buffer will be moved to the Shift Register when the Shift Register is ready to send a new frame. The Shift Register is loaded with new data if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is transmitted. When the Shift Register is loaded with new data, it will transfer one complete frame at the rate given by the Baud Register, U2X bit or by XCK depending on mode of operation.
The following code examples show a simple USART transmit function based on polling of the Data Register Empty (UDRE) Flag. When using frames with less than eight bits, the most significant bits written to the UDR are ignored. The USART has to be initialized before the function can be used. For the assembly code, the data to be sent is assumed to be stored in Register R16
Transmitter Flags and Interrupts:
The USART Transmitter has two flags that indicate its state: USART Data Register Empty (UDRE) and Transmit Complete (TXC). Both flags can be used for generating interrupts.
The Data Register Empty (UDRE) Flag indicates whether the transmit buffer is ready to receive new data. This bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not yet been moved into the Shift Register. For compatibility with future devices, always write this bit to zero when writing the UCSRA Register.
When the Data Register Empty Interrupt Enable (UDRIE) bit in UCSRB is written to one, the USART Data Register Empty Interrupt will be executed as long as UDRE is set (provided that global interrupts are enabled). UDRE is cleared by writing UDR. When interrupt-driven data transmission is used, the Data Register Empty Interrupt routine must either write new data to UDR in order to clear UDRE or disable the Data Register Empty Interrupt, otherwise a new interrupt will occur once the interrupt routine terminates. The Transmit Complete (TXC) Flag bit is set one when the entire frame in the Transmit Shift Register has been shifted out and there are no new data currently present in the transmit buffer. The TXC Flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location.
The TXC Flag is useful in half-duplex communication interfaces (like the RS 485 standard), where a transmitting application must enter Receive mode and free the communication bus immediately after completing the transmission.
When the Transmit Compete Interrupt Enable (TXCIE) bit in UCSRB is set, the USART Transmit Complete Interrupt will be executed when the TXC Flag becomes set (provided that global interrupts are enabled). When the transmit complete interrupt is used, the interrupt handling routine does not have to clear the TXC Flag, this is done automatically when the interrupt is executed.
Parity Generator:
The Parity Generator calculates the parity bit for the serial frame data. When parity bit is enabled (UPM1 = 1), the transmitter control logic inserts the parity bit between the last data bit and the first stop bit of the frame that is sent.
Disabling the Transmitter:
The disabling of the Transmitter (setting the TXEN to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the Transmit Shift Register and Transmit Buffer Register do not contain data to be transmitted. When disabled, the Transmitter will no longer override the TxD pin.
Data Reception – The USART Receiver:
The USART Receiver is enabled by writing the Receive Enable (RXEN) bit in the UCSRB Register to one. When the receiver is enabled, the normal pin operation of the RxD pin is overridden by the USART and given the function as the receiver’s serial input. The baud rate, mode of operation and frame format must be set up once before any serial reception can be done. If synchronous operation is used, the clock on the XCK pin will be used as transfer clock.
Receiving Frames with 5 to 8 Data Bits:
The Receiver starts data reception when it detects a valid start bit. Each bit that follows the start bit will be sampled at the baud rate or XCK clock, and shifted into the Receive Shift Register until the first stop bit of a frame is received. A second stop bit will be ignored by the Receiver. When the first stop bit is received, i.e., a complete serial frame is present in the Receive Shift Register, the contents of the Shift Register will be moved into the receive buffer. The receive buffer can then be read by reading the UDR I/O location. The following code example shows a simple USART receive function based on polling of the Receive Complete (RXC) Flag. When using frames with less than eight bits the most significant bits of the data read from the UDR will be masked to zero. The USART has to be initialized before the function can be used.
Receive Compete Flag and Interrupt:
The USART Receiver has one flag that indicates the receiver state. The Receive Complete (RXC) Flag indicates if there are unread data present in the receive buffer. This flag is one when unread data exist in the receive buffer, and zero when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled (RXEN = 0), the receive buffer will be flushed and consequently the RXC bit will become zero. When the Receive Complete Interrupt Enable (RXCIE) in UCSRB is set, the USART Receive Complete Interrupt will be executed as long as the RXC Flag is set (provided that global interrupts are enabled). When interrupt-driven data reception is used, the receive complete routine must read the received data from UDR in order to clear the RXC Flag, otherwise a new interrupt will occur once the interrupt routine terminates.
Receiver Error Flags :
The USART Receiver has three Error Flags: Frame Error (FE), Data OverRun (DOR) and Parity Error (UPE). All can be accessed by reading UCSRA. Common for the Error Flags is that they are located in the receive buffer together with the frame for which they indicate the error status. Due to the buffering of the Error Flags, the UCSRA must be
read before the receive buffer (UDR), since reading the UDR I/O location changes the buffer read location. Another equality for the Error Flags is that they can not be altered by software doing a write to the flag location. However, all flags must be set to zero when the UCSRA is written for upward compatibility of future USART implementations.
None of the Error Flags can generate interrupts. The Frame Error (FE) Flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. The FE Flag is zero when the stop bit was correctly read (as one), and the FE Flag will be one when the stop bit was incorrect (zero). This flag can be used for detecting out-of-sync conditions, detecting break conditions and protocol handling. The FE Flag is not affected by the setting of the USBS bit in UCSRC since the receiver ignores all, except for the first, stop bits. For compatibility with future devices, always set this bit to zero when writing to UCSRA. The Data OverRun (DOR) Flag indicates data loss due to a receiver buffer full condition. A Data OverRun occurs when the receive buffer is full (two characters), it is a new character waiting in the Receive Shift Register, and a new start bit is detected. If the DOR Flag is set there was one or more serial frame lost between the frame last read from UDR, and the next frame read from UDR. For compatibility with future devices, always write this bit to zero when writing to UCSRA. The DOR Flag is cleared when the frame received was successfully moved from the Shift Register to the receive buffer. The Parity Error (UPE) Flag indicates that the next frame in the receive buffer had a Parity Error when received. If parity check is not enabled the UPE bit will always be read zero. For compatibility with future devices, always set this bit to zero when writing to UCSRA.
• Bit 7 – RXC: USART Receive Complete:
This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). If the receiver is disabled, the receive buffer will be flushed and consequently the RXC bit will become zero. The RXC Flag can be used to generate a Receive Complete interrupt (see description of the RXCIE bit).
• Bit 6 – TXC: USART Transmit Complete:
This flag bit is set when the entire frame in the Transmit Shift Register has been shifted out and there are no new data currently present in the transmit buffer (UDR). The TXC Flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. The TXC Flag can generate a Transmit Complete interrupt (see description of the TXCIE bit).
• Bit 5 – UDRE: USART Data Register Empty:
The UDRE Flag indicates if the transmit buffer (UDR) is ready to receive new data. If UDRE is one, the buffer is empty, and therefore ready to be written. The UDRE Flag can generate a Data Register Empty interrupt (see description of the UDRIE bit). UDRE is set after a Reset to indicate that the transmitter is ready.
• Bit 4 – FE: Frame Error:
This bit is set if the next character in the receive buffer had a Frame Error when received. I.e., when the first stop bit of the next character in the receive buffer is zero. This bit is valid until the receive buffer (UDR) is read. The FE bit is zero when the stop bit of received data is one. Always set this bit to zero when writing to UCSRA.
• Bit 3 – DOR: Data Over Run:
This bit is set if a Data OverRun condition is detected. A data overrun occurs when the receive buffer is full (two characters), it is a new character waiting in the receive Shift Register, and a new start bit is detected. This bit is valid until the receive buffer (UDR) is read. Always set this bit to zero when writing to UCSRA.
• Bit 2 – UPE: Parity Error:
This bit is set if the next character in the receive buffer had a Parity Error when received
and the Parity Checking was enabled at that point (UPM1 = 1). This bit is valid until the
• Bit 1 – U2X: Double the USART Transmission Speed:
This bit only has effect for the asynchronous operation. Write this bit to zero when using synchronous operation. Writing this bit to one will reduce the divisor of the baud rate divider from 16 to 8 effectively doubling the transfer rate for asynchronous communication.
• Bit 0 – MPCM: Multi-processor Communication Mode:
This bit enables the Multi-processor Communication mode. When the MPCM bit is written to one, all the incoming frames received by the USART receiver that do not contain address information will be ignored. The transmitter is unaffected by the MPCM setting.
• Bit 7 – RXCIE: RX Complete Interrupt Enable:
Writing this bit to one enables interrupt on the RXC Flag. A USART Receive Complete interrupt will be generated only if the RXCIE bit is written to one, the Global Interrupt Flag in SREG is written to one and the RXC bit in UCSRA is set.
• Bit 6 – TXCIE: TX Complete Interrupt Enable:
Writing this bit to one enables interrupt on the TXC Flag. A USART Transmit Complete interrupt will be generated only if the TXCIE bit is written to one, the Global Interrupt Flag in SREG is written to one and the TXC bit in UCSRA is set.
• Bit 5 – UDRIE: USART Data Register Empty Interrupt Enable:
Writing this bit to one enables interrupt on the UDRE Flag. A Data Register Empty interrupt will be generated only if the UDRIE bit is written to one, the Global Interrupt Flag in SREG is written to one and the UDRE bit in UCSRA is set.
• Bit 4 – RXEN: Receiver Enable:
Writing this bit to one enables the USART Receiver. The Receiver will override normal port operation for the RxD pin when enabled. Disabling the Receiver will flush the receive buffer invalidating the FE, DOR and UPE Flags.
• Bit 3 – TXEN: Transmitter Enable:
Writing this bit to one enables the USART Transmitter. The Transmitter will override normal port operation for the TxD pin when enabled. The disabling of the Transmitter (writing TXEN to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the Transmit Shift Register and Transmit Buffer Register do not contain data to be transmitted. When disabled, the Transmitter will no longer override the TxD port.
• Bit 2 – UCSZ2: Character Size:
The UCSZ2 bits combined with the UCSZ1:0 bit in UCSRC sets the number of data bits (character size) in a frame the Receiver and Transmitter use.
• Bit 1 – RXB8: Receive Data Bit 8:
RXB8 is the ninth data bit of the received character when operating with serial frames with nine data bits. Must be read before reading the low bits from UDR.
• Bit 0 – TXB8: Transmit Data Bit 8:
TXB8 is the 9th data bit in the character to be transmitted when operating with serial frames with 9 data bits. Must be written before writing the low bits to UDR.
• Bit 7 – URSEL: Register Select:
This bit selects between accessing the UCSRC or the UBRRH Register. It is read as one when reading UCSRC. The URSEL must be one when writing the UCSRC.
• Bit 6 – UMSEL: USART Mode Select:
This bit selects between asynchronous and synchronous mode of operation.
• Bit 5:4 – UPM1:0: Parity Mode:
These bits enable and set type of parity generation and check. If enabled, the transmitter will automatically generate and send the parity of the transmitted data bits within each frame. The receiver will generate a parity value for the incoming data and compare it to the UPM0 setting. If a mismatch is detected, the UPE Flag in UCSRA will be set.
• Bit 3 – USBS: Stop Bit Select:
This bit selects the number of stop bits to be inserted by the transmitter. The receiver ignores this setting.
• Bit 2:1 – UCSZ1:0: Character Size:
The UCSZ1:0 bits combined with the UCSZ2 bit in UCSRB sets the number of data bits (Character Size) in a frame the receiver and transmitter use.
• Bit 0 – UCPOL: Clock Polarity
This bit is used for synchronous mode only. Write this bit to zero when asynchronous mode is used. The UCPOL bit sets the relationship between data output change and data input sample, and the synchronous clock (XCK).
The baud rate generator:
The USART Baud Rate Register (UBRR) and the down-counter connected to it function as a programmable prescaler or baud rate generator. The down-counter, running at system clock (fosc), is loaded with the UBRR value each time the counter has counted down to zero or when the UBRRL Register is written. A clock is generated each time the counter reaches zero. This clock is the baud rate generator clock output (= fosc/(UBRR+1)). The Transmitter divides the baud rate generator clock output by 2, 8 or 16 depending on mode. The baud rate generator output is used directly by the receiver’s clock and data recovery units. However, the recovery units use a state machine that uses 2, 8 or 16 states depending on mode set by the state of the UMSEL, U2X and DDR_XCK bits.
Table contains equations for calculating the baud rate (in bits per second) and for calculating the UBRR value for each mode of operation using an internally generated
Table Equations for setting baud rate register settings:
Note: 1. The baud rate is defined to be the transfer rate in bit per second (bps).
BAUD: Baud rate (in bits per second, bps)
fOSC: System Oscillator clock frequency
UBRR: Contents of the UBRRH and UBRRL Registers, (0 - 4095)
Double Speed Operation (U2X):
The transfer rate can be doubled by setting the U2X bit in UCSRA. Setting this bit only has effect for the asynchronous operation. Set this bit to zero when using synchronous operation.
Setting this bit will reduce the divisor of the baud rate divider from 16 to 8, effectively doubling the transfer rate for asynchronous communication. Note however that the Receiver will in this case only use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery, and therefore a more accurate baud rate setting and system clock are required when this mode is used. For the Transmitter, there are no downsides.
INTERRUPTS
Interrupts are those which create some disturbance in between the program. We have interrupt flag in status register, this is nothing but the master bit which acts as the master to the remaining interrupts i.e., any interrupt is needed in the program, then first set this master interrupt bit and only then remaining interrupts can be accepted.
8-bit Timer/Counter Register Description:
Timer/Counter Control Register – TCCR0:
In this register we use only 3 bits they are CS00, CS01, CS02 and the remaining bits are not used.
• Bit 2:0 – CS02:0: Clock Select
The three Clock Select bits select the clock source to be used by the Timer/Counter.
If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the counter even if the pin is configured as an output. This feature allows software control of the counting.
Timer/Counter Register –TCNT0:
The Timer/Counter Register gives direct access, both for read and write operations, to the Timer/Counter unit 8-bit counter. Writing to the TCNT0 Register blocks (removes) the Compare Match on the following timer clock. Modifying the counter (TCNT0) while the counter is running, introduces a risk of missing a Compare Match between TCNT0 and the OCR0 Register.
Timer/Counter Interrupt Mask Register – TIMSK:
• Bit 1 – TOIE0: Timer/Counter0 Overflow Interrupt Enable:
When the TOIE0 bit is written to one, and the I-bit in the Status Register is set (one), the Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter0 occurs, i.e., when the TOV0 bit is set in the Timer/Counter Interrupt Flag Register – TIFR.
• Bit 0 – OCIE0: Timer/Counter0 Output Compare Match Interrupt Enable
When the OCIE0 bit is written to one, and the I-bit in the Status Register is set (one), the Timer/Counter0 Compare Match interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter0 occurs, i.e., when the OCF0 bit is set in the Timer/Counter Interrupt Flag Register – TIFR.
Timer/Counter Interrupt Flag Register – TIFR:
• Bit 1 – TOV0: Timer/Counter0 Overflow Flag:
The bit TOV0 is set (one) when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE0 (Timer/Counter0 Overflow Interrupt Enable), and TOV0 are set (one), the Timer/Counter0 Overflow interrupt is executed. In phase correct PWM mode, this bit is set when Timer/Counter0 changes counting direction at $00.
• Bit 0 – OCF0: Output Compare Flag 0:
The OCF0 bit is set (one) when a Compare Match occurs between the Timer/Counter0 and the data in OCR0 – Output Compare Register0. OCF0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF0 is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE0 (Timer/Counter0 Compare Match Interrupt Enable), and OCF0 are set (one), the Timer/Counter0 Compare Match Interrupt is executed.
16bit Timer/Counter register description
Timer/Counter1 Control Register A – TCCR1A
• Bit 7:6 – COM1A1:0: Compare Output Mode for Channel A
• Bit 5:4 – COM1B1:0: Compare Output Mode for Channel B
The COM1A1:0 and COM1B1:0 control the Output Compare pins (OC1A and OC1B respectively) behavior. If one or both of the COM1A1:0 bits are written to one, the OC1A output overrides the normal port functionality of the I/O pin it is connected to. If one or both of the COM1B1:0 bit are written to one, the OC1B output overrides the normal port functionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding to the OC1A or OC1B pin must be set in order to enable the output driver.
When the OC1A or OC1B is connected to the pin, the function of the COM1x1:0 bits is dependent of the WGM13:0 bits setting. Table 50 shows the COM1x1:0 bit functionality when the WGM13:0 bits are set to a normal or a CTC mode (non-PWM).
Compare Output mode - non PWM
Compare Output mode – fast PWM
Compare Output Mode, Phase Correct and Phase and Frequency Correct PWM
Note: 1. A special case occurs when OCR1A/OCR1B equals TOP and COM1A1/COM1B1 is set. We should know about “Phase Correct PWM Mode” for more details.
• Bit 3 – FOC1A: Force Output Compare for Channel A
• Bit 2 – FOC1B: Force Output Compare for Channel B
The FOC1A/FOC1B bits are only active when the WGM13:0 bits specifies a non-PWM
mode. However, for ensuring compatibility with future devices, these bits must be set to
zero when TCCR1A is written when operating in a PWM mode. When writing a logical
one to the FOC1A/FOC1B bit, an immediate Compare Match is forced on the waveform
generation unit. The OC1A/OC1B output is changed according to its COM1x1:0 bits setting.
Note that the FOC1A/FOC1B bits are implemented as strobes. Therefore it is the
value present in the COM1x1:0 bits that determine the effect of the forced compare.
A FOC1A/FOC1B strobe will not generate any interrupt nor will it clear the timer in Clear
Timer on Compare Match (CTC) mode using OCR1A as TOP.
The FOC1A/FOC1B bits are always read as zero.
• Bit 1:0 – WGM11:0: Waveform Generation Mode
Combined with the WGM13:2 bits found in the TCCR1B Register, these bits control the
counting sequence of the counter, the source for maximum (TOP) counter value, and
what type of waveform generation to be used. Modes of operation supported by the Timer/Counter unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) mode, and three types of Pulse Width Modulation (PWM) modes.
Waveform generation mode bit description:-
Timer/Counter1 control Register B:
• Bit 7 – ICNC1: Input Capture Noise Canceler
• Bit 6 – ICES1: Input Capture Edge Select
• Bit 5: Reserved Bit
• Bit 4:3 – WGM13:2: Waveform Generation Mode
• Bit 2:0 – CS12:0: Clock Select
Timer/counter1-TCNT1H and TCNT1L:
The two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give
direct access, both for read and for write operations, to the Timer/Counter unit 16-bit
counter. To ensure that both the high and low bytes are read and written simultaneously
when the CPU accesses these registers, the access is performed using an 8-bit temporary
High Byte Register (TEMP). This temporary register is shared by all the other 16-bit
registers. See “Accessing 16-bit Registers” on page 99.
Modifying the counter (TCNT1) while the counter is running introduces a risk of missing
a Compare Match between TCNT1 and one of the OCR1x Registers.
Writing to the TCNT1 Register blocks (removes) the Compare Match on the following
timer clock for all compare units.
Output Compare Register 1 A – OCR1AH and OCR1AL
Output Compare Register 1 B – OCR1BH and OCR1BL
The Output Compare Registers contain a 16-bit value that is continuously compared
with the counter value (TCNT1). A match can be used to generate an output compare
interrupt, or to generate a waveform output on the OC1x pin. The Output Compare Registers are 16-bit in size. To ensure that both the high and low bytes are written simultaneously when the CPU writes to these registers, the access is performed using an 8-bit temporary High Byte Register (TEMP). This temporary register is shared by all the other 16-bit registers.









































































