115
BLOCK DIAGRAM 1

can

Embed Size (px)

Citation preview

Page 1: can

BLOCK DIAGRAM

1

Page 2: can

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

2

ATMEGA32 Sensor-1

2x16 LCD

Sensor-2CAN

Control

CAN

Driver

Micro controller

CAN

Driver

CAN

Control

2x16 LCD

Page 3: can

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.

3

Page 4: can

CHAPTER-2

POWER SUPPLY

An 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.

4

Page 5: can

5

Page 6: can

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 85°C/100 years at 25°C(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

6

Page 7: can

– 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, 25°C for ATmega32L– Active: 1.1 mA– Idle Mode: 0.35 mA– Power-down Mode: < 1 µA

3.3Pin Configurations

7

Page 8: can

Pin Descriptions

VCC 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.

8

Page 9: can

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.

9

Page 10: can

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

10

Page 11: can

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 device’s 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

11

Page 12: can

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.

12

Page 13: can

• 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.

13

Page 14: can

CHAPTER-4

CONTROLLER AREA NETWORK

4.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 choosingCAN 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.

14

Page 15: can

How CAN works

PrincipleData 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 encodingCAN 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 bus

The 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 ExpansionThe 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.

15

Page 16: can

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 BusIn 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 ArbitrationThe 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 implementations

As the CAN standard does not include tasks of application layer protocols, such as flow control, device addressing, and transportation of data blocks larger than one message, many implementations of higher layer protocols were created. Among these are DeviceNet, CANopen, SDS (Smart Distributed System), CANaerospace, J1939, SmartCraft, NMEA 2000, CAN Kingdom, SafetyBUS p, EnergyBus and MilCAN.

An ARINC technical working group develops the ARINC 825 standard with special requirements for the aviation industry.

16

Page 17: can

.

Block Diagram

4.3Types of CAN

There 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 FormatA 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.

17

Page 18: can

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 FormatThe 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.

18

Page 19: can

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 Compatibility2.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!

Standard Common Name Baud Rate Max nodesMax Length

Adapter forPCAN interfaces

ISO 11783 ISOBUS 250 KBit/s 30 40m None

ISO 11898-2

High speed-CAN max. 1 MBit/s 110 6500 m None

ISO 11898-3

Fault Tolerant CAN max. 125 KBit/s 32 500 mPCAN TJA1054

ISO 11992FMS or Truck/Trailer CAN

max. 125 KBit/s2 (Point to Point) 40 m

PCAN-BD10011S

19

Page 20: can

ISO 15765 Diagnostics On CAN max 1 MBit/s 110

SAE J1939 250 KBit/s 30 40m

SAE J2284 max. 1 MBit/s 110

SAE J2411 Single Wire CAN

33,3 KBit/s83,3KBit/s in HSMode

32 PCAN-AU579

4.4Implementations of CANCommunication 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:

20

Page 21: can

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 modelISO7498 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.

21

Page 22: can

Fig . The Seven Layer OSI model

.CAN and the OSI Model

The 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 layers may be implemented in either hardware (as chip level functions) or software, the Physical Layer is always "real" hardware.

CAN Applications LayersMany 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 ManagementMedium Access Control (MAC)• Data Encapsulation/Decapsulation• Frame Coding (Stuffing/Destuffing)]• Error Detection/Signalling• Serialization/Deserialization

22

Page 23: can

Physical Signaling (PLS)• Bit Encoding/Decoding• Bit Timing/SynchronizationPhysical Medium Attachment (PMA)• Driver/Receiver CharacteristicsMedium Dependent Interface (MDI)• Connectors

CANopenCANopen 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 from the CiA User Group

You 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 2000An 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

23

Page 24: can

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 Technology’s 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

24

Page 25: can

• 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): -40°C to +85°C

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

Packages Types

25

Page 26: can

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

26

Page 27: can

27

Page 28: can

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

28

Page 29: can

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 Frame

In 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

29

Page 30: can

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

30

Page 31: can

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.

31

Page 32: can

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 Space

The 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.

32

Page 33: can

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 thedifferential 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 165°C. 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.

33

Page 34: can

6.2 Operating Modes

The RS pin allows three modes of operation to beselected:• High-Speed• Slope-Control• StandbyWhen 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 afunction 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.

34

Page 35: can

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 becomeactive 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

35

Page 36: can

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 dominantstate.

36

Page 37: can

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.

37

Page 38: can

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 Project

In 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.

38

Page 39: can

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 <F7>):

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" <F10> and "Step Into" <F11>. 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 <F11> 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 <F11> key and see how the binary value in Port B is increased.

39

Page 40: can

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 <F11> 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 <F9> (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 <F5> 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 <F5> (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 View

Now 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.

40

Page 41: can

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. That’s 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.

Let’s take a look on the software. The main window looks like following,

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

41

Page 42: can

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

;

42

Page 43: can

See how friendly this code wizard is, all the work (configuring registers) automatically done and we don’t 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.

43

Page 44: can

CHAPTER-9

AVR In-System Programming

9.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.

44

Page 45: can

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 mils

9.3Hardware Design Considerations

To 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

45

Page 46: can

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

46

Page 47: can

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 cycles

MOSI

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)

47

Page 48: can

CHAPTER-10

CODE

10.1Transmitter1 code:

#include <avr/io.h>

#include <avr/interrupt.h>

#include <util/delay.h>

#include <stdio.h>

#include <inttypes.h>

#include <string.h>

#define PRINT(string, ...) printf_P(PSTR(string), ##__VA_ARGS__)

#define setbit(Port,Bit) Port |=(1<<Bit); //Macro to set a port bit

#define clrbit(Port,Bit) Port &= ~(1<<Bit); //Macro to clear a port bit

#include "lcd.h"

#include "mcp2515.h"

#include "mcp2515_defs.h"

#include "global.h"

#include "defaults.h"

#include "adc.h"

/********************************************************************/

void spi_reset(void);

void mcp2515_write_register(char addr, char data);

char mcp2515_read_register(char addr);

char spi_putc(char val);

void DELAY_3SEC(void);

48

Page 49: can

uint8_t mcp2515_send_message3(tCAN *message3);

int Temperatute;

/****************************************************************/

/******************************************************************/

void mcp2515_bit_modify(uint8_t adress, uint8_t mask, uint8_t data)

clrbit(PORTB,4);

spi_putc(SPI_BIT_MODIFY);

spi_putc(address);

spi_putc(mask);

spi_putc(data);

setbit(PORTB,4);

/*-----------------------------------*/

uint8_t mcp2515_read_status(uint8_t type)

uint8_t data;

clrbit(PORTB,4);

spi_putc(type);

data = spi_putc(0x00);

setbit(PORTB,4);

return data;

/*-----------------------------------*/

bool mcp2515_init(void)

SET_INPUT(MCP2515_INT);

SET(MCP2515_INT);

SPCR = 0b01010000;

49

Page 50: can

SPSR=1;

spi_reset();

mcp2515_write_register(0x0f,0x80);

temp=mcp2515_read_register(0x0e);

printf("\ncontrol reg=%X",temp);

// wait a little bit until the MCP2515 has restarted

_delay_us(10);

// load CNF1..3 Register

clrbit(PORTB,4);

spi_putc(SPI_WRITE);

spi_putc(CNF3);

spi_putc((1<<PHSEG21)); /

// Bitrate 125 kbps at 16 MHz

spi_putc((1<<BTLMODE)|(1<<PHSEG11));

spi_putc((1<<BRP2)|(1<<BRP1)|(1<<BRP0));

setbit(PORTB,4);

// test if we could read back the value => is the chip accessible?

if (mcp2515_read_register(CNF1) != ((1<<BRP2)|(1<<BRP1)|(1<<BRP0)))

return false;

// set TXnRTS as inputs

mcp2515_write_register(TXRTSCTRL, 0);

// reset device to normal mode

mcp2515_write_register(CANCTRL, 0);

_delay_ms(10);

temp=mcp2515_read_register(0x0e);

printf("\nnormal mode=%X",temp);

return true;

50

Page 51: can

/*-----------------------------------*/

void spi_reset()

clrbit(PORTB,4);

SPDR = 0b11000000;

while( !( SPSR & (1<<SPIF) ) ) ;

// clear SPIF flag

SPSR = 0;

setbit(PORTB,4);

/*-----------------------------------*/

void mcp2515_write_register(char addr, char data)

SPCR = 0b01010000;

clrbit(PORTB,4);

SPDR = 0b00000010;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = addr;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = data;

while( !( SPSR & (1<<SPIF) ) ) ;

// clear SPIF flag

SPSR= 0;

setbit(PORTB,4);

/*-----------------------------------*/

char mcp2515_read_register(char addr)

51

Page 52: can

unsigned char data;

// set chip select low

SPCR = 0b01010000;

clrbit(PORTB,4);

SPDR = 0b00000011;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = addr;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = 0x00;

while( !( SPSR & (1<<SPIF) ) ) ;

data = SPDR;

// set chip select high

setbit(PORTB,4);

return data;

/*-----------------------------------*/

char spi_putc(char val)

SPDR =val;

while( !( SPSR & (1<<SPIF) ) ) ;

SPSR =0;

return SPDR;

/*-----------------------------------*/

// check if there are any new messages waiting

uint8_t mcp2515_check_message(void)

temp=mcp2515_read_register(0x30);

printf("\nTransmit control reg in check msg=%X\n",temp);

return (!IS_SET(MCP2515_INT));

52

Page 53: can

/*-----------------------------------*/

// check if there is a free buffer to send messages

bool mcp2515_check_free_buffer(void)

uint8_t status = mcp2515_read_status(SPI_READ_STATUS);

if ((status & 0x54) == 0x54)

// all buffers used

return false;

return true;

/*-----------------------------------*/

uint8_t mcp2515_send_message(tCAN *message)

uint8_t status = mcp2515_read_status(SPI_READ_STATUS);

printf("data=%x",status);

/* Statusbyte:

* Bit Function

* 2 TXB0CNTRL.TXREQ

* 4 TXB1CNTRL.TXREQ

* 6 TXB2CNTRL.TXREQ

*/uint8_t address;

//mcp2515_write_register(TXB0CTRL,0x03);

if (bit_is_clear(status, 2))

address = 0x00;

PRINT("In Transmit Buffer 0 mode\n\n");

else if (bit_is_clear(status, 4))

53

Page 54: can

address = 0x02;

PRINT("In Transmit Buffer 1 mode\n\n");

else if (bit_is_clear(status, 6))

address = 0x04;

PRINT("In Transmit Buffer 2 mode\n\n");

else

// all buffer used => could not send message

return 0;

clrbit(PORTB,4);

spi_putc(SPI_WRITE_TX | address);

spi_putc(message->id >> 3);

spi_putc(message->id << 5);

spi_putc(0);

spi_putc(0);

uint8_t length = message->header.length & 0x0f;

if (message->header.rtr)

// a rtr-frame has a length, but contains no data

spi_putc((1<<RTR) | length);

// set message length

spi_putc(length);

// data

for (uint8_t i=0;i<length;i++)

54

Page 55: can

spi_putc(message->data[i]);

setbit(PORTB,4);

clrbit(PORTB,4);

// send message

address = (address == 0) ? 1 : address;

spi_putc(SPI_RTS | address);

setbit(PORTB,4);

return address;

/*----------------------------------*/

uint8_t mcp2515_send_message1(tCAN *message1)

uint8_t status = mcp2515_read_status(SPI_READ_STATUS);

printf("data=%x",status);

/* Statusbyte:

*

* Bit Function

* 2 TXB0CNTRL.TXREQ

* 4 TXB1CNTRL.TXREQ

* 6 TXB2CNTRL.TXREQ

*//

uint8_t address;

mcp2515_write_register(TXB0CTRL,0x03);

if (bit_is_clear(status, 2))

address = 0x00;

PRINT("In Transmit Buffer 0 mode\n\n");

55

Page 56: can

else if (bit_is_clear(status, 4))

address = 0x02;

PRINT("In Transmit Buffer 1 mode\n\n");

else if (bit_is_clear(status, 6))

address = 0x04;

PRINT("In Transmit Buffer 2 mode\n\n");

else

// all buffer used => could not send message

return 0;

clrbit(PORTB,4);

spi_putc(SPI_WRITE_TX | address);

spi_putc(message1->id >> 3);

spi_putc(message1->id << 5);

spi_putc(0);

spi_putc(0);

uint8_t length = message1->header.length & 0x0f;

if (message1->header.rtr)

// a rtr-frame has a length, but contains no data

spi_putc((1<<RTR) | length);

// set message length

56

Page 57: can

spi_putc(length);

// data

for (uint8_t i=0;i<length;i++)

spi_putc(message1->data[i]);

setbit(PORTB,4);

clrbit(PORTB,4);

// send message

address = (address == 0) ? 1 : address;

spi_putc(SPI_RTS | address);

setbit(PORTB,4);

return address;

/******************************************************************/

/*-------------------------------------*/

void DELAY_3SEC(void)

long int i;

for(i=-9999;i<=0x9999;i++);

/*-----------------------------------------*/

void hex2ascii(int T_d)

57

Page 58: can

ones = T_d%10;

tens=T_d/10;

lcd_data_out(tens+0x30);

ones=ones+0x30;

lcd_data_out(ones);

lcd_data_out('c');

/********************************************************************

Void welcome_message(void)

lcd_Line1();

lcd_string("CAN Transmitter #1");

lcd_Line2();

lcd_string(" TEMPERATURE ");

_delay_ms(2000);

unsigned char s=0,v=0;

// --------------------------------------

// Hauptprogram

int main(void)

DDRA = 0xfe;

DDRD = 0xff;

DDRB = 0xff;

//DDRC=0xFF;

58

Page 59: can

lcd_init();

// DDRB = 0b10111001;

setbit(PORTB,4);

sei();

welcome_message();

/*------mcp2515 initilization--------*/

if (!mcp2515_init())

// PRINT("\n mcp 2515 not initilized\n");

for (;;);

else

// PRINT("\n MCP2515 is active\n");

lcd_clr();

tCAN message,message1,message3;

adc_init();

mcp2515_bit_modify(CANCTRL,(1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);

message.id = 0xaa;

message.header.rtr = 0;

message.header.length = 2;

message1.id = 0xbb;

message1.header.rtr = 0;

message1.header.length = 8;

message3.id = 0xba;

message3.header.rtr = 0;

59

Page 60: can

message3.header.length = 8;

/*--------------------------*/

while(1)

Temperatute=adc_convert();

lcd_cmnd_out(0x80);

lcd_string("TEMPERATURE: ");

hex2ascii(Temperatute);

message.data[0] = Temperatute/10;

message.data[1] = Temperatute%10;

mcp2515_send_message(&message);

mcp2515_check_message();

mcp2515_send_message1(&message1);

mcp2515_check_message();

return 0;

60

Page 61: can

10.2 LCD

#include <avr/io.h>

#include <util/delay.h>

#include <compat/ina90.h>

/*#define RS 3 //portD

#define RW 1 //portB

#define EN 2 //portB*/

/*

#define RS 3 //portD

#define RW 1 //portB

#define EN 2 //portB*/

#define LCD PORTA

#define setbit(Port,Bit) Port |=(1<<Bit); //Macro to set a port bit

#define clrbit(Port,Bit) Port &= ~(1<<Bit); //Macro to clear a port bit

void lcd_data_out(char);

void lcd_cmnd_out(char);

void lcd_init(void);

void lcd_string(char *ptr);

void lcd_char(char byte);

void lcd_clr(void);

void lcd_Line1(void);

void lcd_Line2(void);

void lcd_Line3(void);

void lcd_Line4(void);

void lcd_init(void)

lcd_cmnd_out(0x28);

61

Page 62: can

lcd_cmnd_out(0x28);

lcd_cmnd_out(0x28);

lcd_cmnd_out(0x06);

lcd_cmnd_out(0x0c);

lcd_cmnd_out(0x01);

// lcd_cmnd_out(0x80);

void lcd_cmnd_out(char a)

LCD = ((a & 0xF0) | 0x04);

LCD = 0x00;

LCD = ((a << 4) | 0x04);

LCD = 0x00;

_delay_ms(10);

void lcd_data_out(char val)

LCD = ((val & 0xF0) | 0x0C);

LCD = 0x00;

LCD = ((val << 4) | 0x0C);

LCD = 0x00;

_delay_ms(10);

void lcd_string(char *ptr)

while(*ptr)

lcd_char(*ptr);

ptr++;

62

Page 63: can

void lcd_char(char byte)

lcd_data_out(byte);

void lcd_clr(void)

lcd_cmnd_out(0x01);

void lcd_Line1(void)

lcd_cmnd_out(0x80);

void lcd_Line2(void)

lcd_cmnd_out(0xc0);

void lcd_Line3(void)

lcd_cmnd_out(0x94);

void lcd_Line4(void)

lcd_cmnd_out(0xD4);

63

Page 64: can

10.3Transmitter2 code

#include <avr/io.h>

#include <avr/interrupt.h>

#include <avr/pgmspace.h>

#include <util/delay.h>

#include <stdio.h>

#include <inttypes.h>

#define PRINT(string, ...) printf_P(PSTR(string), ##__VA_ARGS__)

#define setbit(Port,Bit) Port |=(1<<Bit); //Macro to set a port bit

#define clrbit(Port,Bit) Port &= ~(1<<Bit); //Macro to clear a port bit

#include "lcd.h"

#include "uart.c"

#include "mcp2515.h"

#include "mcp2515_defs.h"

#include "global.h"

#include "defaults.h"

/******************************************************************************/

unsigned char temp=0;

unsigned char Dtemp;

void spi_reset(void);

void mcp2515_write_register(char addr, char data);

char mcp2515_read_register(char addr);

char spi_putc(char val);

/******************************************************************************/

static int putchar__(char c, FILE *stream)

uart_putc(c);

64

Page 65: can

return 0;

static FILE mystdout = FDEV_SETUP_STREAM(putchar__, 0, _FDEV_SETUP_WRITE);

/*******************************************************************************/

/*******************************************************************************/

void mcp2515_bit_modify(uint8_t adress, uint8_t mask, uint8_t data)

clrbit(PORTB,4);

spi_putc(SPI_BIT_MODIFY);

spi_putc(adress);

spi_putc(mask);

spi_putc(data);

setbit(PORTB,4);

/*-----------------------------------*/

uint8_t mcp2515_read_status(uint8_t type)

uint8_t data;

clrbit(PORTB,4);

spi_putc(type);

data = spi_putc(0x00);

setbit(PORTB,4);

return data;

/*-----------------------------------*/

bool mcp2515_init(void)

65

Page 66: can

SET_INPUT(MCP2515_INT);

SET(MCP2515_INT);

SPCR = 0b01010000;

SPSR=1;

spi_reset();

mcp2515_write_register(0x0f,0x80);

temp=mcp2515_read_register(0x0e);

printf("\ncontrol reg=%X",temp);

// wait a little bit until the MCP2515 has restarted

_delay_us(10);

// load CNF1..3 Register

clrbit(PORTB,4);

spi_putc(SPI_WRITE);

spi_putc(CNF3);

spi_putc((1<<PHSEG21)); // Bitrate 125 kbps at 16 MHz

spi_putc((1<<BTLMODE)|(1<<PHSEG11));

spi_putc((1<<BRP2)|(1<<BRP1)|(1<<BRP0));

setbit(PORTB,4);

// test if we could read back the value => is the chip accessible?

if (mcp2515_read_register(CNF1) != ((1<<BRP2)|(1<<BRP1)|(1<<BRP0)))

return false;

// set TXnRTS as inputs

mcp2515_write_register(TXRTSCTRL, 0);

// reset device to normal mode

mcp2515_write_register(CANCTRL, 0);

_delay_ms(10);

temp=mcp2515_read_register(0x0e);

printf("\nnormal mode=%X",temp);

66

Page 67: can

return true;

/*-----------------------------------*/

void spi_reset()

clrbit(PORTB,4);

SPDR = 0b11000000;

while( !( SPSR & (1<<SPIF) ) ) ;

// clear SPIF flag

SPSR = 0;

setbit(PORTB,4);

/*-----------------------------------*/

void mcp2515_write_register(char addr, char data)

SPCR = 0b01010000;

clrbit(PORTB,4);

SPDR = 0b00000010;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = addr;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = data;

while( !( SPSR & (1<<SPIF) ) ) ;

// clear SPIF flag

SPSR= 0;

setbit(PORTB,4);

/*-----------------------------------*/

char mcp2515_read_register(char addr)

67

Page 68: can

unsigned char data;

// set chip select low

SPCR = 0b01010000;

clrbit(PORTB,4);

SPDR = 0b00000011;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = addr;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = 0x00;

while( !( SPSR & (1<<SPIF) ) ) ;

data = SPDR;

// set chip select high

setbit(PORTB,4);

return data;

/*-----------------------------------*/

char spi_putc(char val)

SPDR =val;

while( !( SPSR & (1<<SPIF) ) ) ;

SPSR =0;

return SPDR;

/*-----------------------------------*/

// check if there are any new messages waiting

uint8_t mcp2515_check_message(void)

temp=mcp2515_read_register(0x30);

printf("\nTransmit control reg in check msg=%X\n",temp);

68

Page 69: can

return (!IS_SET(MCP2515_INT));

/*-----------------------------------*/

// check if there is a free buffer to send messages

bool mcp2515_check_free_buffer(void)

uint8_t status = mcp2515_read_status(SPI_READ_STATUS);

if ((status & 0x54) == 0x54)

// all buffers used

return false;

return true;

/*-----------------------------------*/

uint8_t mcp2515_send_message2(tCAN *message2)

uint8_t status = mcp2515_read_status(SPI_READ_STATUS);

printf("data=%x",status);

/* Statusbyte:

*

* Bit Function

* 2 TXB0CNTRL.TXREQ

* 4 TXB1CNTRL.TXREQ

* 6 TXB2CNTRL.TXREQ

*/

uint8_t address;

// mcp2515_write_register(TXB0CTRL,0x03);

if (bit_is_clear(status, 2))

69

Page 70: can

address = 0x00;

PRINT("In Transmit Buffer 0 mode\n\n");

else if (bit_is_clear(status, 4))

address = 0x02;

PRINT("In Transmit Buffer 1 mode\n\n");

else if (bit_is_clear(status, 6))

address = 0x04;

PRINT("In Transmit Buffer 2 mode\n\n");

else

// all buffer used => could not send message

return 0;

clrbit(PORTB,4);

spi_putc(SPI_WRITE_TX | address);

spi_putc(message2->id >> 3);

spi_putc(message2->id << 5);

spi_putc(0);

spi_putc(0);

uint8_t length = message2->header.length & 0x0f;

if (message2->header.rtr)

// a rtr-frame has a length, but contains no data

spi_putc((1<<RTR) | length);

70

Page 71: can

// set message length

spi_putc(length);

// data

for (uint8_t i=0;i<length;i++)

spi_putc(message2->data[i]);

setbit(PORTB,4);

clrbit(PORTB,4);

// send message

address = (address == 0) ? 1 : address;

spi_putc(SPI_RTS | address);

setbit(PORTB,4);

return address;

void DoorStatus(void)

Dtemp = PINC;

Dtemp = Dtemp & 0x0f;

switch(Dtemp)

case 0x00:

lcd_Line1();

lcd_string("All Doors Open ");

break;

case 0x01:

lcd_Line1();

lcd_string("Fr Fl Bl Open ");

break;

71

Page 72: can

case 0x02:

lcd_Line1();

lcd_string("Fl Bl Fr open ");

break;

case 0x03:

lcd_Line1();

lcd_string("Fl Bl open ");

break;

case 0x04:

lcd_Line1();

lcd_string("Fl Br Fr open ");

break;

case 0x05:

lcd_Line1();

lcd_string("Fl Br open ");

break;

case 0x06:

lcd_Line1();

lcd_string("Fl Fr open ");

break;

case 0x07:

lcd_Line1();

lcd_string("Fl open ");

break;

case 0x08:

lcd_Line1();

lcd_string("Bl Br Fr open ");

break;

case 0x09:

72

Page 73: can

lcd_Line1();

lcd_string("Bl Br open ");

break;

case 0x0A:

lcd_Line1();

lcd_string("Bl Fr open ");

break;

case 0x0B:

lcd_Line1();

lcd_string("Bl open ");

break;

case 0x0C:

lcd_Line1();

lcd_string("Br Fr open ");

break;

case 0x0D:

lcd_Line1();

lcd_string("Br open ");

break;

case 0x0E:

lcd_Line1();

lcd_string("Fr open ");

break;

case 0x0F:

lcd_Line1();

lcd_string("All Doors Close ");

break;

73

Page 74: can

void welcome_message(void)

lcd_Line1();

lcd_string("CAN Transmitter#2");

lcd_Line2();

lcd_string(" Door Status ");

_delay_ms(5000);

/*******************************************************************************/

/*******************************************************************************/

int main(void)

DDRC = 0x00;

DDRA = 0xff;

DDRD = 0xff;

DDRB = 0xff;

lcd_init();

tCAN message2;

// Initialisiere die UART Schnittstelle

uart_init(UART_BAUD_SELECT(9600UL, F_CPU));

setbit(PORTB,4);

sei();

// Umleiten der Standardausgabe => ab jetzt koennen wir printf() verwenden

stdout = &mystdout;

welcome_message();

// Versuche den MCP2515 zu initilaisieren

74

Page 75: can

if (!mcp2515_init())

PRINT("\n mcp 2515 not initilized\n");

for (;;);

else

PRINT("\n MCP2515 is active\n");

lcd_clr();

PRINT("Can Project\n");

// einige Testwerte

message2.id = 0xcc;

message2.header.rtr = 0;

message2.header.length = 8;

PRINT("Normal Mode\n\n");

mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);

while(1)

DoorStatus();

message2.data[0] = Dtemp;

if (mcp2515_send_message2(&message2))

PRINT("message send\n");

else

PRINT("message failed\n");

if (mcp2515_check_message())

75

Page 76: can

return 0;

z

10.4Receiver Code

#include <avr/io.h>

#include <avr/interrupt.h>

#include <avr/pgmspace.h>

#include <compat/deprecated.h>

#include <util/delay.h>

#include <stdio.h>

#include <inttypes.h>

#define PRINT(string, ...) printf_P(PSTR(string), ##__VA_ARGS__)

#define setbit(Port,Bit) Port |=(1<<Bit); //Macro to set a port bit

#define clrbit(Port,Bit) Port &= ~(1<<Bit); //Macro to clear a port bit

#include "lcd.h"

#include "uart.c"

#include "mcp2515.h"

#include "mcp2515_defs.h"

#include "global.h"

#include "defaults.h"

unsigned char temp=0,Dtemp;

void spi_reset(void);

void mcp2515_write_register(char addr, char data);

char mcp2515_read_register(char addr);

char spi_putc(char val);

void delay_3sec(void);

76

Page 77: can

uint8_t mcp2515_get_message1(tCAN *);

void print_can_message1(tCAN *);

void Display_names(void)

lcd_Line1();

lcd_string(" CAN Reciver ");

lcd_Line2();

lcd_string(" Section ");

void print_can_message(tCAN *message)

uint8_t length = message->header.length;

PRINT("id: 0x%3x\n", message->id);

PRINT("length: %d\n", length);

PRINT("rtr: %d\n", message->header.rtr);

if (!message->header.rtr)

PRINT("Time: ");

for (uint8_t i = 0; i < length; i++)

PRINT("%c ", message->data[i]);

void print_can_message2(tCAN *message)

uint8_t length = message->header.length;

PRINT("id: 0x%3x\n", message->id);

PRINT("length: %d\n", length);

77

Page 78: can

PRINT("rtr: %d\n", message->header.rtr);

if (!message->header.rtr)

PRINT("Door: ");

for (uint8_t i = 0; i < length; i++)

PRINT("%x ", message->data[i]);

Dtemp=message->data[0];

switch(Dtemp)

case 0x00:

lcd_Line2();

lcd_string("All Doors Open ");

break;

case 0x01:

lcd_Line2();

lcd_string("Fr Fl Bl Open ");

break;

case 0x02:

lcd_Line2();

lcd_string("Fl Bl Fr open ");

break;

case 0x03:

lcd_Line2();

lcd_string("Fl Bl open ");

break;

case 0x04:

lcd_Line2();

lcd_string("Fl Br Fr open ");

78

Page 79: can

break;

case 0x05:

lcd_Line2();

lcd_string("Fl Br open ");

break;

case 0x06:

lcd_Line2();

lcd_string("Fl Fr open ");

break;

case 0x07:

lcd_Line2();

lcd_string("Fl open ");

break;

case 0x08:

lcd_Line2();

lcd_string("Bl Br Fr open ");

break;

case 0x09:

lcd_Line2();

lcd_string("Bl Br open ");

break;

case 0x0A:

lcd_Line2();

lcd_string("Bl Fr open ");

break;

case 0x0B:

lcd_Line2();

lcd_string("Bl open ");

break;

79

Page 80: can

case 0x0C:

lcd_Line2();

lcd_string("Br Fr open ");

break;

case 0x0D:

lcd_Line2();

lcd_string("Br open ");

break;

case 0x0E:

lcd_Line2();

lcd_string("Fr open ");

break;

case 0x0F:

lcd_Line2();

lcd_string("All Door Close ");

break;

/*------------------------------------*/

void print_can_message1(tCAN *message)

uint8_t length = message->header.length;

PRINT("id: 0x%3x\n", message->id);

PRINT("length: %d\n", length);

PRINT("rtr: %d\n", message->header.rtr);

PRINT("\n");

PRINT("Date: ");

for (uint8_t i = 0; i<length;i++)

PRINT("%c ", message->data[(i)]);

80

Page 81: can

void print_can_message3(tCAN *message)

uint8_t length = message->header.length;

PRINT("id: 0x%3x\n", message->id);

PRINT("length: %d\n", length);

PRINT("rtr: %d\n", message->header.rtr);

PRINT("\n");

PRINT("Temp: ");

for (uint8_t i = 0; i<length;i++)

PRINT("%c ", message->data[(i)]);

static int putchar__(char c, FILE *stream)

uart_putc(c);

return 0;

static FILE mystdout = FDEV_SETUP_STREAM(putchar__, 0, _FDEV_SETUP_WRITE);

/******************************************************************/

void mcp2515_bit_modify(uint8_t adress, uint8_t mask, uint8_t data)

clrbit(PORTB,4);

spi_putc(SPI_BIT_MODIFY);

spi_putc(adress);

spi_putc(mask);

spi_putc(data);

setbit(PORTB,4);

81

Page 82: can

// ----------------------------------------------------------------------------

uint8_t mcp2515_read_status(uint8_t type)

uint8_t data;

clrbit(PORTB,4);

spi_putc(type);

data = spi_putc(0x00);

setbit(PORTB,4);

return data;

// -------------------------------------------------------------------------

bool mcp2515_init(void)

SET_INPUT(MCP2515_INT);

SET(MCP2515_INT);

SPCR = 0b01010000;

SPSR=1;

spi_reset();

mcp2515_write_register(0x0f,0x80);

temp=mcp2515_read_register(0x0e);

printf("\ncontrol reg=%X",temp);

// wait a little bit until the MCP2515 has restarted

_delay_us(10);

// load CNF1..3 Register

clrbit(PORTB,4);

spi_putc(SPI_WRITE);

spi_putc(CNF3);

spi_putc((1<<PHSEG21)); // Bitrate 125 kbps at 16 MHz

spi_putc((1<<BTLMODE)|(1<<PHSEG11));

82

Page 83: can

spi_putc((1<<BRP2)|(1<<BRP1)|(1<<BRP0));

// activate interrupts

spi_putc((1<<RX1IE)|(1<<RX0IE));

setbit(PORTB,4);

// test if we could read back the value => is the chip accessible?

if (mcp2515_read_register(CNF1) != ((1<<BRP2)|(1<<BRP1)|(1<<BRP0)))

return false;

// deaktivate the RXnBF Pins (High Impedance State)

mcp2515_write_register(BFPCTRL, 0);

// set TXnRTS as inputs

// mcp2515_write_register(TXRTSCTRL, 0);

// turn off filters => receive any message

mcp2515_write_register(RXB0CTRL, (1<<RXM1)|(1<<RXM0));

mcp2515_write_register(RXB1CTRL, (1<<RXM1)|(1<<RXM0));

// reset device to normal mode

mcp2515_write_register(CANCTRL, 0);

_delay_ms(10);

temp=mcp2515_read_register(0x0e);

printf("\nnormal mode=%X",temp);

return true;

/*---------------------------------------------*/

void spi_reset()

clrbit(PORTB,4);

SPDR = 0b11000000;

while( !( SPSR & (1<<SPIF) ) ) ;

// clear SPIF flag

SPSR = 0;

83

Page 84: can

setbit(PORTB,4);

void mcp2515_write_register(char addr, char data)

SPCR = 0b01010000;

clrbit(PORTB,4);

SPDR = 0b00000010;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = addr;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = data;

while( !( SPSR & (1<<SPIF) ) ) ;

// clear SPIF flag

SPSR= 0;

setbit(PORTB,4);

char mcp2515_read_register(char addr)

unsigned char data;

// set chip select low

SPCR = 0b01010000;

clrbit(PORTB,4);

SPDR = 0b00000011;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = addr;

while( !( SPSR & (1<<SPIF) ) ) ;

SPDR = 0x00;

while( !( SPSR & (1<<SPIF) ) ) ;

data = SPDR;

84

Page 85: can

// set chip select high

setbit(PORTB,4);

return data;

char spi_putc(char val)

SPDR =val;

while( !( SPSR & (1<<SPIF) ) ) ;

SPSR =0;

return SPDR;

/*-----------------------------------------------*/

// ----------------------------------------------------------------------------

// check if there are any new messages waiting

uint8_t mcp2515_check_message(void)

temp=mcp2515_read_register(0x30);

printf("\nTransmit control reg in check msg=%X\n",temp);

return (!IS_SET(MCP2515_INT));

// ----------------------------------------------------------------------------

uint8_t mcp2515_get_message(tCAN *message)

// read status

uint8_t status = mcp2515_read_status(SPI_RX_STATUS);

uint8_t addr;

// printf("\n satus reg=%X",status);

if (bit_is_set(status,6))

// message in buffer 0

85

Page 86: can

addr = SPI_READ_RX;

printf("\nmessage in buffer 0");

else if (bit_is_set(status,7))

// message in buffer 1

addr = SPI_READ_RX | 0x04;

printf("\nmessage in buffer 1");

else

// Error: no message available

printf("\nError: no message available");

return 0;

clrbit(PORTB,4);

spi_putc(addr);

// read id

message->id = (uint16_t) spi_putc(0xff) << 3;

message->id |= spi_putc(0xff) >> 5;

spi_putc(0xff);

spi_putc(0xff);

// read DLC

uint8_t length = spi_putc(0xff) & 0x0f;

message->header.length = length;

message->header.rtr = (bit_is_set(status, 3)) ? 1 : 0;

// read data

for (uint8_t i=0;i<length;i++)

86

Page 87: can

message->data[i] = spi_putc(0xff);

setbit(PORTB,4);

// clear interrupt flag

if (bit_is_set(status, 6))

mcp2515_bit_modify(CANINTF, (1<<RX0IF), 0);

else

mcp2515_bit_modify(CANINTF, (1<<RX1IF), 0);

return (status & 0x07) + 1;

/*------------------------------------*/

void delay_3sec(void)

long int i;

for(i=0;i<=0x9999;i++);

// ----------------------------------------------------------------------------

// Hauptprogram

int main(void)

// Initialisiere die UART Schnittstelle

uart_init(UART_BAUD_SELECT(9600UL, F_CPU));

DDRA = 0xFF;

DDRB = 0xff;

87

Page 88: can

DDRC=0xff;

/* sbi(PORTA,reset);

_NOP();

_NOP();

cbi(PORTA,reset);

_NOP();

_NOP();

sbi(PORTA,reset);*/

lcd_init();

// lcd_Clr();

Display_names();

_delay_ms(500);

// lcd_Clr();

// disp_string("CAN Receiver");

// Aktiviere Interrupts

// DDRB = 0b10111001;

setbit(PORTB,4);

sei();

// Umleiten der Standardausgabe => ab jetzt koennen wir printf() verwenden

stdout = &mystdout;

// Versuche den MCP2515 zu initilaisieren

if (!mcp2515_init())

PRINT("\n mcp 2515 not initilized\n");

lcd_Line1();

lcd_string("not initilized");

for (;;);

else

88

Page 89: can

PRINT("\n MCP2515 is active\n");

lcd_Line1();

lcd_string(" initilized");

tCAN message;

mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);

lcd_clr();

while (1)

if (mcp2515_check_message())

if (mcp2515_get_message(&message))

uint8_t length = message.header.length;

//print_can_message(&message);

if(message.id==0xaa)

print_can_message(&message);

lcd_Line1();

lcd_string("Temperature: ");

for (uint8_t i = 0; i < length; i++)

lcd_data_out(message.data[i]+0x30);

lcd_data_out('c');

if(message.id==0xcc)

89

Page 90: can

print_can_message2(&message);

return 0;

90

Page 91: can

SCHEMATIC

Y.T HIR UM A L A B A B U 1

M E S S AG E S T RE AM W IT H C ANC

1 1Th u rs d a y , F e b ru a ry 1 8 , 2 0 1 0

Tit le

S ize D o c u m e n t N u m b e r R e v

D a t e : S h e e t o f

V C C

V C C

V C C

V C CV C C

V C C

V C CV C C

V C C

V C C

V C C

V C C

V C C

V C C V C C V C CV C C

V C C

V C C

V C C

V C C

V C CV C C

V C C 1 2 V

1 2 V

1 2 V1 2 V

1 2 V

V C C1 2 V

V C C

V C C

V C C

V C C

V C C

V C C

V C C

V C C

V C C

V C C

V C C

V C C

V C C

V C C

V C C

V C C

TXDR XD

TE M P _ D A TATE M P _ C L K

C A N _ S C K

C A N _ C S

C A N _ I N T

C A N _ M O S I

C A N _ M I S O

F U A L 0

F U A L 2

F U A L 1

A D C _ C H 1A D C _ C H 0

C A N _ M O S I

C A N _ M I S O

C A N _ M O S IC A N _ M I S OC A N _ S C K

C A N _ S C K

C A N _ C S

S D _ C SS D _ M O S IS D _ C L KS D _ M I S OTE M P _ C L K

TE M P _ D A TA

D 3D 4D 5

D 2

D 0

D 7

D 1

D 6

A D C _ C H 0A D C _ C H 1

TXDR XD

R TC _ D A TAR TC _ C L K

C A N _ I N TI N TE R R U P T

TXDR XD

S D _ C SS D _ M O S IS D _ C L KS D _ M I S OTE M P _ C L K

TE M P _ D A TA

D 7D 6D 5D 4D 3D 2D 1D 0

I N TE R R U P TC A N _ I N T

R TC _ D A TAR TC _ C L K

C A N _ C S

C A N _ S C KC A N _ M I S OC A N _ M O S I

I N TE R R U P T

R TC _ C L K

R TC _ D A TA

I N TE R R U P T

A D C _ C H 4A D C _ C H 5A D C _ C H 6A D C _ C H 7A D C _ C H 3A D C _ C H 2

S D _ M I S O

S D _ C SS D _ M O S IS D _ C L K

A D C _ C H 0A D C _ C H 1

A D C _ C H 2A D C _ C H 3

A D C _ C H 4A D C _ C H 5

A D C _ C H 6A D C _ C H 7

D 0D 1

D 3D 2

D 0

D 1

D 2

D 3

O P _ A M P 1O P _ A M P 2O P _ A M P 3O P _ A M P 4

O P _ A M P 1

O P _ A M P 2

O P _ A M P 3

O P _ A M P 4

R S T

R S T

U 2

ATM EG A32

9

1 81 92 0

2 9

3031

4 0

12345678

2 1 2 22 32 42 52 62 72 8

1011

1 2

1 3

1 41 51 61 7

3 9

3 83 7

3 63 53 43 3

32

R S T

P D 4 (O C 1 B )P D 5 (O C 1 A )P D 6 (I C P 1 )

P C 7 (TO S C 2 )

AVCC

GND

P A 0 / A D C 0

P B 0 (XC K / T0 )P B 1 (T1 )P B 2 (I N T2 / A I N 0 )P B 3 (O C 0 / A I N 1 )P B 4 (S S )P B 5 (M O S I )P B 6 (M I S O )P B 7 (S C K )

P D 7 (O C 2 ) P C 0 (S C L )P C 1 (S D A )P C 2 (TC K )P C 3 (TM S )P C 4 (TD O )

P C 5 (TD I )P C 6 (TO S C 1 )

VCC

GND

XTA L 2

XTA L 1

P D 0 (R XD )P D 1 (TXD )P D 2 (I N T0 )P D 3 (I N T1 )

P A 1 / A D C 1

P A 2 / A D C 2P A 3 / A D C 3

P A 4 / A D C 4P A 5 / A D C 5P A 6 / A D C 6P A 7 / A D C 7

AREF

+

-

U 1 A

L M 3 2 4

3

21

411

C

R 1 9

1 0 K

123456789

C 1 9

1 0 u F / 2 5 V

C 1 1

1 0 0 P F

C 2 1 2 2 P F

C 1 8 2 2 P F

Y 3

3 2 . 7 6 8 k Z

U 3

L293D

27

1 01 5

19

361 11 4

16 8

4 5 13 12

1 A2 A3 A4 A

1,2EN

3,4EN

1 Y2 Y3 Y4 Y

VCC1

VCC2

GND

GND

GND

GND

C 2

0 . 1 u F

J 1

MOTOR3

12

J 3

MOTOR4

12

J P 3

J U M P E R

1 2

R 2 1 1 KD 2

1 N 4 0 0 7

1 2

J 1 8

C O N 1 0 A P

13579

24681 0

13579

2468

1 0

U 7

MAX232

1 3

8

1 1

1 0

1

3

4

5

26

1 2

9

1 4

7

1615

R 1 I N

R 2 I N

T1 I N

T2 I N

C +

C 1 -

C 2 +

C 2 -

V+V-

R 1 O U T

R 2 O U T

T1 O U T

T2 O U T VCC

GND

C 2 61 0 u F / 2 5 V

C 2 20 . 1 u F

C 2 71 0 u F / 2 5 V

+

-

U 1 B

L M 3 2 4

5

67

411

J 4

PORT A

12345678

U 1 0 LM 7805

1

2

3V I N

GND

V O U T

C

R 5

1 0 K

123456789

B T1

3 . 3 V

12

J 1 1

C O N 2

1

2

R 41 0 K

13

2

C 2 50 . 1 u F

U 6

S HT1x

41

32

5678

VDD

GND

C L KD A TA

N CN CN CN C

J 1 7

C O N 2

1

2

U 9 LM 7812

1

2

3V I N

GND

V O U T

J 9

PORT B

12345678

C

R 1 7

1 0 K

123456789

U 8

D S 1 3 0 74

7

5

1

26

3

8GN

D

S Q W / O U T

S D A

X1

X2S C L K

V B A T

VCC

J 7

C O N 3

123

R 1 61 0 K

R 1 41 0 K

C 1 70 . 1 u F

C 60 . 1 u F

+

-

U 1 D

L M 3 2 4

1 2

1 31 4

411

C 90 . 1 u F

U 1 1

A T2 4 C 2 5 6

123

4

5

67

8

A 0A 1A 2

G N D

S D A

S C L KW P

VCC

-+

D 5

B R I D G E

2

1

3

4

S W 3

O N / O F F S W I TC H

1 2

J 2 1

C O N 2

12

R 31 0 K

J 1 3

C H A N N E L 1

123

D 43 M M

J 2 3

C O N 2

12

D 6

L E D

R 2 33 3 0 E

J 1 4

I /O P IN

123

R 1

1 0 K

13

2

R 2 42 2 0 H

+

-

U 1 C

L M 3 2 4

1 0

98

411

C 2 31 0 u F / 2 5 V

J 2 4

C O N 2

12

J 1 6

C O N 2

1

2

C 2 80 . 1 u F

P 1

D -TY P E F e m a le

594837261

J 2 5

C O N 2

12

C 2 40 . 1 u F

D 33 M M

R 2 2 4 . 7 K

J 2 6

C O N 2

12

C 1 5

1 0 u F / 2 5 V

C 5 2 2 P F

C 4 2 2 P F

Y 1

1 6 M h z

J 1 5

SD CARD

12

3

45

6

7

89

J P 5

J U M P E R

1 2

J 2 2

C O N 2

12

J 2 0

C O N 2

12

J 2

LCD

1

2

3

9

5

1 0

1 11 21 31 4

46

78

1 5

1 6

R 1 0

1 0 k

R 9

1 0 k

J 1 9

C O N 2

12

C 31 0 u F / 2 5 V

S W 1 R S T S W

1 2

R 61 0 K

C 1 6

0 . 1 u F

S W 2 R S T S W

1 2

J 1 2

PORT C

12345678

R 2

1 0 K

13

2

R 1 3

1 0 k

R 1 1

1 0 k

R 1 2

1 0 k

J 6

PORT D

12345678

C

R 8

1 0 K

123456789

R 2 0

1 0 0 E

D 13 M M

C 2 0

1 0 u F / 2 5 V

U 4

M C P 2 5 1 5

1

2

3

456

7

8

9

1 01 1

1 2

1 3

1 4

1 5

1 6

1 7

18

TXC A N

R XC A N

C L K O U T/ S O F

TX0 R TSTX1 R TSTX2 R TS

O S C 2

O S C 1

VSS

R X1 B FR X0 B F

I N T

S C K

S I

S O

C S

R E S E T

VDD

J 5

C O N 4

1234

U 5

M C P 2 5 5 1

1

23

4

5

6

7

8

TXD

VSS

VDD

R XD

V R E F

C A N L

C A N H

R S

R 1 8

6 0 E

J P 21 2

J P 11 2

J 8

C H A N N E L 2

123

J P 41 2

J 1 0

C O N 2

1

2

R 2 5 1 K

R 2 6 1 K

C 81 0 u F / 2 5 V

R 1 58 . 2 K

C 1 40 . 1 u F

C 1 0

0 . 1 u F

C 70 . 1 u F

C 1 3 2 2 P F

C 1 2 2 2 P F

Y 2

2 5 M h z

C 10 . 1 u F

R 7

1 0 K

13

2

POWERSUPPLY

CAN CONTROLLER & TRNSCEIVER

SERIAL COMMUNICATION

FUAL INDICATOR

ADC CHANNELS

TEMPRATURE & HUMIDITY SENSOR

SPI IN SYSTEM PROGRAMMING

91

Page 92: can

92

Page 93: can

CONCLUSION

In this project we had measured the temperature and door status of the car by using CAN (Controller Area Network)protocol. It can also extended to RTC(Real Time Control), window status of the car,MP3 player status etc.

CAN (Controller Area Network) is a serial bus system. CAN was originally designed for automotive applications and it is a serial bus system especially suited for networking "intelligent" devices as well as sensors and actuators within a machine or plant. Due to its excellent technical and commercial properties CAN is used today in a wide range of applications, eg. Mobile systems, machine and auto mobiles.

93

Page 94: can

BIBLIOGRAPHY

Reffered Books

1.AVR MICROCONTROLLER

- ATMEL

2.CAN

-MOTOROLA

3.CAN

-BOSCH

4. CANopen

-H. Boterenbrood

5.CAN TUTORIAL

-ATMEL

Reffered Links

1.WWW.WIKIPEDIA.COM

2.WWW.GOOGLE.COM

3.WWW.ATMEL.COM

94