avr+lcd report

  • Upload
    yrikki

  • View
    22

  • Download
    0

Embed Size (px)

DESCRIPTION

atmega 16 with LCD report

Citation preview

BLOCK DIAGRAM

CHAPTER-1

INTRODUCTION

Controller Area Network (CAN) was initially created by German automotive system supplier Robert Bosch in the mid-1980s for automotive applications as a method for enabling robust serial communication. The goal was to make automobiles more reliable, safe and fuel-efficient while decreasing wiring harness weight and complexity. Since its inception, the CAN protocol has gained widespread popularity in industrial automation and automotive/truck applications. Other markets where networked solutions can bring attractive benefits like medical equipment, test equipment and mobile machines are also starting to utilize the benefits of CAN. The goal of this application note is to explain some of the basics of CAN and show the benefits of choosing CAN for embedded systems networked applications.

The Controller Area Network (the CAN bus) is a serial communications bus for real-time control applications; operates at data rates of up to 1 Megabits per second, and has excellent error detection and confinement capabilities. CAN was originally developed by the German company, Robert Bosch, for use in cars, to provide a cost-effective communications bus for in-car electronics and as alternative to expensive, cumbersome and unreliable wiring looms and connectors. The car industry continues to use CAN for an increasing number of applications, but because of its proven reliability and robustness, CAN is now also being used in many other control applications.

CAN is an international standard and is documented in ISO 11898 (for high-speed applications) and ISO 11519 (for lower-speed applications).

In this application CAN uses multiple transmitter nodes to acquire data from sensors and transmit the data in packets over a CAN bus. Each transmitter consists of an AT Mega32 micro controller. The CAN packets are received by a single receiver node and display messages on the GLCD display unit.

CHAPTER-2

POWER SUPPLYAn AC powered linear power supply usually uses a transformer to convert the voltage from the wall outlet (mains) to a different, usually a lower voltage. If it is used to produce DC, a rectifier is used. A capacitor is used to smooth the pulsating current from the rectifier. Some small periodic deviations from smooth direct current will remain, which is known as ripple. These pulsations occur at a frequency related to the AC power frequency (for example, a multiple of 50 or 60 Hz).

The voltage produced by an unregulated power supply will vary depending on the load and on variations in the AC supply voltage. For critical electronics applications a linear regulator will be used to stabilize and adjust the voltage. This regulator will also greatly reduce the ripple and noise in the output direct current. Linear regulators often provide current limiting, protecting the power supply and attached circuit from overcurrent.

Adjustable linear power supplies are common laboratory and service shop test equipment, allowing the output voltage to be set over a wide range. For example, a bench power supply used by circuit designers may be adjustable up to 30 volts and up to 5 amperes output. Some can be driven by an external signal, for example, for applications requiring a pulsed output.

The simplest DC power supply circuit consists of a single diode and resistor in series with the AC supply. This circuit is common in rechargeable flashlights.

The power supply we get from the supply is 230V AC supply. But here we need 5V/12V DC power supply.So we have to convert it to 5V DC supply.For this purpose we use step down transformer,rectifier,regulator and filter circuits.The step down transformer here we are using is 230V-12V which is operated at 50Hz. And the rectifier we are using is full wave bridge rectifier by using 1N4007 diodes.The regulator we are using is 7805/7812. For the filtering purpose we are using capacitor as a filter.

CHAPTER-3

AVR MICROCONTROLLER

3.1OVRVIEWThe ATmega32 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 ATmega32 achieves throughputs approaching 1 MIPS per MHz allowing the system designer to optimize power consumption versus processing speed.

3.2Features

High-performance, Low-power AVR 8-bit Microcontroller

Advanced RISC Architecture

131 Powerful Instructions Most Single-clock Cycle Execution

32 x 8 General Purpose Working Registers

Fully Static Operation

Up to 16 MIPS Throughput at 16 MHz

On-chip 2-cycle Multiplier

High Endurance Non-volatile Memory segments

32K Bytes of In-System Self-programmable Flash program memory

1024 Bytes EEPROM

2K Byte Internal SRAM

Write/Erase Cycles: 10,000 Flash/100,000 EEPROM

Data retention: 20 years at 85C/100 years at 25C(1)

Optional Boot Code Section with Independent Lock Bits In-System Programming by On-chip Boot Program True Read-While-Write Operation

Programming Lock for Software Security

JTAG (IEEE std. 1149.1 Compliant) Interface

Boundary-scan Capabilities According to the JTAG Standard

Extensive On-chip Debug Support

Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface

Peripheral Features

Two 8-bit Timer/Counters with Separate Prescalers and Compare Modes

One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode

Real Time Counter with Separate Oscillator

Four PWM Channels

8-channel, 10-bit ADC 8 Single-ended Channels 7 Differential Channels in TQFP Package Only 2 Differential Channels with Programmable Gain at 1x, 10x, or 200x

Byte-oriented Two-wire Serial Interface

Programmable Serial USART

Master/Slave SPI Serial Interface

Programmable Watchdog Timer with Separate On-chip Oscillator

On-chip Analog Comparator

Special Microcontroller Features

Power-on Reset and Programmable Brown-out Detection

Internal Calibrated RC Oscillator

External and Internal Interrupt Sources

Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby and Extended Standby

I/O and Packages

32 Programmable I/O Lines

40-pin PDIP, 44-lead TQFP, and 44-pad QFN/MLF

Operating Voltages

2.7 - 5.5V for ATmega32L

4.5 - 5.5V for ATmega32

Speed Grades

0 - 8 MHz for ATmega32L

0 - 16 MHz for ATmega32

Power Consumption at 1 MHz, 3V, 25C for ATmega32L

Active: 1.1 mA

Idle Mode: 0.35 mA

Power-down Mode: < 1 A3.3Pin Configurations

Pin DescriptionsVCC Digital supply voltage.

GND Ground.

Port A (PA7..PA0) Port A serves as the analog inputs to the A/D Converter.Port A also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used. Port pins can provide internal pull-up resistors (selected for each bit). The Port A output buffers have symmetrical drive characteristics with both high sink and source capability. 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 running.

Port B (PB7..PB0) Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers have symmetrical drive characteristics with both high sink and source capability. 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 running.Port C (PC7..PC0) Port C is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port C output buffers have symmetrical drive characteristics with both high sink and source capability. 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 running. If the JTAG interface is enabled, the pull-up resistors on pins PC5(TDI), PC3(TMS) and PC2(TCK) will be activated even if a reset occurs.The TD0 pin is tri-stated unless TAP states that shift out data are entered. Port C also serves the functions of the JTAG interface and other special features of the ATmega32.Port D (PD7..PD0) Port D is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port D output buffers have symmetrical drive characteristics with both high sink and source capability. 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 running.RESET Reset Input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not running.

XTAL1 Input to the inverting Oscillator amplifier and input to the internal clock operating circuit.XTAL2 Output from the inverting Oscillator amplifier.AVCC AVCC is the supply voltage pin for Port A and the A/D Converter. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter.

AREF AREF is the analog reference pin for the A/D Converter.

3.4MCU Control Register MCUCR

The MCU Control Register contains control bits for power management.

Bit 7 SE: Sleep Enable

The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmers purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up.

Bits 6...4 SM2..0: Sleep Mode Select Bits 2, 1, and 0 .These bits select between the six available sleep modes as shown in below Table .

Idle Mode

When the SM2..0 bits are written to 000, the SLEEP instruction makes the MCU enter Idle mode, stopping the CPU but allowing SPI, USART, Analog Comparator, ADC, Two-wire Serial Interface, Timer/Counters, Watchdog, and the interrupt system to continue operating. This sleep mode basically halts clkCPU and clkFLASH, while allowing the other clocks to run. Idle mode enables the MCU to wake up from external triggered interrupts as well as internal ones like the Timer Overflow and USART Transmit Complete interrupts. If wake-up from the Analog Comparator interrupt is not required, the Analog Comparator can be powered down by setting the ACD bit in the Analog Comparator Control and Status Register ACSR. This will reduce power consumption in Idle mode. If the ADC is enabled, a conversion starts automatically when this mode is entered.ADC Noise Reduction Mode

When the SM2..0 bits are written to 001, the SLEEP instruction makes the MCU enter ADC Noise Reduction mode, stopping the CPU but allowing the ADC, the External Interrupts, the Two-wire Serial Interface address watch, Timer/Counter2 and the Watchdog to continue operating (if enabled). This sleep mode basically halts clkI/O, clkCPU, and clkFLASH, while allowing the other clocks to run.

This improves the noise environment for the ADC, enabling higher resolution measurements. If the ADC is enabled, a conversion starts automatically when this mode is entered. Apart form the ADC Conversion Complete interrupt, only an External Reset, a Watchdog Reset, a Brown-out Reset, a Two-wire Serial Interface Address Match Interrupt, a Timer/Counter2 interrupt, an SPM/EEPROM ready interrupt, an External level interrupt on INT0 or INT1, or an external interrupt on INT2 can wake up the MCU from ADC Noise Reduction mode.Power-down Mode When the SM2..0 bits are written to 010, the SLEEP instruction makes the MCU enter Power-down mode. In this mode, the External Oscillator is stopped, while the External interrupts, the Two-wire Serial Interface address watch, and the Watchdog continue operating (if enabled).Only an External Reset, a Watchdog Reset, a Brown-out Reset, a Two-wire Serial Interface address match interrupt, an External level interrupt on INT0 or INT1, or an External interrupt on INT2 can wake up the MCU. This sleep mode basically halts all generated clocks, allowing operation of asynchronous modules only.

Note that if a level triggered interrupt is used for wake-up from Power-down mode, the changed level must be held for some time to wake up the MCU.

When waking up from Power-down mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. This allows the clock to restart and become stable after having been stopped. The wake-up period is defined by the same CKSEL fuses that define the reset time-out period.

Power-save Mode When the SM2..0 bits are written to 011, the SLEEP instruction makes the MCU enter Power-save mode. This mode is identical to Power-down, with one exception:If Timer/Counter2 is clocked asynchronously, i.e., the AS2 bit in ASSR is set, Timer/Counter2 will run during sleep. The device can wake up from either Timer Overflow or Output Compare event from Timer/Counter2 if the corresponding Timer/Counter2 interrupt enable bits are set in TIMSK, and the Global Interrupt Enable bit in SREG is set.

If the Asynchronous Timer is NOT clocked asynchronously, Power-down mode is recommended instead of Power-save mode because the contents of the registers in the Asynchronous Timer should be considered undefined after wake-up in Power-save mode if AS2 is 0.

This sleep mode basically halts all clocks except clkASY, allowing operation only of asynchronous modules, including Timer/Counter2 if clocked asynchronously.Standby Mode When the SM2..0 bits are 110 and an external crystal/resonator clock option is selected, the SLEEP instruction makes the MCU enter Standby mode. This mode is identical to Power-down with the exception that the Oscillator is kept running. From Standby mode, the device wakes up in six clock cycles.Extended Standby Mode

When the SM2..0 bits are 111 and an external crystal/resonator clock option is selected, the SLEEP instruction makes the MCU enter Extended Standby mode. This mode is identical to Power-save mode with the exception that the Oscillator is kept running. From Extended Standby mode, the device wakes up in six clock cycles..

Minimizing Power Consumption

There are several issues to consider when trying to minimize the power consumption in an AVR controlled system. In general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as few as possible of the devices functions are operating. All functions not needed should be disabled. In particular, the following modules may need special consideration when trying to achieve the lowest possible power consumption.

Analog to Digital Converter

If enabled, the ADC will be enabled in all sleep modes. To save power, the ADC should be dis-abled before entering any sleep mode. When the ADC is turned off and on again, the next conversion will be an extended conversion. Analog Comparator When entering Idle mode, the Analog Comparator should be disabled if not used. When entering ADC Noise Reduction mode, the Analog Comparator should be disabled. In the other sleep modes, the Analog Comparator is automatically disabled. However, if the Analog Comparator is set up to use the Internal Voltage Reference as input, the Analog Comparator should be disabled in all sleep modes. Otherwise, the Internal Voltage Reference will be enabled,independent of sleep mode. Refer to Analog Comparator on page 198 for details on how to configure the Analog Comparator.

Brown-out Detector If the Brown-out Detector is not needed in the application, this module should be turned off. If the Brown-out Detector is enabled by the BODEN Fuse, it will be enabled in all sleep modes, and hence, always consume power. In the deeper sleep modes, this will contribute significantly to the total current consumption. Refer to Brown-out Detection on page 39 for details on how to configure the Brown-out Detector.

Internal Voltage Reference

The Internal Voltage Reference will be enabled when needed by the Brown-out Detector, the Analog Comparator or the ADC. If these modules are disabled as described in the sections above, the internal voltage reference will be disabled and it will not be consuming power. When turned on again, the user must allow the reference to start up before the output is used. If the reference is kept on in sleep mode, the output can be used immediately. Refer to Internal Volt- age Reference on page 41 for details on the start-up time.

Watchdog Timer If the Watchdog Timer is not needed in the application, this module should be turned off. If the Watchdog Timer is enabled, it will be enabled in all sleep modes, and hence, always consume power. In the deeper sleep modes, this will contribute significantly to the total current consump-tion. Refer to Watchdog Timer on page 41 for details on how to configure the Watchdog Timer.Port Pins When entering a sleep mode, all port pins should be configured to use minimum power. The most important thing is then to ensure that no pins drive resistive loads. In sleep modes where the both the I/O clock (clkI/O) and the ADC clock (clkADC) are stopped, the input buffers of the device will be disabled. This ensures that no power is consumed by the input logic when not needed. In some cases, the input logic is needed for detecting wake-up conditions, and it will then be enabled. If the input buffer is enabled and the input signal is left floating or have an analog signal level close to VCC/2, the input buffer will use excessive power.

JTAG Interface and On-chip Debug System

If the On-chip debug system is enabled by the OCDEN Fuse and the chip enter Power down or Power save sleep mode, the main clock source remains enabled. In these sleep modes, this will contribute significantly to the total current consumption. There are three alternative ways to avoid this:

Disable OCDEN Fuse.

Disable JTAGEN Fuse.

Write one to the JTD bit in MCUCSR.

The TDO pin is left floating when the JTAG interface is enabled while the JTAG TAP controller is not shifting data. If the hardware connected to the TDO pin does not pull up the logic level, power consumption will increase. Note that the TDI pin for the next device in the scan chain contains a pull-up that avoids this problem. Writing the JTD bit in the MCUCSR register to one or leaving the JTAG fuse unprogrammed disables the JTAG interface.

CHAPTER-4

CONTROLLER AREA NETWORK4.1INTRODUCTION

Controller Area Network (CAN) was initially created by German automotive system supplier Robert Bosch in the mid-1980s for automotive applications as a method for enabling robust serial communication. The goal was to make automobiles more reliable, safe and fuel-efficient while decreasing wiring harness weight and complexity. Since its inception, the CAN protocol has gained widespread popularity in industrial automation and automotive/truck applications. Other markets where networked solutions can bring attractive benefits like medical equipment, test equipment and mobile machines are also starting to utilize the benefits of CAN. The goal of this application note is to explain some of the basics of CAN and show the benefits of choosing

CAN for embedded systems networked applications.The Controller Area Network (the CAN bus) is a serial communications bus for real-time control applications; operates at data rates of up to 1 Megabits per second, and has excellent error detection and confinement capabilities. CAN was originally developed by the German company, Robert Bosch, for use in cars, to provide a cost-effective communications bus for in-car electronics and as alternative to expensive, cumbersome and unreliable wiring looms and connectors. The car industry continues to use CAN for an increasing number of applications, but because of its proven reliability and robustness, CAN is now also being used in many other control applications.

CAN is an international standard and is documented in ISO 11898 (for high-speed applications) and ISO 11519 (for lower-speed applications).

Low-cost CAN controllers and interface devices are available as off-the-shelf components from several of the leading semiconductor manufacturers. Custom built devices and popular microcontrollers with embedded CAN controllers are also available. There are many CAN-related system development packages, hardware interface cards and easy-to-use software packages that provide system designers, builders and maintainers with a wide range of design, monitoring, analysis, and test tools.What is CAN?CAN or Controller Area Network is a robust industrial strength hardware and software protocol used to communicate between microcontrollers. It is very popular in modern automotive applications and is gaining popularity in industrial and home automation applications.

How CAN works

Principle

Data messages transmitted from any node on a CAN bus do not contain addresses of either the transmitting node, or of any intended receiving node.Instead, the content of the message (e.g. Revolutions Per Minute, Hopper Full, X-ray Dosage, etc.) is labeled by an identifier that is unique throughout the network. All other nodes on the network receive the message and each performs an acceptance test on the identifier to determine if the message, and thus its content, is relevant to that particular node.If the message is relevant, it will be processed; otherwise it is ignored. The unique identifier also determines the priority of the message. The lower the numerical value of the identifier, the higher the priority.

In situations where two or more nodes attempt to transmit at the same time, a non-destructive arbitration technique guarantees that messages are sent in order of priority and that no messages are lost.

Bit encoding

CAN uses Non Return to Zero (NRZ) encoding (with bit-stuffing) for data communication on a differential two wire bus. The use of NRZ encoding ensures compact messages with a minimum number of transitions and high resilience to external disturbance.The physical busThe two wire bus is usually a twisted pair (shielded or unshielded). Flat pair (telephone type) cable also performs well but generates more noise itself, and may be more susceptible to external sources of noise.

Robustness

CAN will operate in extremely harsh environments and the extensive error checking mechanisms ensure that any transmission errors are detected. See the 'Error Handling' section of this site for more details.

The ISO11898 standard "Recommends" that bus interface chips be designed so that communication can still continue (but with reduced signal to noise ratio) even if:

- Either of the two wires in the bus is broken- Either wire is shorted to power- Either wire is shorted to ground

Network Flexibility and Expansion

The content-oriented nature of the CAN messaging scheme delivers a high degree of flexibility for system configuration.New nodes that are purely receivers, and which need only existing transmitted data, can be added to the network without the need to make any changes to existing hardware or software.Measurements needed by several controllers can be transmitted via the bus, thereby removing the need for each controller to have its own individual sensor

How Arbitration Works on the CAN Bus

In any system, some parameters will change more rapidly than others. For example - parameters that change quickly could be the RPM of a car engine, or the current floor level of an elevator (US) - lift (UK). Slower changing parameters may be the temperature of the coolant of a car engine.It is likely that the more rapidly changing parameters need to be transmitted more frequently and, therefore, must be given a higher priority.To determine the priority of messages, CAN uses the established method known as Carrier Sense, Multiple Access with Collision Detect (CSMA/CD) but with the enhanced capability of non-destructive bitwise arbitration to provide collision resolution, and to deliver maximum use of the available capacity of the bus.

Non-Destructive Bitwise Arbitration

The priority of a CAN message is determined by the numerical value of its identifier.The numerical value of each message identifier (and thus the priority of the message) is assigned during the initial phase of system design.The identifier with the lowest numerical value has the highest priority. Any potential bus conflicts are resolved by bitwise arbitration in accordance with the wired-and mechanism, by which a dominant state (logic 0) overwrites a recessive state (logic 1).4.2Higher layer implementationsAs the CAN standard does not include tasks of application layer protocols, such asflow control, device addressing, and transportation of data blocks larger than one message, many implementations of higher layer protocols were created. Among these areDeviceNet,CANopen,SDS (Smart Distributed System),CANaerospace,J1939, SmartCraft,NMEA 2000,CAN Kingdom,SafetyBUS p,EnergyBusandMilCAN.

AnARINCtechnical working group develops theARINC 825standard with special requirements for the aviation industry.

.

Block Diagram4.3Types of CANThere are two types of CAN implementations depending in the size of the identifier field.

1) STANDARD: 11-bit wide identifier field.2) EXTENDED: 29-bit wide identifier field.The Standard CAN protocol (version 2.0A), also now known as Base Frame Format, supports messages with 11 bit identifiers.The Extended CAN protocol (version 2.0B), also now known as Extended Frame Format, supports both 11 bit and 29 bit identifiers.

Most 2.0A controllers transmit and receive only Standard format messages, although some (known as 2.0B passive) will receive Extended format messages - but then ignore them. 2.0B controllers can send and receive messages in both formats.

2.0A Format

A Standard CAN (Version 2.0A) Message Frame consists of seven different bit fields: A Start of Frame (SOF) field - which indicates the beginning of a message frame.

An Arbitration field, containing a message identifier and the Remote Transmission Request (RTR) bit. The RTR bit is used to discriminate between a transmitted Data Frame and a request for data from a remote node.

Message Frame

A Control Field containing six bits:* two reserved bits (r0 and r1) and* a four bit Data Length Code (DLC). The DLC indicates the number of bytes in the Data Field that follows A Data Field, containing from zero to eight bytes.

The CRC field, containing a fifteen bit cyclic redundancy check code and a recessive delimiter bit

The ACKnowledge field, consisting of two bits. The first is the Slot bit which is transmitted as recessive, but is subsequently over written by dominant bits transmitted from any node that successfully receives the transmitted message. The second bit is a recessive delimiter bit

The End of Frame field, consisting of seven recessive bits.

Following the End Of Frame is the INTermission field consisting of three recessive bits.After the three bit INTermission period the bus is recognised to be free. Bus Idle time maybe of any arbitrary length including zero.

2.0B Format

The CAN 2.0B format provides a twenty nine (29) bit identifier as opposed to the 11 bit identifier in 2.0A.Version 2.0B evolved to provide compatibility with other serial communications protocols used in automotive applications in the USA. To cater for this, and still provide compatibility with the 2.0A format, the Message Frame in Version 2.0B has an extended format.The differences are:

In Version 2.0B the Arbitration field contains two identifier bit fields. The first (the base ID) is eleven (11) bits long for compatibility with Version 2.0A. The second field (the ID extension) is eighteen (18) bits long, to give a total length of twenty nine (29) bits.

The distinction between the two formats is made using an Identifier Extension (IDE) bit.

A Substitute Remote Request (SRR) bit is also included in the Arbitration Field. The SRR bit is always transmitted as a recessive bit to ensure that, in the case of arbitration between a Standard Data Frame and an Extended Data Frame, the Standard Data Frame will always have priority if both messages have the same base (11 bit) identifier.

All other fields in a 2.0B Message Frame are identical to those in the Standard format.

2.0A and 2.0B Compatibility

2.0B controllers are completely backward compatible with 2.0A controllers and can transmit and receive messages in either format.Note, however, that there are two types of 2.0A controllers: The first is capable of transmitting and receiving only messages in 2.0A format. With this type of controller, reception of any 2.0B message will flag an error.

The second (known as 2.0B passive) is capable of sending and receiving 2.0A messages. They will also acknowledge receipt of 2.0B messages - but then ignore them.

Therefore, within the above mentioned constraints it is possible to use both Version 2.0A (with 2.0B passive capabilities) and 2.0B controllers on a single network.

The number of unique identifiers available to users, on a single 2.0A network, is 2,032 (2 to the power 11 - 2 to the power 4).

Leaving aside the use for compatibility purposes with American buses, the number of unique identifiers available on a 2.0B network is in excess of 500 million!StandardCommon NameBaud RateMax nodesMax LengthAdapter forPCAN interfaces

ISO 11783ISOBUS250 KBit/s3040mNone

ISO 11898-2High speed-CANmax. 1 MBit/s1106500 mNone

ISO 11898-3Fault Tolerant CANmax. 125 KBit/s32500 mPCAN TJA1054

ISO 11992FMS or Truck/Trailer CANmax. 125 KBit/s2 (Point to Point)40 mPCAN-BD10011S

ISO 15765Diagnostics On CANmax 1 MBit/s110

SAE J1939250 KBit/s3040m

SAE J2284max. 1 MBit/s110

SAE J2411Single Wire CAN33,3 KBit/s

83,3KBit/s in HSMode32PCAN-AU579

4.4Implementations of CAN

Communication is identical for all implementations of CAN. However, there are two principal hardware implementations.The two implementation are known as Basic CAN and Full CAN.The terms Basic CAN and Full CAN must not be confused with the terms Standard CAN - also known as Base Frame Format (11 bit identifier, Version 2.0A data format) and Extended CAN - also known as Extended Frame Format(29 bit identifier, or Version 2.0B data format). Suitably configured, each implementation (Basic or Full CAN) can handle both Base and Extended data formats.Basic CANIn Basic CAN configurations there is a tight link between the CAN controller and the associated microcontroller. The microcontroller, which will have other system related functions to administer, will be interrupted to deal with every CAN message.Full CANFull CAN devices contain additional hardware to provide a message "server" that automatically receives and transmits CAN messages without interrupting the associated microcontroller. Full CAN devices carry out extensive acceptance filtering on incoming messages, service simultaneous requests, and generally reduce the load on the microcontroller.Network SizesThe number of nodes that can exist on a single network is, theoretically, limited only by the number of available identifiers. However, the drive capabilities of currently available devices imposes greater restrictions. Depending on the device types, up to 32 or 64 nodes per network is normal, but at least one manufacturer now provides devices that will allow networks of 110 nodes.Data Rate vs Bus LengthThe rate of data transmission depends on the total overall length of the bus and the delays associated with the transceivers. For all ISO11898 compliant devices running at 1Mbit/sec speed, the maximum possible bus length is specified as 40 Metres, For longer bus lengths it is necessary to reduce the bit rate. To give some indication of this the following numbers are from the DeviceNet features list: 500 K bits per second at 100 metres (328 ft)

250 K bits per second at 200 metres (656 ft)

125 K bits per second at 500 metres (1640 ft) Signal Characteristics

CAN may be implemented over a number of physical media so long as the drivers are open-collector and each node can hear itself and others while transmitting (this is necessary for its message priority and error handling mechanisms). The most common media is a twisted pair 5v differential signal which will allow operations in high noise environments and with the right drivers will work even if one of the wires is open circuit.A number of transceiver chips are available the most popular probably being the Philips 82C251 as well as the TJA1040.

When running Full CAN (ISO 11898-2) at its higher speeds it is necessary to terminate the bus at both ends with 120 Ohms. The resistors are not only there to prevent reflections but also to unload the open collector transceiver drivers.

4.5The OSI model

ISO7498 defines a communications standard known as the Open Systems Interconnection (OSI) model. This model describes how communications should occur between computers on any network, and has been adopted as a general "open" network communication standard. In principle - anything that conforms to the standard can communicate, electronically, with anything else that conforms to the standard.The OSI model defines seven independent "layers" of a protocol stack. Strict compliance with the standard requires that each layer is insulated from the others by well-defined interfaces. Few, if any, networks comply absolutely with the OSI model with regard to provision of all seven layers as distinct entities. Fig . The Seven Layer OSI model

.CAN and the OSI ModelThe CAN specification (ISO11898) discusses only the Physical and Data-Link layers for a CAN network.

The Data-Link Layer - is the only layer that recognises and understands the format of messages. This layer constructs the messages to be sent to the Physical Layer, and decodes messages received from the Physical Layer. In CAN controllers, the Data-Link Layer is usually implemented in hardware.

The Physical Layer - specifies the physical and electrical characteristics of the bus, and of the hardware that converts the characters of a message into electrical signals for transmitted messages - and electrical signals into characters for received messages. Although the other layersmaybe implemented in either hardware (as chip level functions) or software, the Physical Layer is always "real" hardware.

CAN Applications Layers

Many applications of CAN require services that are beyond the basic functionality specified by the Data-Link Layer but which may be implemented at the Application Layer. For example, the transmission or reception of data units longer than eight bytes. To meet this need several organisations have developed Application Layers. Brief details about just a few of them and contact details are given below.CAL (CAN Application Layer)

Aptly named, and based on an existing and proven protocol originally developed by Philips Medical Systems, CAL is an application-independent application layer that has been specified and is now maintained by the CAN in Automation (CiA) user group. Anyone who implements CAL may do so free of any licence royalty. The CAL specification (document reference CiA DS-201...207) may be purchased from CiA. Logical Link Control (LLC)

Acceptance Filtering

Overload Notification

Recovery Management

Medium Access Control (MAC)

Data Encapsulation/Decapsulation

Frame Coding (Stuffing/Destuffing)]

Error Detection/Signalling

Serialization/Deserialization

Physical Signaling (PLS)

Bit Encoding/Decoding

Bit Timing/Synchronization

Physical Medium Attachment (PMA)

Driver/Receiver Characteristics

Medium Dependent Interface (MDI)

Connectors

CANopen

CANopen is an implementation of CAL and is defined by the CANopen Communications Profile in CiA DS-301. This document may also be purchased from CiA. Information about CANopen may be obtained fromthe CiA User GroupYou might also want to get hold of a copy of "Embedded Networking with CAN and CANopen" by Olaf Pfeiffer, Andrew Ayre and Christian Keydel. Published by RTC Books. ISBN: 0-929392-78-7. Price in the USA $49.95.

DeviceNet

DeviceNet is a CiA-approved application layer based on CAN 2.0A and is widely used in industrial automation applications. DeviceNet (originally developed by Rockwell/Allen-Bradley) is now an "Open" fieldbus regulated by an independent organisation know as the Open DeviceNet Vendors Association, from whom copies of the specification may be purchased. Purchasers of the specification receive an unlimited, royalty-free licence to develop DeviceNet compatible products.

NMEA 2000

An application layer used in the marine and pleasure craft sector.

SDS (Smart Distributed System)

SDS is also a CiA-approved application layer. Developed by Honeywell, one of the main uses of SDS is for machine control applications.

CAN Kingdom

Another CiA-approved application layer, named CAN Kingdom, is provided by a Swedish company named Kvaser AB. 4.6Target Applications

CAN is being designed into a widerange of applications that usecommand and control networks.

Some of these applications include:

Industrial control

Maritime electronics

Avionics/aerospace electronics

UPS (Uninterruptible Power Supply)

Heavy machinery and earthmoving equipment

Factory automation

Medical equipment

Elevator control

Exercise equipment

Automotive passenger car

Trucks/buses

Off-highway and off-road vehicles

CHAPTER-5

MCP2515 Stand-Alone CAN Controller With SPI Interface

5.1Description

Microchip Technologys MCP2515 is a stand-alone Controller Area Network (CAN) controller that implements the CAN specification, version 2.0B. It is capable of transmitting and receiving both standard and extended data and remote frames. The MCP2515 has two acceptance masks and six acceptance filters that are used to filter out unwanted messages, thereby reducing the host MCUs overhead. The MCP2515 interfaces with microcontrollers (MCUs) via an industry standard Serial Peripheral Interface (SPI).

5.2Features

Implements CAN V2.0B at 1 Mb/s:

- 0 8 byte length in the data field

- Standard and extended data and remote frames

Receive buffers, masks and filters:

- Two receive buffers with prioritized message storage

- Six 29-bit filters

- Two 29-bit masks

Data byte filtering on the first two data bytes (applies to standard data frames)

Three transmit buffers with prioritizaton and abort features

High-speed SPI Interface (10 MHz):

- SPI modes 0,0 and 1,1

One-shot mode ensures message transmission is attempted only one time

Clock out pin with programmable prescaler:

- Can be used as a clock source for other device(s)

Start-of-Frame (SOF) signal is available for monitoring the SOF signal:

- Can be used for time-slot-based protocols and/or bus diagnostics to detect early bus degredation

Interrupt output pin with selectable enables

Buffer Full output pins configurable as:

- Interrupt output for each receive buffer

- General purpose output

Request-to-Send (RTS) input pins individually configurable as:

- Control pins to request transmission for each transmit buffer

- General purpose inputs

Low-power CMOS technology:

- Operates from 2.7V 5.5V

- 5 mA active current (typical)

- 1 A standby current (typical) (Sleep mode)

Temperature ranges supported:

- Industrial (I): -40C to +85C

- Extended (E): -40C to +125C

Packages Types

Overview

The MCP2515 is a stand-alone CAN controller developed to simplify applications that require interfacing with a CAN bus. A simple block diagram of the MCP2515 is shown in Figure 1-1. The device consists of three main blocks:

1. The CAN module, which includes the CAN protocol engine, masks, filters, transmit and receive buffers.

2. The control logic and registers that are used to configure the device and its operation.

3. The SPI protocol block.

CAN Module

The CAN module handles all functions for receiving and transmitting messages on the CAN bus. Messages are transmitted by first loading the appropriate message buffer and control registers. Transmission is initiated by using control register bits via the SPI interface or by using the transmit enable pins. Status and errors can be checked by reading the appropriate registers. Any message detected on the CAN bus is checked for errors and then matched against the user-defined filters to see if it should be moved into on of the two receive buffers.

5.3BLOCK DIAGRAM

5.4CAN MESSAGE FRAMES

The MCP2515 supports standard data frames, extended data frames and remote frames (standard and extended), as defined in the CAN 2.0B specification.

Standard Data Frame

The CAN standard data frame is shown in Figure 2-1.As with all other frames, the frame begins with a Start-Of-Frame (SOF) bit, which is of the dominant state and allows hard synchronization of all nodes.

The SOF is followed by the arbitration field, consisting of 12 bits: the 11-bit identifier and the Remote Transmission Request (RTR) bit. The RTR bit is used to distinguish a data frame (RTR bit dominant) from a remote frame (RTR bit recessive).

Following the arbitration field is the control field, consisting of six bits. The first bit of this field is the Identifier Extension (IDE) bit, which must be dominant to specify a standard frame. The following bit, Reserved

Bit Zero (RB0), is reserved and is defined as a dominant bit by the CAN protocol. The remaining four bits of the control field are the Data Length Code (DLC), which specifies the number of bytes of data (0 8 bytes)contained in the message.

After the control field is the data field, which contains any data bytes that are being sent, and is of the length defined by the DLC (0 8 bytes).

The Cyclic Redundancy Check (CRC) field follows the data field and is used to detect transmission errors. The CRC field consists of a 15-bit CRC sequence, followed by the recessive CRC Delimiter bit.

The final field is the two-bit Acknowledge (ACK) field.During the ACK Slot bit, the transmitting node sends out a recessive bit. Any node that has received an error-free frame acknowledges the correct reception of the frame by sending back a dominant bit (regardless of whether the node is configured to accept that specific message or not). The recessive acknowledge delimiter completes the acknowledge field and may not be overwritten by a dominant bit.

Extended Data FrameIn the extended CAN data frame, shown in Figure 2-2,the SOF bit is followed by the arbitration field, which consists of 32 bits. The first 11 bits are the Most Significant bits (MSb) (Base-lD) of the 29-bit identifier.

These 11 bits are followed by the Substitute Remote Request (SRR) bit, which is defined to be recessive.

The SRR bit is followed by the lDE bit, which is recessive to denote an extended CAN frame. It should be noted that if arbitration remains unresolved after transmission of the first 11 bits of the identifier, and one of the nodes involved in the arbitration is sending a standard CAN frame (11-bit identifier), the standard CAN frame will win arbitration due to the assertion of a dominant lDE bit. Also, the SRR bit in an extended CAN frame must be recessive to allow the assertion of a dominant RTR bit by a node that is sending a standard CAN remote frame.

The SRR and lDE bits are followed by the remaining18 bits of the identifier (Extended lD) and the remote transmission request bit.To enable standard and extended frames to be sent across a shared network, the 29-bit extended messageidentifier is split into 11-bit (most significant) and 18-bit (least significant) sections. This split ensures that thelDE bit can remain at the same bit position in both the standard and extended frames.Following the arbitration field is the six-bit control field.The first two bits of this field are reserved and must bedominant. The remaining four bits of the control field are the DLC, which specifies the number of data bytescontained in the message.

The remaining portion of the frame (data field, CRC field, acknowledge field, end-of-frame and intermission) is constructed in the same way as a standard data frame (see Section 2.1 Standard Data Frame).

Remote Frame

Normally, data transmission is performed on an autonomous basis by the data source node (e.g., a sensor sending out a data frame). It is possible, however, for a destination node to request data from the source. To accomplish this, the destination node sends a remote frame with an identifier that matches the identifier of the required data frame. The appropriate data source node will then send a data frame in response to the remote frame request.

There are two differences between a remote frame(shown in Figure 2-3) and a data frame. First, the RTR bit is at the recessive state and, second, there is no data field. In the event of a data frame and a remote frame with the same identifier being transmitted at the same time, the data frame wins arbitration due to the dominant RTR bit following the identifier. In this way,the node that transmitted the remote frame receives the desired data immediately.

Error Frame

An error frame is generated by any node that detects a bus error. An error frame, shown in Figure 2-4, consists of two fields: an error flag field followed by an error delimiter field. There are two types of error flag fields.The type of error flag field sent depends upon the error status of the node that detects and generates the error flag field.M

1.active errors

If an error-active node detects a bus error, the node interrupts transmission of the current message by generating an active error flag. The active error flag is composed of six consecutive dominant bits. This bit sequence actively violates the bit-stuffing rule. All other stations recognize the resulting bit-stuffing error and, in turn, generate error frames themselves, called error echo flags.

The error flag field, therefore, consists of between six and twelve consecutive dominant bits (generated by one or more nodes). The error delimiter field (eight recessive bits) completes the error frame. Upon completion of the error frame, bus activity returns to normal and the interrupted node attempts to resend the aborted message.

2.passive errors

If an error-passive node detects a bus error, the node transmits an error-passive flag followed by the error delimiter field. The error-passive flag consists of six consecutive recessive bits. The error frame for an error-passive node consists of 14 recessive bits. From this it follows that, unless the bus error is detected by an error-active node or the transmitting node, the message will continue transmission because the error-passive flag does not interfere with the bus.If the transmitting node generates an error-passive flag,it will cause other nodes to generate error frames due to the resulting bit-stuffing violation. After transmission of an error frame, an error-passive node must wait for six consecutive recessive bits on the bus before attempting to rejoin bus communications.

The error delimiter consists of eight recessive bits and allows the bus nodes to restart bus communications cleanly after an error has occurred.

Overload Frame

An overload frame, shown in Figure 2-5, has the same format as an active error frame. An overload frame,however, can only be generated during an interframe space. In this way, an overload frame can be differentiated from an error frame (an error frame is sent during the transmission of a message). The overload frame consists of two fields: an overload flag followed by an overload delimiter. The overload flag consists of six dominant bits followed by overload flags generated by other nodes (and, as for an active error flag, giving a maximum of twelve dominant bits). The overload delimiter consists of eight recessive bits. An overload frame can be generated by a node as a result of two conditions:

1. The node detects a dominant bit during the interframe space, an illegal condition.

Exception: The dominant bit is detected during the third bit of IFS. In this case, the receivers will interpret this as a SOF.

2. Due to internal conditions, the node is not yet able to begin reception of the next message. A node may generate a maximum of two sequential overload frames to delay the start of the next message.

Interframe SpaceThe interframe space separates a preceding frame (of any type) from a subsequent data or remote frame.

The interframe space is composed of at least three recessive bits called the Intermission. This allows nodes time for internal processing before the start of the next message frame. After the intermission, the bus line remains in the recessive state (bus idle) until the next transmission starts.CHAPTER-6

High-Speed CAN Transceiver(MCP2551)6.1OVERVIEW

The MCP2551 is a high-speed CAN, fault-tolerant device that serves as the interface between a CAN protocol controller and the physical bus. The MCP2551 provides differential transmit and receive capability for\ the CAN protocol controller and is fully compatible with the ISO-11898 standard, including 24V requirements. It will operate at speeds of up to 1 Mb/s. Typically, each node in a CAN system must have a device to convert the digital signals generated by a CAN controller to signals suitable for transmission over the bus cabling (differential output). It also provides a buffer between the CAN controller and the high-voltagespikes that can be generated on the CAN bus byoutside sources (EMI, ESD, electrical transients, etc.).

Transmitter Function

The CAN bus has two states: Dominant and Recessive. A dominant state occurs when the

differential voltage between CANH and CANL is greater than a defined voltage (e.g.,1.2V). A recessive state occurs when the differential voltage is less than a defined voltage (typically 0V). The dominant and recessive states correspond to the low and high state of the TXD input pin, respectively. However, a dominant state initiated by another CAN node will override arecessive state on the CAN bus.

Maximum number of nodes

The MCP2551 CAN outputs will drive a minimum load of 45, allowing a maximum of 112 nodes to be connected (given a minimum differential input resistance of 20 k and a nominal termination resistor value of 120).

Receiver Function

The RXD output pin reflects the differential bus voltage between CANH and CANL. The low and high states of the RXD output pin correspond to the dominant and recessive states of the CAN bus, respectively.

Internal Protection

CANH and CANL are protected against battery shortcircuits and electrical transients that can occur on the CAN bus. This feature prevents destruction of the transmitter output stage during such a fault condition. The device is further protected from excessive current loading by thermal shutdown circuitry that disables the output drivers when the junction temperature exceeds a nominal limit of 165C. All other parts of the chip remain operational and the chip temperature is lowered due to the decreased power dissipation in the transmitter outputs. This protection is essential to protect against bus line short-circuit-induced damage.

6.2 Operating Modes

The RS pin allows three modes of operation to beselected:

High-Speed

Slope-Control

Standby

When in High-speed or Slope-control mode, the drivers for the CANH and CANL signals are internally regulated to provide controlled symmetry in order to minimize EMI emissions.

Additionally, the slope of the signal transitions on CANH and CANL can be controlled with a resistor connected from pin 8 (RS) to ground, with the slope proportional to the current output at RS, further reducing EMI emissions.

HIGH-SPEED

High-speed mode is selected by connecting the RS pin to VSS. In this mode, the transmitter output drivers have fast output rise and fall times to support high-speedCAN bus rates.

SLOPE-CONTROL

Slope-control mode further reduces EMI by limiting the rise and fall times of CANH and CANL. The slope, or slew rate (SR), is controlled by connecting an external resistor (REXT) between RS and VOL (usually ground). The slope is proportional to the current output at the RS pin. Since the current is primarily determined by the slope-control resistance value REXT, a certain slew rate is achieved by applying a respective resistance. llustrates typical slew rate values as a

function of the slope-control resistance value.

STANDBY MODE

The device may be placed in standby or SLEEP mode by applying a high-level to RS. In SLEEP mode, the transmitter is switched off and the receiver operates at a lower current. The receive pin on the controller side (RXD) is still functional but will operate at a slower rate.

The attached microcontroller can monitor RXD for CAN bus activity and place the transceiver into normal operation via the RS pin (at higher bus rates, the first CAN message may be lost).

TXD Permanent Dominant Detection

If the MCP2551 detects an extended low state on the TXD input, it will disable the CANH and CANL output drivers in order to prevent the corruption of data on the CAN bus. The drivers are disabled if TXD is low for more than 1.25 ms (minimum). This implies a maximum bit time of 62.5 s (16 kb/s bus rate), allowing up to 20 consecutive transmitted dominant bits during a multiple bit error and error frame scenario. The drivers remain disabled as long as TXD remains low. A rising edge on TXD will reset the timer logic and enable the CANH and CANL output drivers.

Power-on Reset

When the device is powered on, CANH and CANL remain in a high-impedance state until VDD reaches the voltage-level VPORH. In addition, CANH and CANL will remain in a high impedance state if TXD is low when VDD reaches VPORH. CANH and CANL will become

active only after TXD is asserted high. Once powered on, CANH and CANL will enter a high-impedance state if the voltage level at VDD falls below VPORL, providing voltage brown-out protection during normal operation.

6.3Block Diagram

6.4Pin Diagram

Pins Description

TRANSMITTER DATA INPUT (TXD)

TXD is a TTL-compatible input pin. The data on this pin is driven out on the CANH and CANL differential output pins. It is usually connected to the transmitter data output of the CAN controller device. When TXD is low,CANH and CANL are in the dominant state. When TXD is high, CANH and CANL are in the recessive state,provided that another CAN node is not driving the CAN bus with a dominant state. TXD has an internal pull-up resistor (nominal 25 k to VDD).

GROUND SUPPLY (VSS)

Ground supply pin.

SUPPLY VOLTAGE (VDD)

Positive supply voltage pin.

RECEIVER DATA OUTPUT (RXD)

RXD is a CMOS-compatible output that drives high or low depending on the differential signals on the CANH and CANL pins and is usually connected to the receiver data input of the CAN controller device. RXD is high when the CAN bus is recessive and low in the dominant

state.

REFERENCE VOLTAGE (VREF)

Reference Voltage Output (Defined as VDD/2).

CAN LOW (CANL)

The CANL output drives the low side of the CAN differential bus. This pin is also tied internally to the receive input comparator.

CAN HIGH (CANH)

The CANH output drives the high-side of the CAN differential bus. This pin is also tied internally to the receive input comparator.

SLOPE RESISTOR INPUT (RS)

The RS pin is used to select High-speed, Slope-control or Standby modes via an external biasing resistor.

CHAPTER-7

AVR STUDIO

Starting AVR Studio

Start the AVR Studio program by clicking on:

Start->Programs->ATMEL AVR Tools->AVR Studio 4

Once the program has started, you will be looking at a screen like this:

Creating a New ProjectIn this tutorial we will make a simple program that increases the value of one of the PORT registers, making a binary counter.

To create a new project, click on "New Project" on the Welcome Screen or go to the"Project" menu and select "New".

In this dialog box you should select "Atmel AVR Assembler" and enter the project name. We choose the name "led" here, but this could of course be an arbitrary name. Next you'll have to select the project location. This is the location where AVR Studio will store all files associated with the project. We have used the location H:\csse1000\pracs\ as the folder. If the folder does not exist, AVR Studio will ask you whether to create it or not. Click "Next >>"

Select "AVR Simulator" as the debug platform and "AT90S8515" as the device to use, then click "Finish".

We can now enter the Assembly code of the program. (AVR Studio has opened an editor window called led.asm). Alternatively you can add or create other assembly language files by right clicking on "Source Files" in the Project window.

The led.asm file is automatically marked as "Assembler Entry File" (the small red arrow on the icon next to the filename shows this). This indicates that the code from this file will be assembled (and executed) first. Only one file can be marked as an entry file.

Editing the Assembler file

We have now added a new but empty file to our project. The next step is to fill this file with our code. The file is initially empty and you'll have to manually enter the following code: (or you may Copy and Paste the code below directly into the editor window.)

Assemble the Source Code

To assemble the code, we need to build the project. Select "Build" from the Build menu (or press ):

The result of building the project will be shown in the "Build" pane.

We are now ready to advance to the next step, which is running the code in simulator mode.

Simulating the Code

At this point we have generated the files needed to simulate the code. To start running the code, select "Start Debugging" from the "Debug" menu:Instruction Pointer

Now take a look in the editor view, you'll see that a yellow right-arrow has appeared in the left margin of the code. This arrow indicates the position of the program counter. In other words, it points to the next instruction to be executed.We want to set the I/O View so that we can have a closer look at what is happening on the Port B registers during program execution. In the "I/O View" Window, click on the + symbol next to "PORTB". Similarly, you can expand other views if desired.This shows all registers associated with Port B, these are: Port B Data register (PORTB), Data Direction (DDRB) and Input Pins (PINB). As shown each bit in the registers are represented by a checkbox. A logical 'zero' (0) is represented by an empty checkbox and a logical 'one(1) is represented by a filled-in checkbox. These checkboxes will be updated during program execution, and show the current state of every bit. You may also set and clear these bits by clicking on the appropriate checkbox at any time during the program execution. You can also monitor the hexadecimal equivalent representation.Single Stepping the Program

There are two commands to single step through the code. These are "Step Over" and "Step Into" . The difference between these commands is that "Step Over" does not trace into subroutines. Since our example does not contain any subroutines, there is no difference between the operation of these commands in this example.

Now single step down to the last line of code (rjmp loop) by repeatedly pressing the key or by selecting "Step Into" from the"Debug" menu. Notice how the colour changes from black to red on the registers that change value. This makes it easier to identify which registers change value on each instruction. Continue pressing the key and see how the binary value in Port B is increased.

Setting Breakpoints

Breakpoints are a method of halting execution flow. By adding a breakpoint in the assembly code we can run run the program at full speed, and it will be stopped at the line with the breakpoint. By now you have noticed that you have to press three times to go through the loop once. We will add a breakpoint at the rjmp loop instruction to show how this can be used to speed up the debug process.

Place the cursor on the rjmp loop instruction in the source view window and press (or the "Toggle Breakpoint" in the "Debug" menu or right-click on the line of code and select "Toggle Breakpoint"). A red circle will appear in the left margin of the source view . By pressing or "Run" from the "Debug" menu the program will start running and break (stop) at the instruction with the breakpoint.Modifying the Code

Now we want the program to count down instead of up. To make this change we'll have to edit the source code. Place the cursor in the source view, and change the inc to a dec instruction. If you now press (Run) the following dialog box will appear. This box indicates that one of the source files has been changed, and that the project should be rebuilt. Press "Yes".The Project will now be rebuilt, and the instruction pointer will start at the first line of code. Notice how the breakpoint is remembered.

Opening the Watch View

Open the Watch window by selecting "Watch" from the "View" menu:

Variables that are defined (by the .def directive) can be placed in the Watch view. The only defined variable in this code is the temp variable. Right-click the "Watches" window and select "Add Item". Type in the variable name temp at the cursor and then press the Enter key. As we continue to run through the program the temp variable will constantly be updated during program execution.Setting up the Processor ViewNow we will examine the Processor view. Open this view by right clicking in the toolbar area and select "Processor":

This view shows processor specific information like the value of the Program Counter. In this view you will also find a Cycle Counter and a StopWatch. These are very useful if you wish to measure the length of a loop or how much time a specific subroutine uses. We will not use this view directly in this example, but it provides a lot of useful information during debugging of a project. You can also view the contents of the individual registers.

Saving the Project

Before exiting AVR Studio we will save our project. AVR Studio will remember where the views are placed and will use this setting when opening the project later. To save the project select "Save Project" from the "Project" menu.CHAPTER-8

Code Vision AVR (CVAVR)An IDE has following functions:

Preprocessing

Compilation

Assembly

Linking

Object Translation

Text Editor

If we just use compiler and linker independently we still need to get a text editor. So combining everything will actually mess things up. So the best way is to get So f twa r e which has it all. Thats called an Integrated Development Environment, in short IDE.

I consider Code-Vision-AVR to be the best IDE for getting started with AVR programming on Windows XP, Vista. It has a very good Code Wizard which generate codes automatically ! You need not mess with the assembly words. So in all my tutorials I will be using CVAVR. You can download evaluation version for free which has code size limitation but good enough for our purpose.

For all my examples I will be using Atmega-16 as default microcontroller because it very easily available and is powerful enough with sufficient number of pins and peripherals we use. Lets take a look on the software. The main window looks like following,

Now click on Fi le ---> New --->Project

A pop up window will come asking whether you want to use Code Wizard AVR, obviously select yes because that is the reason we are using CVAVR !

Now have a look on this Wizard. It has many tabs where we can configure PORTS, TIMERS, LCD, ADC etc. I am explaining some of them

CHIP: Select the chip for which you are going to write the program. Then select the frequency at which Chip is running. By default all chips are set on Internal Oscillator of 1 MHz so select 1 MHz if that is the case. If you want to change the running clock frequency of the chip then you have to change its fuse bits (I will talk more about this in fuse bits section). PORT:

PORT is usually a collection of 8 pins.

From this tab you can select which pin you want to configure as output and which as input. It basically writes the DDR and PORT register through this setting. Registers are basically RAM locations which configure various peripherals of microcontroller and by changing value of these registers we can change the function it is performing. I will talk more about registers later. All the details are provided in the datasheet.

So you can configure any pin as output or input by clicking the box.

For Atmega-16 which has 4 Ports we can see 4 tabs each corresponding to one Port. You can also set initial value of the Pins you want to assign. or if you are using a pin as input then whether you want to make it as pull-up or tristated, again I will talk in details about these functions later.

Similarly using this code wizard you can very easily configure all the peripherals on the Atmega.

Now for generating code just go to Fi le ----> Generate, Save and Exit (of the code wizard)

Now it will ask you name and location for saving three files. Two being project files and one being the.C file which is your program. try to keep same names of all three files to avoid confusion. By default these files are generated in C:\CVAVR\bin

The generated program will open in the text editor. Have a look it has some declarations like PORT, DDR, TCCR0 and many more. These are all registers which configures various functions of Atmega and by changing these value we make different functions. All the details about the registers are commented just below them. Now go down and find following infinite while loop there. We can start writing our part of program just before the while loop. And as for most of the applications we want microcontroller to perform the same task forever we put our part of code in the infinite while loop provided by the code wizard !

while (1)

{

// Place your code here

};

}

See how friendly this code wizard is, all the work (configuring registers) automatically done and we dont even need to understand and go to the details about registers too !

Now we want to generate the hex file, so first compile the program. Either press F9 or go to Project ---> Compile.

It will show compilation errors if any. If program is error free we can proceed to making of hex file. So either press Shift+F9 or go to Project ----> Make. A pop up window will come with information about code size and flash usage etc.

So the machine file is ready now ! It is in the same folder where we saved those 3 files.

CHAPTER-9

AVR In-System Programming9.1Introduction

In-System Programming allows programming and reprogramming of any AVR microcontroller positioned inside the end system. Using a simple Three-wire SPI interface,the In-System Programmer communicates serially with the AVR microcontroller,reprogramming all non-volatile memories on the chip.

In-System Programming eliminates the physical removal of chips from the system.This will save time, and money, both during development in the lab, and when updating the software or parameters in the field.

This application note shows how to design the system to support In-System Programming. It also shows how a low-cost In-System Programmer can be made, that will allow the target AVR microcontroller to be programmed from any PC equipped with a regular 9-pin serial port. Alternatively, the entire In-System Programmer can be builtinto the system allowing it to reprogram itself.9.2The Programming Interface

For In-System Programming, the programmer is connected to the target using as few wires as possible. To program any AVR microcontroller in any target system, a simple Six-wire interface is used to connect the programmer to the target PCB. Figure below shows the connections needed.

The Serial Peripheral Interface (SPI) consists of three wires: Serial ClocK (SCK), Master In Slave Out (MISO) and Master Out Slave In (MOSI). When programming the AVR, the In-System Programmer always operate as the Master, and the target system always operate as the Slave.

The In-System Programmer (Master) provides the clock for the communication on the SCK Line. Each pulse on the SCK Line transfers one bit from the Programmer (Master) to the Target (Slave) on the Master Out Slave In (MOSI) line. Simultaneously,each pulse on the SCK Line transfers one bit from the target (Slave) to the Programmer (Master) on the Master In Slave Out (MISO) line.

To assure proper communication on the three SPI lines, it is necessary to connect ground on the programmer to ground on the target (GND).

To enter and stay in Serial Programming mode, the AVR microcontroller reset line has to be kept active (low). Also, to perform a Chip Erase, the Reset has to be pulsed to end the Chip Erase cycle. To ease the programming task, it is preferred to let the programmer take control of the tar-get microcontroller reset line to automate this process using a fourth control line (Reset).

To allow programming of targets running at any allowed voltage (2.7 - 6.0 V), the programmer can draw power from the target system (VCC). This eliminate the need for a separate power sup-ply for the programmer. Alternatively, the target system can be supplied from the programmer at programming time, eliminating the need to power the target system through its regular power connector for the duration of the programming cycle.Figure below shows the connector used by this In-System Programmer to connect to the target system. The standard connector supplied is a 2 x 3 pin header contact, with pin spacing of 100 mils9.3Hardware Design ConsiderationsTo allow In-System Programming of the AVR microcontroller, the In-System Programmer must be able to override the pin functionality during programming. This section describes the details of each pin used for the programming operation.

GND The In-System Programmer and target system need to operate with the same reference voltage. This is done by connecting ground of the target to ground of the programmer. No special consid-erations apply to this pin.

RESET

The target AVR microcontroller will enter Serial Programming mode only when its reset line is active (low). When erasing the chip, the reset line has to be toggled to end the erase cycle. To simplify this operation, it is recommended that the target reset can be controlled by the In-Sys-tem Programmer.

Immediately after Reset has gone active, the In-System Programmer will start to communicate on the three dedicated SPI wires SCK, MISO, and MOSI. To avoid driver contention, a series resistor should be placed on each of the three dedicated lines if there is a possibility that external circuitry could be driving these lines. The connection is shown in Figure 3. The value of the resistors should be chosen depending on the circuitry connected to the SPI bus. Note that the AVR microcontroller will automatically set all its I/O pins to inputs, with pull ups disabled, when Reset is active.

To avoid problems, the In-System Programmer should be able to keep the entire Target System Reset for the duration of the programming cycle. The target system should never attempt to drive the three SPI lines while Reset is active.SCK When programming the AVR in Serial mode, the In-System Programmer supplies clock information on the SCK pin. This pin is always driven by the programmer, and the target system should never attempt to drive this wire when target reset is active. Immediately after the Reset goes active, this pin will be driven to zero by the programmer. During this first phase of the programming cycle, keeping the SCK Line free from pulses is critical, as pulses will cause the target AVR to loose synchronization with the programmer. When in synchronization, the second byte ($53),will echo back when issuing the third byte of the programming enable instruction. If the $53 did not echo back, give Reset a positive pulse, and issue a new Programming Enable command.

Note that all four bytes of the of the Programming Enable command must be sent before starting a new transmission.

The target AVR microcontroller will always set up its SCK pin to be an input with no pull up whenever Reset is active. See also the description of the Reset wire.The minimum low and high periods for the Serial Clock (SCK) input are defined in the programming section of the datasheet. For the AT90S1200 they are defined as follows:

Low: >1 XTAL1 clock cycle

High: >4 XTAL1 clock cyclesMOSI When programming the AVR in Serial mode, the In-System Programmer supplies data to the target on the MOSI pin. This pin is always driven by the programmer, and the target system should never attempt to drive this wire when target reset is active.

The target AVR microcontroller will always set up its MOSI pin to be an input with no pull up whenever Reset is active. See also the description of the Reset wire. MISO When Reset is applied to the target AVR microcontroller, the MISO pin is set up to be an input with no pull up. Only after the Programming Enable command has been correctly transmitted to the target will the target AVR microcontroller set its MISO pin to become an output. During this first time, the In-System programmer will apply its pull up to keep the MISO line stable until it is driven by the target microcontroller.

VCC When programming the target microcontroller, the programmer outputs need to stay within the ranges specified in the DC Characteristics.

To easily adapt to any target voltage, the programmer can draw all power required from the tar- get system. This is allowed as the In-System Programmer will draw very little power from the target system, typically no more than 20 mA. The programmer shown in this application note operates in this mode.

As an alternative, the target system can have its power supplied from the programmer through the same connector used for the communication. This would allow the target to be programmed without applying power to the target externally. (CAN)CHAPTER-10

CODE10.1Transmitter1 code:

#include

#include

#include

#include

#include

#include

#definePRINT(string, ...)

printf_P(PSTR(string), ##__VA_ARGS__)

#define setbit(Port,Bit) {Port |=(1