SYNOPSIS
The main aim of the project is to control the whole system in a single module .In this project RTC(Real Time Clock), ADC,Serial Communication, Calculator are design and develop in a single module. In this Project the Real Time Clock is to show the current Time and Date, month Year Everything display in the LCD Screen. Then the other Module ADC Part 12bit Resolution, any given analog input is given the corresponding digital output is converted, and display in the LCD Screen.
Then the Serial communication part the string “HELLO” is Serially transmitted for the baud rate 9600. In this serial communication section any wireless protocol like ZIGBEE or R.F, Blue tooth and other protocol is used to receive same Baud Rate the Original Transmitted string is receive and display in the LCD Screen.
The main part of the Project is Calculator in this calculator part the Two operations like Addition and Subtraction is successfully developed. In this calculator section single bit addition, subtraction is done with a fraction of a second. In this all application module is control by the 3*4 matrix keypad, the key 1 is pressed the calculator operation is run, key 2 is pressed ADC, Key 3 Serial Communication, Key 4 RTC Vice Versa.,
CONTENTS
CHAPTER 1 : INTRODUCTION Page No
1.1 Objective 1
1.2 General Block Diagram 1
1.3 Domain of the Project 2
1.4 Components Required 2
1.5 Introduction to Embedded System 3
CHAPTER 2 : MICROCONTROLLER
2.1General Description 5
2.2 Features 6
2.3 Block Diagram 7
2.4 Pin Diagram and Description 8
2.5 Special Function Register & Timers 11
2.6 Flash Organization & Functional Description 12
CHAPTER 3 : RAISONANCE INTEGRATED
DEVELOPMENT ENVIRONMENT (RIDE)
3.1 Multi-file Editor 16
3.2 Project Manager 16
3.3 Advanced Features 19
CHAPTER 4 : FLASH MAGIC
4.1 Introduction 21
4.2 Minimum requirements 22
4.3 Main Window 22
4.4 Five Step Programming 24
CHAPTER 5 : TEMPERATURE SENSOR – LM35
5.1 Description 31
5.2 Features 31
5.3 Sensor Operation 32
5.4 Advantages 32
CHAPTER 6 : A/D CONVERTER – MCP3202
6.1 General Description 34
6.2 Features 34
6.3 Pin Diagram 34
6.4 Functional Diagram 35
6.5 ADC Serial Communication 37
6.6 Applications 38
CHAPTER 7 : REAL TIME CLOCK DS1307
7.1 General Description 40
7.2 Features 40
7.3 Pin Diagram 40
7.4 Functional Diagram 42
7.5 Communication 43
CHAPTER 8 : SERIAL PERIPHERAL INTERFACE (SPI)
8.1 Introduction 46
8.2 SPI Bus Configuration 46
8.3 SPI Registers 48
8.4 SPI Advantages and Disadvantages 49
CHAPTER 9 : INTER –INTEGRATED CIRCUIT (I2C)
9.1 Introduction 51
9.2 I2C Bus Configuration 51
9.3 I2C Communication 52
9.4 I2C Implementation types 52
CHAPTER 10 : CIRCUIT DIAGRAM WITH OPERATION
10.1 Circuit Diagram 57
10.2 Operation 58
10.3 Program Coding 59
10.4 Conclusion 73
CHAPTER 1
INTRODUCTION
INTRODUCTION
1.1 OBJECTIVE
The objective of this project is to perform four type of task one is Real Time Clock, Adc, Serial Communication, Calculator and the other using I2C Protocol.
1.2 GENERAL BLOCK DIAGRAM
1.3 DOMAIN OF THE PROJECT
AT89S52 Microcontroller acts as the heart of the project which has its own in built memory for the controlling operation.. LM35 is used as a temperature sensor that senses the appropriate temperature level in 0 C .MCP 3202 A/D converter is used for analog signal to digital signal conversion. DS1307 is used as a real time clock, which counts seconds, minutes, hours, date, day, month and year. Keypad using to perform Calculator Function, LCD is used to display the message.
1.4 COMPONENTS REQUIRED
HARDWARE:
AT89S52 (Micro controller)
LM35
MCP 3202
DS1307
Power Supply
SOFTWARE
RIDE v6.1.6
Flash magic v3.21.116
1.5 INTRODUCTION TO EMBEDDED SYSTEM
Embedded System is one that has computer- hardware with software embedded in it as one of its most important component.
CHARACTERISTICS
Efficient reliability
Small size
Low cost
High performance
Easy upgradeability
TYPES OF EMBEDDED SYSTEMS
Small scale
Medium scale
Large scale
APPLICATIONS OF EMBEDDED SYSTEM
Household appliances including microwave ovens, washing machines, television sets, DVD players/recorders
Measurement equipment such as digital storage oscilloscopes, logic analyzers, and spectrum analyzers
Programmable logic controllers (PLCs) for industrial automation and monitoring
CHAPTER 2
AT89S52 MICRO CONTROLLER
AT89S52 MICRO CONTROLLER
2.1 GENERAL DESCRIPTION
The AT89S8252 is a low-power, high-performance CMOS 8-bit microcomputer with 8K bytes of downloadable Flash programmable and erasable read only memory and 2K bytes of EEPROM. The device is manufactured using Atmel’s high-density nonvol-atile memory technology and is compatible with the industry-standard 80C51 instruction set and pinout.
The on-chip downloadable Flash allows the program mem-ory to be reprogrammed in-system through an SPI serial interface or by a conventional nonvolatile memory programmer. By combining a versatile 8-bit CPU with downloadable Flash on a monolithic chip, the Atmel AT89S8252 is a powerful microcomputer which provides a highly-flexible and cost-effective solution to many embedded control applications.
The AT89S8252 provides the following standard features: 8K bytes of downloadable Flash, 2K bytes of EEPROM, 256 bytes of RAM, 32 I/O lines, programmable watch-dog timer, two data pointers, three 16-bit timer/counters, a six-vector two-level interrupt architecture, a full duplex serial port, on-chip oscillator, and clock circuitry.
In addition, the AT89S8252 is designed with static logic for operation down to zero fre-quency and supports two software selectable power saving modes. The Idle Mode stops the CPU while allowing the RAM, timer/counters, serial port, and interrupt sys-tem to continue functioning. The Power-down mode saves the RAM contents but freezes the oscillator, disabling all other chip functions until the next interrupt or hard-ware reset.
The downloadable Flash can be changed a single byte at a time and is accessible through the SPI serial interface. Holding RESET active forces the SPI bus into a serial programming interface and allows the program memory to be written to or read from unless Lock Bit 2 has been activated.
2.2 FEATURES
• Compatible with MCS-51™ Products 8K Bytes of In-System Reprogrammable Downloadable Flash Memory
– SPI Serial Interface for Program Downloading
– Endurance: 1,000 Write/Erase Cycles
• 2K Bytes EEPROM
– Endurance: 100,000 Write/Erase Cycles
• 4V to 6V Operating Range
• Fully Static Operation: 0 Hz to 24 MHz
• Three-level Program Memory Lock
• 256 x 8-bit Internal RAM
• 32 Programmable I/O Lines
• Three 16-bit Timer/Counters
• Nine Interrupt Sources
• Programmable UART Serial Channel
• SPI Serial Interface
• Low-power Idle and Power-down Modes
• Interrupt Recovery From Power-down
• Programmable Watchdog Timer
• Dual Data Pointer
• Power-off Flag
2.3 BLOCK DIAGRAM
2.4 PIN DIAGRAM AND DESCRIPTION
PIN DESCRIPTION
VCC :Supply voltage.
GND :Ground.
PORT 0
Port 0 is an 8-bit open drain bbi-didirectional I/O port. As an output port, each pin can sink eight TTL inputs. When 1s are written to port 0 pins, the pins can be used as high-impedance inputs.
Port 0 can also be configured to be the multiplexed low-order address/data bus during accesses to external program and data memory. In this mode, P0 has internal pullups. Port 0 also receives the code bytes during Flash program-ming and outputs the code bytes during program verification. External pullups are required during program verification.
PORT 1
Port 1 is an 8-bit bi-directional I/O port with internal pullups. The Port 1 output buffers can sink/source four TTL inputs. When 1s are written to Port 1 pins, they are pulled high by the internal pullups and can be used as inputs. As inputs, Port 1 pins that are externally being pulled low will source current (IIL) because of the internal pullups. Some Port 1 pins provide additional functions. P1.0 and P1.1 can be configured to be the timer/counter 2 external count input (P1.0/T2) and the timer/counter 2 trigger input (P1.1/T2EX), respectively. Port 1 also receives the low-order address bytes during Flash programming and verification
PORT 2
Port 2 is an 8-bit bi-directional I/O port with internal pullups.The Port 2 output buffers can sink/source four TTL inputs.When 1s are written to Port 2 pins, they are pulled high by the internal pullups and can be used as inputs. As inputs, Port 2 pins that are externally being pulled low will source current (IIL) because of the internal pullups. Port 2 emits the high-order address byte during fetches from external program memory and during accesses to external data memory that use 16-bit addresses (MOVX @ DPTR). In this application, Port 2 uses strong internal pul-lups when emitting 1s. During accesses to external data memory that use 8-bit addresses (MOVX @ RI), Port 2 emits the contents of the P2 Special Function Register. Port 2 also receives the high-order address bits and some control signals during Flash programming and verification.
PORT 3
Port 3 is an 8 bit bi-directional I/O port with internal pullups.The Port 3 output buffers can sink/source four TTL inputs.When 1s are written to Port 3 pins, they are pulled high by the internal pullups and can be used as inputs. As inputs,Port 3 pins that are externally being pulled low will source current (IIL) because of the pullups. Port 3 also receives some control signals for Flash pro-gramming and verification.
PROGRAM STORE ENABLE
PSEN is the read strobe for external program memory. When the device is executing from internal program memory, PSEN is inactive (HIGH). When the device is executing code from external program memory, PSEN is activated twice each machine cycle, except that two PSEN activations are skipped during each access to external data memory.
RESET
While the oscillator is running, a HIGH logic state on this pin for two machine cycles will reset the device. If the PSEN pin is driven by a HIGH-to-LOW input transition while the RST input pin is held HIGH, the device will enter the external host mode; otherwise the device will enter the normal operation mode.
EXTERNAL ACCESS ENABLE
EA must be strapped to GND in order to enable the device to fetch code from external program memory locations starting at 0000H up to FFFFH, if lock bit 1 is programmed, EA will be internally latched on reset. EA should be strapped to VCC for internal program execu-tions. This pin also receives the 12-volt programming enable voltage (VPP) during Flash programming when 12-volt programming is selected.
ADDRESS LATCH ENABLE
ALE is the output signal for latching the low byte of the address during an access to external memory. This pin is also the programming pulse input (PROG) for flash programming. Normally the ALE is emitted at a constant rate of 1/6 the crystal frequency and can be used for external timing and clocking. One ALE pulse is skipped during each access to external data memory. However, if AO is set to ‘1’, ALE is disabled.
XTAL1
Input to the inverting oscillator amplifier and input to the internal clock operating circuit.
XTAL2
Output from the inverting oscillator amplifier.
2.5 SPECIAL FUNCTION REGISTER & TIMERS
2.5.1 SPECIAL FUNCTION REGISTER
SPI Registers
Control and status bits for the Serial Periph-eral Interface are contained in registers SPCR (shown in Table 4) and SPSR (shown in Table 5). The SPI data bits are contained in the SPDR register. Writing the SPI data register during serial data transfer sets the Write Collision bit, WCOL, in the SPSR register. The SPDR is double buff-ered for writing and the values in SPDR are not changed by Reset.
Interrupt Registers
The global interrupt enable bit and the individual interrupt enable bits are in the IE register. In addition, the individual interrupt enable bit for the SPI is in the SPCR register. Two priorities can be set for each of the six interrupt sources in the IP register.
Dual Data Pointer Registers
To facilitate accessing both internal EEPROM and external data memory, two banks of 16 bit Data Pointer Registers are provided: DP0 at SFR address locations 82H-83H and DP1 at 84H-85H. Bit DPS = 0 in SFR WMCON selects DP0 and DPS = 1 selects DP1. The user should always initialize the DPS bit to the appropriate value before accessing the respective Data Pointer Register.
Power Off Flag
The Power Off Flag (POF) is located at bit_4 (PCON.4) in the PCON SFR. POF is set to “1” during power up. It can be set and reset under software control and is not affected by RESET.
2.5.2 TIMERS
Programmable Watchdog Timer
The programmable Watchdog Timer (WDT) operates from an independent oscillator. The prescaler bits, PS0, PS1 and PS2 in SFR WMCON are used to set the period of the Watchdog Timer from 16 ms to 2048 ms. The available timer periods are shown in the following table and the actual timer periods (at VCC = 5V) are within ±30% of the nominal. The WDT is disabled by Power-on Reset and during Power-down. It is enabled by setting the WDTEN bit in SFR WMCON (address = 96H). The WDT is reset by setting the WDTRST bit in WMCON. When the WDT times out without being reset or disabled, an internal RST pulse is generated to reset the CPU.
Timer 0 and 1
Timer 0 and Timer 1 in the AT89S8252 operate the same way as Timer 0 and Timer 1 in the AT89C51, AT89C52 and AT89C55.
Timer 2
Timer 2 is a 16 bit Timer/Counter that can operate as either a timer or an event counter. The type of operation is selected by bit C/T2 in the SFR T2CON (shown in Table 2). Timer 2 has three operating modes: capture, auto-reload (up or down counting), and baud rate generator. The modes are selected by bits in T2CON, as shown in Table 8. Timer 2 consists of two 8-bit registers, TH2 and TL2. In the Timer function, the TL2 register is incremented every machine cycle. Since a machine cycle consists of 12 oscil-lator periods, the count rate is 1/12 of the oscillator frequency.
2.6 MEMORY ORGANIZATION
Programming the Flash and EEPROM
Atmel’s AT89S8252 Flash Microcontroller offers 8K bytes of in-system reprogrammable Flash Code memory and 2K bytes of EEPROM Data memory. The AT89S8252 is normally shipped with the on-chip Flash Code and EEPROM Data memory arrays in the erased state (i.e. contents = FFH) and ready to be programmed. This device supports a High-voltage (12V) Parallel pro-gramming mode and a Low-voltage (5V) Serial programming mode. The serial programming mode pro-vides a convenient way to download the AT89S8252 inside the user’s system. The parallel programming mode is com-patible with conventional third party Flash or EPROM programmers.
The Code and Data memory arrays are mapped via sepa-rate address spaces in the serial programming mode. In the parallel programming mode, the two arrays occupy one contiguous address space: 0000H to 1FFFH for the Code array and 2000H to 27FFH for the Data array.
The Code and Data memory arrays on the AT89S8252 are programmed byte-by-byte in either programming mode. An auto-erase cycle is provided with the self-timed program-ming operation in the serial programming mode. There is no need to perform the Chip Erase operation to reprogram any memory location in the serial programming mode unless any of the lock bits have been programmed.
In the serial programming mode, a chip erase operation is initiated by issuing the Chip Erase instruction. In this mode, chip erase is self-timed and takes about 16 ms. During chip erase, a serial read from any address location will return 00H at the data outputs. In the parallel programming mode, there is no auto-erase cycle. To reprogram any non-blank byte, the user needs to use the Chip Erase operation first to erase both arrays
Programming Interface
Every code byte in the Flash and EEPROM arrays can be written, and the entire array can be erased, by using the appropriate combination of control signals. The write oper-ation cycle is self-timed and once initiated, will automatically time itself to completion.
Serial Programming Algorithm
To program and verify the AT89S8252 in the serial pro-gramming mode, the following sequence is recommended:
1. Power-up sequence: Apply power between VCC and GND pins.
Set RST pin to “H”.
If a crystal is not connected across pins XTAL1 and XTAL2, apply a 3 MHz to 24 MHz clock to XTAL1 pin and wait for at least 10 milliseconds.
2. Enable serial programming by sending the Pro-gramming Enable serial instruction to pin MOSI/P1.5. The frequency of the shift clock sup-plied at pin SCK/P1.7 needs to be less than the CPU clock at XTAL1 divided by 40.
3. The Code or Data array is programmed one byte at a time by supplying the address and data together with the appropriate Write instruction. The selected memory location is first automatically erased before new data is written. The write cycle is self-timed and typically takes less than 2.5 ms at 5V.
4. Any memory location can be verified by using the Read instruction which returns the content at the selected address at serial output MISO/P1.6.
5. At the end of a programming session, RST can be set low to commence normal operation.
Power-off sequence (if needed): Set XTAL1 to “L” (if a crystal is not used).
Set RST to “L”.
Turn VCC power off.
The data RAM has 1024 bytes of internal memory.
The device can also address up to 64 Kb for external data memory.
Serial Downloading
Both the Code and Data memory arrays can be pro-grammed using the serial SPI bus while RST is pulled to VCC. The serial interface consists of pins SCK, MOSI (input) and MISO (output). After RST is set high, the Programming Enable instruction needs to be executed first before pro-gram/erase operations can be executed. An auto-erase cycle is built into the self-timed programming operation (in the serial mode ONLY) and there is no need to first execute the Chip Erase instruction unless any of the lock bits have been programmed. The Chip Erase opera-tion turns the content of every memory location in both the Code and Data arrays into FFH. The Code and Data memory arrays have separate address spaces
CHAPTER 3
RAISONANCE INTEGRATED DEVELOPMENT ENVIRONMENT (RIDE)
RAISONANCE INTEGRATED DEVELOPMENT ENVIRONMENT
(RIDE)
RIDE is a fully featured Integrated Development Environment that provides seamless integration and easy access to all the development tools. From editing to compiling, linking, debugging and back to the start, with a Simulator, ICE, Rom Monitor or other debugging tool, RIDE conveniently manages all aspects of the Embedded Systems development with a single user interface.
3.1 MULTI-FILE EDITOR
RIDE is based on a fast multi-document editor designed to meet the specific needs of programming. The various methods, menus, commands, and shortcuts are all fully compliant with the Microsoft® specifications for Windows 2000, XP and NT. Classic commands, such as string search and block action are integrated. Advanced features such as Matching Delimiter (parenthesis, brackets), Grep (multi-file search) and Indenter are integrated as well. The customizable color-highlighting feature is very useful to indicate specific syntactic elements as they appear in the source file: keywords, comments, identifiers, operators, and so on. The color-highlighting feature is automatically keyed to the intrinsic file type (that is, it works differently for C and assembler).This permits the user to identify quickly and easily those parts of the code responsible for syntax errors.
3.2 PROJECT MANAGER
The project manager creates links between the various files that comprise a project and the tools necessary to create that project. A project is dedicated to a particular target: 8051, XA, ST7, STR7, ST6, ST5 or other microcontrollers. The linker manages object and library files, and output format conversion as necessary. Tree-structured projects ease the management of the most complex applications (bank switching, flash, multi-processor, multi-module…).
The 'Project | Make' command directs the integrated "make" utility to build or rebuild the target programs for the current project. To avoid wasting time, each source file will be translated by its associated tool only if any of its dependencies are found to be out of date. Dependency analysis, even of directly or indirectly included files, is automatic. Options can be defined as global (for all the files) or as local (for a specific node or file). Individual attributes can be set for any file in the project. Similarities between the different tools make migration from one processor family to another immediate and easy, permitting multi-processor.
3.2.1 THE MESSAGE WINDOW AND THE ON-LINE HELP
The message window displays all warning, error, and progress messages generated during the processing of files associated with each project. Clicking on an error string in the message window automatically positions the cursor at the point of that error in the source code window.
Online Help Menu
The Online help system is context-sensitive and provides information on nearly all aspects of RIDE. A specific help file is supplied with each tool driven by the IDE ('C' Compiler, Assembler, Linker and RTOS).Online menu hints appear on the status line whenever you select a menu command.
3.2.2 THE SCRIPT LANGUAGE
Most RIDE commands can be run from a script file. Scripts are written in a C-like language, and are interpreted at execution time. With the script language, most repetitive tasks can be done automatically thus speeding up operations and reducing the probability of errors.
Scripts are very useful for Hardware Testing (board, emulator) and to initialize the system to a known status, but can be conveniently used also for other tasks such as creating very complex breakpoints or redirecting some output to a file to run a 'batch' debug session.
CONTEXT SAVING
When a project is closed, the whole associated context is saved (open file list, window size and position etc...).Settings associated with the debugger are also saves such as breakpoints, watches etc...
3.2.3 INTEGRATED HIGH-LEVEL DEBUG
RIDE provides a fully integrated source-level debugging environment. All information necessary is derived from the translators used to accomplish each step of the process. This is the heart of RIDE,
Program Window
This includes mundane aspects such as "path names", and source code specific information such as details of complex data types. With the simple click of a mouse button, the user can select among several powerful capabilities: simulate, monitor, or emulate. The fast smooth integration afforded by RIDE promotes a feeling of familiarity and ease of use, while providing a level of comfort and efficiency that reduces the most difficult and complex applications to tasks that are easily managed.
This seamless progression of the "code-translate-link-debug-test" cycle is the result of perfect communication between the programming tools and the debugger.
3.2.4. INTEGRAL SIMULATION
RIDE includes simulation engines for most 8051, XA and ST6 derivatives. The simulator/debugger is cleanly integrated into the presentation Windows. A wide range of 'views' can be selected to provide flexible direct examination of all memory spaces as well the all internal peripherals.
The simulation engines perform detailed and faithful simulations (including IDLE or Power down modes), of all peripherals—including interrupt and watchdog events—present on the selected component.
3.3 ADVANCED FEATURES
RIDE provides a rich variety of 'views' into an application. These views or windows are associated with control commands like complex breakpoints or high level trace recording.
Trace Window
CHAPTER 4
FLASH MAGIC
FLASH MAGIC
4.1 INTRODUCTION
NXP Semiconductors produce a range of Microcontrollers that feature both on-chip Flash memory and the ability to be reprogrammed using In-System Programming technology.
Flash Magic is Windows software from the Embedded Systems Academy that allows easy access to all the ISP features provided by the devices. These features include,
Erasing the Flash memory (individual blocks or the whole device)
Programming the Flash memory
Modifying the Boot Vector and Status Byte
Reading Flash memory
Performing a blank check on a section of Flash memory
Reading the signature bytes
Reading and writing the security bits
Direct load of a new baud rate (high speed communications)
Sending commands to place device in Boot loader mode
Flash Magic provides a clear and simple user interface to these features and more as described in the following sections. Under Windows, only one application may have access the COM Port at any one time, preventing other applications from using the COM Port.
Flash Magic only obtains access to the selected COM Port when ISP operations are being performed. This means that other applications that need to use the COM Port, such as debugging tools, may be used while Flash Magic is loaded. Note that in this manual third party Compilers are listed alphabetically. No preferences are indicated or implied.
4.2 MINIMUM REQUIREMENTS
Windows 95/98/ME/NT/2000/XP
Mouse
COM Port
16Mb RAM
3Mb Disk Space
4.3 MAIN WINDOW
The following is a screenshot of the main Flash Magic window. The appearance may differ slightly depending on the device selected. The window is divided up into five sections. Work your way from section 1 to section 5 to program a device using the most common functions. Each section is described in detail in the following sections. At the very bottom left of the window is an area where progress messages will be displayed and at the very bottom right is where the progress bar is displayed.
Main Window
In between the messages and the progress bar is a count of the number of times the currently selected hex file has been programmed since it was last modified or selected. Just above the progress information embedded hints are displayed. These are rotating Internet links that you can click on to go to a web page using your default browser. If you wish to quickly flick through all the hints then you can click on the fast forward button: Progress information Progress bar Section 1 includes
Embedded Hints
Menus
Programmed Count
Flash Magic User Manual
4.3.1 MENUS
There are five menus, File, ISP, Options, Tools and Help. The File menu provides access to loading and saving Hex Files, loading and saving settings files and exiting the application. The ISP menu provides access to the less commonly used ISP features. The Options menu allows access to the advanced options and includes an item to reset all options. The Tools menu provides features that support the operation and use of Flash Magic.
The Help menu contains items that link directly to useful web pages and also open the Help About window showing the version number. The Loading and Saving of Hex Files and the other ISP features are described in the following sections.
4.3.2 TOOL TIPS
Tool window
Throughout the Flash Magic user interface extensive use has been made of tool tips. These are small text boxes that appear when you place the pointer over something and keep it still for a second or two. Note that tool tips do not appear for items that are disabled (grayed out).
4.3.3 SAVING OPTIONS
The options in the main window and the Advanced Options window are automatically saved to the registry whenever Flash Magic is closed. This removes the need for an explicit save operation.
When Flash Magic is restarted the main window and the Advanced Options window will appear as you left it, so you do not have to repeatedly make the same selections every time you start the application. If you wish to reset the options to the original defaults then choose Reset from the Options menu.
4.4 FIVE STEP PROGRAMMING
For each step there is a corresponding section in the main window as described in the User Interface Tour.
4.4.1 STEP 2-CONNECTION SETTINGS
Before the device can be used the settings required to make a connection must be specified. Select the desired COM port from the drop down list or type the desired COM port directly into the box.
If you enter the COM port yourself then you must enter it in one of the following formats:
COM n
n
Any other format will generate an error. So if you want to use COM 5 (which is not present on the drop down list) you can directly type in either “COM 5” or “5”.Select the baud rate to connect at. Try a low speed first. The maximum speed that can be used depends on the crystal frequency on your hardware. You can try connecting at higher and higher speeds until connections fail. Then you have found the highest baud rate to connect at. Alternatively, some devices support high speed communications. Please refer to the High-Speed Communications section for information.
Select the device being used from the drop down list. Ensure you select the correct one as different devices have different feature sets and different methods of setting up the serial communications. Select the interface being used, if any.
Step 1
An interface is a device that connects between your PC and the target hardware. If you simply have a serial cable or USB to serial cable connecting your COM port to the target hardware, then chooses "None (ISP)".
Choosing the correct interface will automatically configure Flash Magic for that interface, along with enabling and disabling the relevant features.
Enter the oscillator frequency used on the hardware. Do not round the frequency, instead enter it as precisely as possible. Some devices do not require the oscillator frequency to be entered, so this field will not be displayed.
Once the options are set ensure the device is running the on-chip Boot loader if you are using a manual ISP entry method. Note that the connection settings affect all ISP features provided by Flash Magic.
4.4.2 STEP 2-ERASING
This step is optional, however if you attempt to program the device without first erasing at least one Flash block, then Flash Magic will warn you and ask you if you are sure you want to program the device. Select each Flash block that you wish to erase by clicking on its name. If you wish to erase all the Flash then check that option. If you check to erase a Flash block and all the Flash, then the Flash block will not be individually erased.
Step 2
If you wish to erase only the Flash blocks used by the hex file you are going to select, then check that option. For most devices erasing all the Flash also results in the Boot Vector and Status Byte being set to default values, which ensure that the Boot loader will be executed on reset, regardless of the state of the PSEN pin or other hardware requirements.
Only when programming a Hex File has been completed will the Status Byte be set to 00H to allow the code to execute. This is a safeguard against accidentally attempting to execute when the Flash is erased. On some devices erasing all the Flash will also erase the security bits.
This will be indicated by the text next to the Erase all Flash option. On some devices erasing all the Flash will also erase the speed setting of the device (the number of clocks per cycle) setting it back to the default. This will be indicated by the text next to the Erase all Flash option.
4.4.3 STEP 3-SELECTING THE HEX FILES
This step is optional. If you do not wish to program a Hex File then do not select one. You can either enter a path name in the text box or click on the Browse button to select a Hex File by browsing to it.
Also you can choose Open… from the File menu. Note that the Hex file is not loaded or cached in any way. This means that if the Hex File is modified, you do not have to reselect it in Flash Magic. Every time the Hex File is programmed it is first re-read from the location specified in the main window. The date the Hex file was last modified is shown in this section.
Step 3
This information is updated whenever the hex file is modified. The hex file does not need to be reselected. Clicking on more info or choosing Information… from the File menu will display additional information about the Hex file.
The information includes the range of Flash memory used by the Hex file, the number of bytes of Flash memory used and the percentage of the currently selected device that will be filled by programming the Hex file. If the device supports programming and execution from RAM, for example the ARM devices, then the hex file may contain records for the RAM. First the flash will be programmed followed by the RAM. Programs loaded into RAM via a hex file may be executed using such features as the Go option. See chapter 6 for more details.
4.4.4 STEP 4-OPTIONS
Flash Magic provides various options that may be used after the Hex File has been programmed. This section is optional, however Verify After Programming, Fill Unused Flash and Gen Block Checksums may only be used if a Hex File is selected (and therefore being programmed), as they all need to know either the Hex File contents or memory locations used by the Hex File.
Checking the Verify after Programming option will result in the data contained in the Hex File being read back from Flash and compared with the Hex File after programming.
Step 4
This helps to ensure that the Hex File was correctly programmed. If the device does not support verifying then this item will be disabled. Checking the Fill Unused Flash option will result in every memory location not used by the File being programmed with the value that sets all the bits to a programmed state. Once a location has been programmed with this feature it cannot be reprogrammed with any other value, preventing someone from programming the device with a small program to read out the contents of Flash or altering the application’s operation. Checking the Gen Block Checksums option will instruct Flash Magic to program the highest location in every Flash block used by the Hex File with a special “checksum adjuster value”. This value ensures that when a checksum is calculated for the whole Flash Block it will equal 55H, providing the contents of the Flash block have not be altered or corrupted. Please refer to the Block Checksums section for more information. Checking the Execute option will cause the downloaded firmware to be executed automatically after the programming is complete. Note that this will not work if using the Hardware Reset option or a device that does not support this feature.
4.4.5 STEP 5-PERFORMING THE OPERATIONS
Step 5 contains a Start button. Clicking the Start button will result in all the selected operations in the main window taking place. They will be in order:
Step 5
Erasing Flash
Programming the Hex File
Verifying the Hex File
Filling Unused Flash
Generating Checksums
Programming the clocks bit
Programming the Security Bits
Executing the firmware
Once started, progress information and a progress bar will be displayed at the bottom of the main window. In addition the Start button will change to a cancel button. Click on the cancel button to cancel the operation.
Note that if you cancel during erasing all the Flash, it may take a few seconds before the operation is cancelled. Once the operations have finished the progress information will briefly show the message “Finished…” . The Programmed Count shown next to the progress bar will increment. This shows the total number of times the hex file has been programmed. Modifying the hex file or selecting another hex file will reset the count. Alternatively, right-clicking over the count provides a menu with the option to immediately reset the count.
CHAPTER 5
TEMPERATURE SENSOR - LM35
TEMPERATURE SENSOR – LM35
The LM35 is an integrated circuit sensor that can be used to measure temperature with an electrical output proportional to the temperature in degree Celsius.
5.1 FEATURES
Calibrated directly in centigrade (o C)
Linear +10.0 mV/ o C
0.5 o C accuracy guarantee able (at +25 o C)
Rated for full -55 o C to +150o C range
Suitable for remote applications
Low cost due to wafer-level trimming
Operates from 4 to 30 volts
Less than 60 µA current drain
Low self-heating, 0.08 o C in still air
Non- linearity only ±1/4 o C typical
Low impedance output, 0.1 W for 1 mA load
5.2 DESCRIPTION
The LM35 series are precision integrated- circuit temperature sensors, whose output voltage is linearly proportional to the Celsius temperature.
The LM35 thus has an advantage over linear temperature sensors calibrated in o Kelvin, as the user is not required to subtract a large constant voltage from its output to obtain convenient centigrade scaling. The LM35’s low output impedance, linear output, and precise inherent calibration make interfacing to readout or control circuitry especially easy. It can be used with single power supplies, or with plus and minus supplies. As it draws only 60 µA from its supply, it has very low self-heating, less than 0.1 o C in still air. The LM35 is rated to operate over a -55 o C to +150 o C temperature range.
5.3 SENSOR OPERATION
In this circuit, parameter values commonly used are supply Vcc=5v or 12v, and resistance
Ra=Vcc/10-6=80 KΩ. The output voltage is converted to temperature by a simple conversion factor.
Temperature (o C) = Vout * (100 o C/ V)
LM35 Circuit
The sensor has the sensitivity of 10mV / o C and the output voltage varies linearly with temperature.
5.4 ADVANTAGES
One can measure temperature more accurately than using a thermistor.
The sensor circuitry is sealed and not subject to oxidation, etc.,
The LM35 generates a higher output voltage than thermocouples and may not require that the output voltage be amplified.
CHAPTER 6
A/D CONVERTER – MCP3202
ANALOG TO DIGITAL CONVERTER (ADC)
6.1 GENERAL DESCRIPTION
The MCP3202 is a successive approximation 12 bit Analog to Digital converter with on-board sample and hold circuitry. The MCP3202 is programmable to provide a single pseudo-differential input pair or dual single-ended inputs. Communication with the device is done using a simple serial interface compatible with the SPI protocol The device is capable of conversion rates of up to 100kbps at 5v and 50 kbps at 2.7v.Low current design of only 500nA and 375 microAmps.
6.2 FEATURES
12 bit resolution
Operating supply voltage 2.7 V to 5.5 V
On-chip sample and hold
SPI Serial interface
Low power CMOS technology
100kbps max sampling rate at Vdd =5v
50kbps max sampling rate at Vdd =2.7v
Analog inputs programmable as single-ended or differential inputs
Industrial temperature range -400c to +85 0 c
8-bit successive approximation A/D conversion
6.3 PIN DIAGRAM
6.3.1 PIN DESCRIPTIONS
1.CH0/CH1
Analog inputs for channels 0 and 1 respectively. These channels can programmed to be used as two indepen-dent channels in single ended-mode or as a single pseudo-differential input where 1 channel is IN+ and one channel is IN-.
2CS/SHDN(Chip Select/Shutdown)
The CS/SHDN pin is used to initiate communication with the device when pulled low and will end a conver-sion and put the device in low power standby when pulled high. The CS/SHDN pin must be pulled high between conversions.
3CLK (Serial Clock)
The SPI clock pin is used to initiate a conversion and to clock out each bit of the conversion as it takes place.
4DIN (Serial Data Input)
The SPI port serial data input pin is used to clock in input channel configuration data.
5DOUT (Serial Data output)
The SPI serial data output pin is used to shift out the results of the A/D conversion. Data will always change on the falling edge of each clock as the conversion takes place.
6.4 FUNCTIONAL DIAGRAM
6.4.1 DEVICE OPERATION
The MCP3202 A/D Converter employs a conventional SAR architecture. With this architecture, a sample is acquired on an internal sample/hold capacitor for 1.5 clock cycles starting on the second rising edge of the serial clock after the start bit has been received. Following this sample time, the input switch of the con-verter opens and the device uses the collected charge on the internal sample and hold capacitor to produce a serial 12-bit digital output code. Conversion rates of 100ksps are possible on the MCP3202. See Section 6.2 for information on minimum clock rates. Communication with the device is done using a 3-wire SPI-compatible interface.
6.4.2Analog Inputs:
The MCP3202 device offers the choice of using the ana-log input channels configured as two single-ended inputs or a single pseudo-differential input. Configura-tion is done as part of the serial command before each conversion begins. When used in the psuedo-differen-tial mode, CH0 and CH1 are programmed as the IN+ and IN- inputs as part of the command string transmit-ted to the device. The IN+ input can range from IN- to VREF (VREF + IN-). The IN- input is limited to ±100mV from the VSS rail. The IN- input can be used to cancel small signal common-mode noise which is present on both the IN+ and IN- inputs.
For the A/D Converter to meet specification, the charge holding capacitor (CSAMPLE) must be given enough time to acquire a 12-bit accurate voltage level during the 1.5 clock cycle sampling period. (RS) adds to the internal sampling switch (RSS) imped-ance, directly affecting the time that is required to charge the capacitor, CSAMPLE. Consequently, larger source impedances increase the offset, gain, and inte-gral linearity errors of the conversion.
Ideally, the impedance of the signal source should be near zero. This is achievable with an operational ampli-fier such as the MCP601 which has a closed loop out-put impedance of tens of ohms. When operating in the pseudo-differential mode, if the voltage level of IN+ is equal to or less than IN-, the resultant code will be 000h. If the voltage at IN+ is equal to or greater than {[VREF + (IN-)] - 1 LSB}, then the out-put code will be FFFh. If the voltage level at IN- is more than 1 LSB below VSS, then the voltage level at the IN+ input will have to go below VSS to see the 000h output code. Conversely, if IN- is more than 1 LSB above VSS, then the FFFh code will not be seen unless the IN+ input level goes above VREF level.
6.4.3 Digital Output Code
The digital output code produced by an A/D Converter is a function of the input signal and the reference volt-age. For the MCP3202, VDD is used as the reference voltage. As the VDD level is reduced, the LSB size is reduced accordingly. The theoretical digital output code produced by the A/D Converter is shown below.
Digital Output Code = 4096 * VIN / VDD
where:
VIN = analog input voltage,VDD = supply voltage,
6.5 SERIAL COMMUNICATIONS
Communication with the MCP3202 is done using a standard SPI-compatible serial interface. Initiating communication with the device is done by bringing the CS line low. See Figure 5-1. If the device was powered up with the CS pin low, it must be brought high and back low to initiate communication. The first clock received with CS low and DIN high will constitute a start bit. The SGL/DIFF bit and the ODD/SIGN bit follow the start bit and are used to select the input channel configuration. The SGL/DIFF is used to select single ended or psuedo-differential mode. The ODD/SIGN bit selects which channel is used in single ended mode, and is used to determine polarity in pseudo-differential mode. Following the ODD/SIGN bit, the MSBF bit is transmit-ted to and is used to enable the LSB first format for the device. If the MSBF bit is low, then the data will come from the device in MSB first format and any further clocks with CS low will cause the device to output zeros. If the MSBF bit is high, then the device will output the converted word LSB first after the word has been transmitted in the MSB first format.
MCP3202. The device will begin to sample the analog input on the second rising edge of the clock, after the start bit has been received. The sample period will end on the falling edge of the third clock following the start bit. MSB first. Data is always output from the device on the falling edge of the clock. If all 12 data bits have been transmitted and the device contin-ues to receive clocks while the CS is held low, (and MSBF = 1), the device will output the conversion result LSB first If more clocks are pro-vided to the device while CS is still low (after the LSB first data has been transmitted), the device will clock out zeros indefinitely. If necessary, it is possible to bring CS low and clock in leading zeros on the DIN line before the start bit. This is often done when dealing with microcontroller-based SPI ports that must send 8 bits at a time.
CONFIG
BITS CHANNEL
SELECTION GND
SGL/
DIFF ODD/
SIGN 0 1
SINGLE
ENDED MODE 1 0 -
1 1 +
PSEUDO-
DIFFERENTIAL
MODE 0 0 I I
0 1 I IN
6.6 APPLICATIONS
Closed loop control systems
Low power converter for remote data acquisition
Battery operated equipment
Acquisition of analog values in automotive, audio and
TV applications (as tuner cards)
Software defined radio and digital oscilloscopes
CHAPTER 7
REAL TIME CLOCK DS1307
REAL TIME CLOCK (RTC)
7.1 GENERAL DESCRIPTION
The DS1307 Serial Real Time Clock is a low power, full BCD clock/calendar plus 56 bytes of nonvolatile SRAM. Address and data are transferred serially via a 2-wire bi-directional bus. The clock/calendar provides seconds, minutes, hours, day, date, month, and year information. The end of the month date is automatically adjusted for months with less than 31 days, including corrections for leap year. The clock operates in either the 24-hour or 12-hour format with AM/PM indicator. The DS1307 has a built-in power sense circuit which detects power failures and automatically switches to the battery supply.
7.2 FEATURES
• Real time clock counts seconds, minutes, hours, date of the month, month, day of the week, and year
• 56 byte nonvolatile RAM for data storage
• 2-wire serial interface
• Programmable square wave output signal
• Automatic power-fail detect and switch circuitry
• Consumes less than 500 nA in battery backup mode with oscillator running
• Optional industrial temperature range -40_C to +85_C
• Available in 8-pin DIP or SOIC
7.3 PIN DIAGRAM
7.4 DESCRIPTION
VCC - Primary Power Supply
X1, X2 - 32.768 kHz Crystal Connection VBAT - +3V Battery Input
GND - Ground
SDA - Serial Data
SCL - Serial Clock
SQW/OUT - Square wave/Output Driver
7.5 FUNTIONAL BLOCK DIAGRAM:
OPREATION:
The DS1307 operates as a slave device on the serial bus. Access is obtained by implementing a START condition and providing a device identification code followed by a register address. Subsequent registers can be accessed sequentially until a STOP condition is executed. When VCC falls below 1.25 x VBAT the device terminates an access in progress and resets the device address counter. Inputs to the device will not be recognized at this time to prevent erroneous data from being written to the device from an out of tolerance system. When VCC falls below VBAT the device switches into a low current battery backup mode. Upon power up, the device switches from battery to VCC when VCC is greater than VBAT +0.2V and recognizes inputs when VCC is greater than 1.25 x VBAT.
7.5 SIGNAL DESCRIPTIONS
VCC, GND - DC power is provided to the device on these pins. VCC is the +5 volt input. When 5 volts is applied within normal limits, the device is fully accessible and data can be written and read. When a 3-volt battery is connected to the device and VCC is below 1.25 x VBAT, reads and writes are inhibited. However, the Timekeeping function continues unaffected by the lower input voltage. As VCC falls below VBAT the RAM and timekeeper are switched over to the external power supply (nominal 3.0V DC) at VBAT.
VBAT - Battery input for any standard 3-volt lithium cell or other energy source. Battery voltage must be held between 2.0 and 3.5 volts for proper operation. The nominal write protect trip point voltage at which access to the real time clock and user RAM is denied is set by the internal circuitry as 1.25 x VBAT nominal. A lithium battery with 48 mAhr or greater will back up the DS1307 for more than 10 years in the absence of power at 25 degrees C.
SCL (Serial Clock Input) - SCL is used to synchronize data movement on the serial interface.
SDA (Serial Data Input/Output) - SDA is the input/output pin for the 2-wire serial interface. The SDA pin is open drain which requires an external pullup resistor.
SQW/OUT (Square Wave/ Output Driver) - When enabled, the SQWE bit set to 1, the SQW/OUT pin outputs one of four square wave frequencies (1 Hz, 4 kHz, 8 kHz, 32 kHz). The SQW/OUT pin is open drain which requires an external pullup resistor. SQW/OUT will operate with either Vcc or Vbat applied.
X1, X2 - Connections for a standard 32.768 kHz quartz crystal. The internal oscillator circuitry is designed for operation with a crystal having a specified load capacitance (CL) of 12.5 pF.
RTC AND RAM ADDRESS MAP
The address map for the RTC and RAM registers of the DS1307 is shown in Figure 2. The real time clock registers are located in address locations 00h to 07h. The RAM registers are located in address locations 08h to 3Fh. During a multi-byte access, when the address pointer reaches 3Fh, the end of RAM space, it wraps around to location 00h, the beginning of the clock space.
CLOCK AND CALENDAR
The time and calendar information is obtained by reading the appropriate register bytes. The real time clock registers are illustrated in Figure 3. The time and calendar are set or initialized by writing the appropriate register bytes. The contents of the time and calendar registers are in the Binary-Coded Decimal (BCD) format. Bit 7 of Register 0 is the Clock Halt (CH) bit. When this bit is set to a 1, the oscillator is disabled. When cleared to a 0, the oscillator is enabled.
7.6 COMMUNICATION
Data transfer may be initiated only when the bus is not busy. During data transfer, the data line must remain stable whenever the clock line is HIGH. Changes in the data line while the clock line is high will be interpreted as control signals. Accordingly, the following bus conditions have been defined:
Bus not busy: Both data and clock lines remain HIGH.
Start data transfer: A change in the state of the data line, from HIGH to LOW, while the clock is HIGH, defines a START condition.
Stop data transfer: A change in the state of the data line, from LOW to HIGH, while the clock line is HIGH, defines the STOP condition.
Data valid: The state of the data line represents valid data when, after a START condition, the data line is stable for the duration of the HIGH period of the clock signal. The data on the line must be changed during the LOW period of the clock signal. There is one clock pulse per bit of data.
Each data transfer is initiated with a START condition and terminated with a STOP condition. The number of data bytes transferred between START and STOP conditions is not limited, and is determined by the master device. The information is transferred byte-wise and each receiver acknowledges with a ninth bit. Within the 2-wire bus specifications a regular mode (100 kHz clock rate) and a fast mode (400 kHz clock rate) are defined. The DS1307 operates in the regular mode (100 kHz) only.
Acknowledge: Each receiving device, when addressed, is obliged to generate an acknowledge after the reception of each byte. The master device must generate an extra clock pulse which is associated with this acknowledge bit.
A device that acknowledges must pull down the SDA line during the acknowledge clock pulse in such a way that the SDA line is stable LOW during the HIGH period of the acknowledge related clock pulse. Of course, setup and hold times must be taken into account. A master must signal an end of data to the slave by not generating an acknowledge bit on the last byte that has been clocked out of the slave. In this case, the slave must leave the data line HIGH to enable the master to generate the STOP condition.
Depending upon the state of the R/W bit, two types of data transfer are possible:
1. Data transfer from a master transmitter to a slave receiver. The first byte transmitted by the master is the slave address. Next follows a number of data bytes. The slave returns an acknowledge bit after each received byte. Data is transferred with the most significant bit (MSB) first.
2. Data transfer from a slave transmitter to a master receiver. The first byte (the slave address) is
transmitted by the master. The slave then returns an acknowledge bit. This is followed by the slave transmitting a number of data bytes. The master returns an acknowledge bit after all received bytes other than the last byte. At the end of the last received byte, a ’not acknowledge’ is returned.
The master device generates all of the serial clock pulses and the START and STOP conditions. A transfer is ended with a STOP condition or with a repeated START condition. Since a repeated START condition is also the beginning of the next serial transfer, the bus will not be released. Data is transferred with the most significant bit (MSB) first.
CHAPTER 8
SERIAL PERIPHERAL INTERFACE
8.1 INTRODUCTION:
SPI stands for Serial Peripheral Interfacing. It is a synchronous serial bus developed by Motorola and is present on many of their micro controllers. SPI is used to communicate with peripheral devices.Benefit of serial communications is low pin counts Many common embedded system peripherals, such as A2D and D2A converters, LCD, and temperature sensors, support serial interfaces
Two types of devise are involved in data transfer in the SPI format: master and slaves. The master device initiates data transfer and also generates the clock signal required for data transfer synchronization .SPI can achieve higher data rates. SPI has full duplex capability
8.2 SPI BUS CONFIGURATION:
Devices communicate using a master/slave relationship, in which the master initiates the data frame. When the master generates a clock and selects a slave device, data may be transferred in either or both directions simultaneously. In fact, as far as SPI is concerned, data are always transferred in both directions. It is up to the master and slave devices to know whether a received byte is meaningful or not. So a device must discard the received byte in a "transmit only" frame or generate a dummy byte for a "receive only" frame.
Single master,single slave SPI implementation
SCLK is generated by the master and input to all slaves. MOSI carries data from master to slave. MISO carries data from slave back to master. A slave device is selected when the master asserts its ÇSS signal.
Single master,Multiple slave SPI implementation
If multiple slave devices exist, the master generates a separate slave select signal for each slave.
Four main signals:
Master Out Slave In (MOSI) : data from master to slave
Master In Slave Out (MISO) : data from slave to master
Serial Clock (SCLK or SCK) : clock
Chip Select (CS) : select particular peripheral when multiple peripherals are connected to
master
8.3 SPI REGISTERS:
There are three registers unique to the serial peripheral interface which provide control,status,and data stroage
SPCR:
The Serial Peripheral Control Register (SPCR) provides control for the SPI. A pair of parameters called clock polarity (CPOL) and clock phase (CPHA) determine the edges of the clock signal on which the data are driven and sampled.
Bit 7 6 5 4 3 2 1 0
SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0
R/W R/W R/W R/W R/W R/W R/W R/W
0 0 0 0 0 0 0 0
SPIE:Serial Peripheral Interrupt Enable
SPE :Serial Peripheral System Enable
DORD:Data Order
MSTR: Master Mode Select
CPOL:Clock Polarity
CPHA:Clock Phase
SPR0:SPI Clock Rate Select0
SPR1:SPI Clock Rate Select1
SPDR:
The SPI Data register is a Read/Write register used for data transfer between the register file and the SPI shift register.Writing to the register initiates data transmission.Reading the register causes the shift register receive buffer to be read
Bit 7 6 5 4 3 2 1 0
MSB LSB
R/W R/W R/W R/W R/W R/W R/W R/W
X X X X X X X X
SPSR:
Bit 7 6 5 4 3 2 1 0
SPIF WCOL - - - - - SPI2X
R/W R/W R/W R/W R/W R/W R/W R/W
0 0 0 0 0 0 0 0
SPIF: SPI Interrupt Flag
WCOL: Write Collision
SPI2X:To double the data transmission rate
8.4 SPI ADVANTAGES AND DISADVANTAGES:
• SPI does not have an acknowledgement mechanism to confirm receipt of data. In fact, without a communication protocol, the SPI master has no knowledge of whether a slave even exists. SPI also offers no flow control.
• Slaves can be thought of as input/output devices of the master. SPI does not specify a particular higher-level protocol for master-slave dialog. In some applications, a higher-level protocol is not needed and only raw data are exchanged. An example of this is an interface to a simple codec. In other applications, a higher-level protocol, such as a command-response protocol, may be necessary. Note that the master must initiate the frames for both its command and the slave's response.
• SPI's full duplex communication capability and data rates (ranging up to several megabits per second) make it, in most cases, extremely simple and efficient for single master, single slave applications. On the other hand, it can be troublesome to implement for more than one slave, due to its lack of built-in addressing; and the complexity only grows as the number of slaves increases
CHAPTER 9
INTER –INTEGRATED CIRCUIT BUS
(I2C)
9.1 INTRODUCTION:
The name stands for “Inter - Integrated Circuit Bus” .A Small Area Network connecting ICs and other electronic systems . Synchronous Serial Signal.Multi master invented by Philips
Two wires are used to carry information between a number of devices .One wire is used for the data ,One wire is used for the clock .I2C is a true multi master bus providing arbitration and collision detection
Today, a variety of devices are available with I2C Interfaces
1.Microcontroller,
2. EEPROM,
3. Real-Timer,
4. interface chips,
5. LCD driver,
6. A/D converter.
9.2 I2C BUS CHARACTERISTICS:
• Includes electrical and timing specifications, and an
• associated bus protocol
• Two wire serial data & control bus implemented with the serial
• data (SDA) and clock (SCL) lines For reliable operation, a third line common ground is required:
• Unique start and stop condition
• Slave selection protocol uses a 7-Bit slave address .The bus specification allows an extension to 10 bits
• Bi-directional data transfer
• Acknowledgement after each transferred byte
• No fixed length of transfer
• True multi-master capability -Clock synchronization ,Arbitration procedure
• Transmission speeds up to 100Khz (classic I2C)
• Max. line capacitance of 400pF, approximately 4 meters (12 feet)
• Compatible with different IC technologies
I2C Bus Definition:
Master:
Initiates a transfer by generating start and stop conditions
Generates the clock
Transmits the slave address
Determines data transfer direction
Slave:
Responds only when addressed
Timing is controlled by the clock line .
9.3 I2C COMMUNICATION:
Bit Transfer :
In normal data transfer, the data line only changes state when the clock is low
SDA
SCL
Data line stable Change of data allowed
Data valid
Start and Stop Conditions :
A transition of the data line while the clock line is high is defined as either a start or a stop condition.
Both start and stop conditions are generated by the bus master .The bus is considered busy after a start condition, until a stop condition occurs .
SDA
SCL
Start Stop
Condition condition
I2C Addressing:
Each node has a unique 7 (or 10) bit address
Peripherals often have fixed and programmable address portions
Addresses starting with 0000 or 1111 have special functions:-
0000000 Is a General Call Address
0000001 Is a Null (CBUS) Address
1111XXX Address Extension
1111111 Address Extension – Next Bytes are the actual address
First Byte in Data Transfer on the I2C Bus:
MSB LSB ACK
R/Wr
7-bit slave address
R/Wr
0-Slave written to by master
1-Slave red by master
Ack
Generated by the slave whose address has been output
Data Transfer:
Transmitter releasesSDA
Line during 9th clock pulse
Acknowledgement from receiver
1.Start Condition-SDA is pulled low while SCL stays high
2. Slave address + R/W
3. Slave acknowledges with ACK
4. All data bytes– Each followed by ACK
5.Stop Condition- SDA is pulled High while SCL stays Low
9.4 TYPES OF I2C IMPLEMENTATION:
Byte Oriented Interface :
• Data is handled one byte at a a time
• Processor interprets a status byte when an event occurs
• For instance Philips 8xC554, 8xC591
Bit Oriented Interface:
• Processor is involved in every bus event when the interface is not Idle
“Bit Banged” :
• Implemented completely in software on 2 regular I/O pins of the microcontroller
• Works for single master systems
• Not recommended for Slave devices or Multimaster systems
9.5 I2C DEVICES:
Analog to Digital Converters (A/D, D/A):
MMI functions, battery & converters, temperature monitoring, control systems .
Bus Controller:
Telecom, consumer electronics, utomotive, Hi-Fi systems, PCs, servers
Real Time Clock (RTC)/Calendar:
Telecom, EDP,consumer electronics, clocks, automotive, Hi-Fi systems, FAX, PCs, terminals
DIP Switch:
Telecom, automotive, servers, battery & converters, control systems
LCD/LED Display Drivers:
Telecom, automotive instrument driver clusters, metering systems, POS terminals, portable items, consumer electronics
CHAPTER 10
CIRCUIT DIAGRAM WITH OPERATION
10.1 CIRCUIT DIAGRAM:
10.2 OPERATION
Many industry needs constant and regular updates on physical parameters like temperature,pressure etc.,for every small time intervals which may be difficult task for humans.Thus comes this device…..
The temperature will be sensed using a LM35 temperature sensor,which is a 3 pin IC.The analog output voltage from sensor is directly proportional to the temperature in degree celsius.It is fed to 12bit ADC MCP3202 which gives a digital output.The adc is interfaced with the microcontroller using serial peripheral interface(SPI).The IC DS1307,which is a real time clock,is interfaced with a microcontroller using I2C.The temperature along with time ,day,month and year is sent to LCD.A switch is provided to change the task,if the switch is on SPI based task is performed and displayed .If the switch is off I2C based task is performed and displays the same.
TEMPERATURE SENSOR
The temperature sensor LM35 is connected to the third pin CH1 of ADC. Where separate supply and ground is given to LM35. The supply to LM35 is given through Vref and also grouned. The LM35 is an integrated circuit sensor that can be used to measure the temperature with an electrical output proportional to the temperature in degree Celsius.
When the message is send through Microcontroller, LM35 senses the temperature and sends it as an analog input to ADC.
ANALOG TO DIGITAL CONVERTOR:
The A/D Converter MCP3202 is connected to the 6,7,8 pins of the microcontroller which are port 1.5,1.6,1.7Pins and they are MOSI,MISO,SCK.The supply to ADC is given through Vref and also grounded.The ADC Is a 12 bit converter that converts the analog signal into digital signal. This digital signal is given to the AT89S52 mirocontroller where it is communicated using SPI Protocol and displays the same in the LCD Display.
REAL TIME CLOCK:
The Real time clock DS1307 is connected to 3,4 pins of the microcontroller which are ports 1.2,1.3 pins and they are SDA and SCL.The supply to the RTC is given through Vref and also grounded.The RTC is using a Crystal of clock frequency of 32,768 khz and a battery backup of 3volts is used.The RTC reads the default date,Time,day,month and year and sends it to the AT89S52 microcontroller where it is communicated using I2C Protocol and displays the same in the LCD display
10.3 PROJECT CODING
#include
#include
#include
sbit cs = P2^2;
sbit output=P1^0;
void spi ();
void display(char *);
void dela();
char getdata(int);
void sclhigh();
void start();
void end();
void init_int();
void setclock(unsigned char,unsigned char);
void readclock();
void init_timer();
void run_timer();
void get_day(int);
int pm;
int sec =0x00;
int min = 0x35;
int hrs = 0x03;//12 hrs mode make 6th high (now time is 12)
//make 5th bit high for AM/PM indication
int day1 = 0x04;
int day = 0x14;
int month = 0x06;
int year = 0x07;
char dta[2];
char days[3],clk1[23];
int d_sec,d_min,d_hrs,i,rst1,rst2;
sbit sda = P2^3;
sbit scl = P2^4;
void rtc_4();
int release_key();
void key_press();
void debounce();
void column();
void dispay(char *);
void cal_1();
void disp(int result);
void ser_2();
void display1(char *name);
void adc_3();
void dis();
void dip(int name1);
void delay1();
void line1 ();
char a[4][3]={'1','2','3','4','5','6','7','8','9','*','0','#'};
char r=0,c=0;
int num1,num2,op;
int result,l,t;
xdata char *ptr_cmd = (xdata char *) 0x0FFF8;
xdata char *ptr_en = (xdata char *) 0x0FFF9;
void busy_check()
{
*ptr_cmd = 0x02;
while ( ( *ptr_en & 0x80 ) != 0x00 );
}
void delay()
{
unsigned int i =1000;
while ( i-- );
}
void lcd_comm()
{
*( ptr_cmd ) = 0x00;
}
void spi ()
{
SPCTL = 0X5C;
}
void line1 ()
{
lcd_comm();
*(ptr_en) = 0x80;
busy_check();
}
void init_lcd()
{
lcd_comm();
*( ptr_en ) = 0x38;
busy_check();
lcd_comm();
*(ptr_en) = 0x0e;
busy_check();
lcd_comm();
*(ptr_en) = 0x80;
busy_check();
lcd_comm();
*(ptr_en) = 0x01;
busy_check();
}
void dis(char a)
{
*(ptr_cmd) = 0x01;//Rs 1 for data write
*(ptr_en)= a;
busy_check();
}
void display()
{
*(ptr_cmd) = 0x01;
*(ptr_en) =a[r][c];
l=a[r][c];
busy_check();
}
void dip(int name1) //LCD display routine for digits display
{
*(ptr_cmd) = 0x01;
*(ptr_en) = name1;
busy_check();
delay1();
}
void disp(int result)
{
*(ptr_cmd) = 0x01;
*(ptr_en) = result;
busy_check();
}
void dispmenu()
{
lcd_comm();
*(ptr_en)=0x80;
display1("1.CAL 2.SER");
lcd_comm();
*(ptr_en)=0xC0;
display1("3.ADC 4.RTC");
}
void display1(char *name)
{
int l = strlen(name);
int i;
for(i = 0;i < l;i++)
{
*(ptr_cmd) = 0x01;
*(ptr_en) = name[i];
busy_check();
}
}
void key_press()
{
while((P3 & 0x038) == 0x038)
{
delay();
}
debounce();
}
int release_key()
{
P1=0xf0;
while((P3 & 0x38) == 0x38)
{
delay();
}
P3 = 0x0ff;
debounce();
return l;
}
void debounce()
{
P1 = 0xfe; //ground row 0 only
while((P3 & 0x38) != 0x38)
{
r=0;
column();
}
P1 = 0xfd; //ground row 1 only
while((P3 & 0x38) != 0x38)
{
r=1;
column();
}
P1 = 0xfb; //ground row 2 only
while((P3 & 0x38) != 0x38)
{
r=2;
column();
}
P1 = 0xf7; //ground row 3 only
while((P3&0x38) != 0x38)
{
r=3;
column();
}
}
void column()
{
if ((P3 & 0x30) == 0x30)
{
c=0;
l=a[r][c];
delay();
}
else if((P3 & 0x28) == 0x28)
{
c=1;
l=a[r][c];
delay();
}
else if((P3 & 0x18) == 0x18)
{
c=2;
l=a[r][c];
delay();
}
}
void dispay(char *s)
{ int l= strlen(s);
int i,c=0;
for(i=0;i<=l; i++)
{
if(c == 0)
{
if(i == 14)
{
lcd_comm();
*(ptr_en) = 0xc8;
busy_check();
c++;
}
}
*(ptr_cmd ) = 0x01;
*(ptr_en) = s[i];
busy_check();
}
}
void get_day(int dys)
{
if(dys == 01)
{
clk1[11] = 'S';
clk1[12] = 'U';
clk1[13] = 'N';
}
if(dys == 02)
{
clk1[11] = 'M';
clk1[12] = 'O';
clk1[13] = 'N';
}
if(dys == 03)
{
clk1[11] = 'T';
clk1[12] = 'U';
clk1[13] = 'S';
}
if(dys == 04)
{
clk1[11] = 'W';
clk1[12] = 'E';
clk1[13] = 'D';
}
if(dys == 05)
{
clk1[11] = 'T';
clk1[12] = 'H';
clk1[13] = 'U';
}
if(dys == 06)
{
clk1[11] = 'F';
clk1[12] = 'R';
clk1[13] = 'I';
}
if(dys == 07)
{
clk1[11] = 'S';
clk1[12] = 'A';
clk1[13] = 'T';
}
}
void init_timer()
{
TR0 = 0;
TMOD = TMOD & 0xf0;
TMOD = TMOD | 0x01;
TH0 = 0xdc;
TL0 = 0x00;
IE = IE & 0x7f;
IE = IE | 0x02;
IE = IE | 0x80;
TR0 = 1;
}
void run_timer() interrupt 1
{
i++;
if (i == 100)
{
//init_lcd();
readclock();
i = 0;
}
TR0 = 0;
TH0 = 0xdc;
TL0 = 0x00;
TR0 = 1;
}
void sclhigh()
{
scl = 1;
if(!scl)
{
dispay("ERROR");
// printf("error");
while(1);
}
}
void start()
{
sclhigh();
sda = 1;
if (!sda)
{
dispay(" gg");
// printf("gg");
while(1);
}
sda = 0;
delay();
scl = 0;
}
void end()
{
sclhigh();
sda = 0;
delay();
sda = 1;
}
int senddata(unsigned char databyte)
{
int i = 0,ret = 0,h=0;
for (i = 0;i<8;i++)
{
if ((databyte & 0x80) == 0x80) sda = 1; // if msb is 1 then send 1
else sda = 0; // else send 0 in sda line
databyte = databyte << 1; // left shift the data's
sclhigh();
delay();
scl = 0;
delay();
}
sda = 1;
sclhigh();
delay();
h = 1;
if(!sda)
{
h=0;
ret = 0;
}
else
{
dispay("2");
ret = 1;
}
scl = 0;
delay();
return(ret);
}
void dela()
{
int i =2;
while(i--);
}
void delay1()
{
int i =200;
while(i--);
}
char getdata(int ack)
{
int i;
rst1 = 0,rst2= 0;
for(i = 0;i<8;i++)
{
sclhigh();
dela();
if (i<=3)
{
rst1 *= 2;
if(sda) rst1++;
}
else
{
rst2 *= 2;
if(sda) rst2++;
}
scl = 0;
dela();
}
scl = 0;
sda = ack;
sclhigh();
dela();
scl = 0;
sda = 1;
dela();
return('A');
}
void setclock(unsigned char setbyte,unsigned char addr)
{
while (senddata(setbyte))
{
end();
start();
while (senddata(addr))
{
end();
start();
}
}
}
void readclock()
{
start(); // send start signal
while (senddata(0xd0))
{
end();
start();
}
setclock(0x00,0xd0);
end();
start();
while (senddata(0xd1))
{
end();
start();
}
d_sec = getdata(0); // sec
clk1[6] = (char) (rst1 + 48);
clk1[7] = (char) (rst2 + 48);
clk1[5]=':';
d_sec = getdata(0); // min
clk1[3] = (char) (rst1 + 48);
clk1[4] = (char) (rst2 + 48);
clk1[2] = ':';
d_sec = getdata(0); // hrs
pm=rst1&0x02;
clk1[0] = (char) ((rst1&0x01) + 48);
clk1[1] = (char) (rst2 + 48);
if(pm)
{
clk1[8] = 'P';
}
else
{
clk1[8] = 'A';
}
clk1[9]= 'M';
clk1[10] = ' ';
clk1[11] = 'S';
clk1[12] = 'U';
clk1[13] = 'N';
d_sec = getdata(0); // day1
get_day(d_sec);
d_sec = getdata(0); // day
clk1[14] = (char) (rst1 + 48);
clk1[15] = (char) (rst2 + 48);
clk1[16] = '/';
d_sec = getdata(0);// month
clk1[17] = (char) (rst1 + 48);
clk1[18] = (char) (rst2 + 48);
clk1[19] = '/';
d_sec = getdata(1);
clk1[20] = (char) (rst1 + 48);
clk1[21] = (char) (rst2 + 48);
lcd_comm();
*(ptr_en) = 0x01;
busy_check();
dispay(clk1);
for(i=0;i<=21;i++)
{
printf("%c",clk1[i]);
}
end();
}
void second_line ()
{
*ptr_cmd = 0x00;
*ptr_en = 0xC0;
busy_check ();
}
int sign ()
{
result = (~result) + 1 ;
*(ptr_cmd) = 0x01;
*ptr_en = '-';
return result;
}
void adc_3()
{
char c,d,i;
int e=0;
init_lcd ();
spi ();
cs = 0;
while(1)
{
SPDAT = 0XC0;
while (SPCFG != 0X80);
SPCFG = 0;
c = SPDAT;
SPDAT = 0XFF;
while(SPCFG != 0X80);
SPCFG = 0;
i = SPDAT;
cs = 1;
cs = 1;
cs = 0;
e = c;
e = e<<8;
e = e | i;
e = e<<1;
e = e & 0x0fff;
display1("12BIT ADC OUTPUT");//display in LCD
lcd_comm(); // LCD command routine call function
*(ptr_en) = 0xc0;// LCD display for 2nd line 1st location
delay1(); //call for delay routine
{
dip(((e%100000)/10000)+48); // ,,
display1(".");
dip(((e%10000)/1000)+48); // ,,
dip(((e%1000)/100)+48); // ,,
dip(((e%100)/10)+48); // ,,
dip((e%10)+48); // ,,
}
lcd_comm();//LCD command routine call
*(ptr_en)=0xc6;//LCD 2nd line 8th position
lcd_comm();//LCD command routine call
*(ptr_en) = 0x01;// LCD command for clear the display
delay1();//Delay routine call for some delay
}
}
void ser_2()
{
init_lcd();
display1("ser com:");
{
unsigned char m[]="hello ";
unsigned char a,x;
TMOD=0x20;// Use Timer 1 8-bit Auto Reload mode
TH1=0xE8; //Baud Rate 1200
SCON=0X50;// 8 bit,1 stop bit
TR1=1; // Start Timer 1 for Serial communication
while(1)
{
for(x=0;x<6;x++)
{
a=m[x];
SBUF=m[x];
delay();
disp(a);
while(TI==0);
TI=0;
}
}
}}
void cal_1()
{
char de=2,co=0;
while(1)
{
init_lcd();
lcd_comm();
do
{
/// (de--);
num1 = release_key ();
}
while( num1 < '0' || num1 > '9' );
*ptr_cmd = 0x01 ;
*ptr_en = num1 ;
busy_check();
num1 = num1 - 0x30;
printf(" %x ",num1);
do
{
op = release_key ();
}
while( op < '#' );
*ptr_cmd = 0x01;
if ( op == '#')
{
for(co=0;co<4;co++)
{
if(op==1)
{
*ptr_en = '+';
}
else if(op==2)
{
*ptr_en = '-';
}
else if(op==3)
{
*ptr_en = '*';
}
else
{
*ptr_en = '/';
}
}
}
busy_check();
do {
// (op--);
{
num2 = release_key ();
}
} while( num2 < '0' || num2 > '9' );
*ptr_cmd = 0x01;
*ptr_en = num2 ;
busy_check();
num2 = num2 - 0x30;
if (op == '#')
{
result = num1 + num2;
second_line ();
*(ptr_cmd) = 0x01;
*ptr_en = (result / 10 ) + 0x30;
busy_check ();
*(ptr_cmd) = 0x01;
*ptr_en = (result % 10 ) + 0x30;
busy_check ();
printf(" %d ",result);
}
else if ( op == '*' )
{
second_line ();
result = num1 - num2;
result = (result <= 9 && result >= 0 ) ? result : sign ();
*(ptr_cmd) = 0x01;
*ptr_en = (result / 10 ) + 0x30;
busy_check ();
*(ptr_cmd) = 0x01;
*ptr_en = (result % 10 ) + 0x30;
busy_check ();
printf(" %x ",result);
}
while(1){}
}
}
void rtc_4()
{
int k;
long int s=60000;
init_lcd();
printf("test");
start(); // send start signal
while(senddata(0xd0)){
end (); // send Slave address & write mode
delay1();
start();
}
setclock(0x00,0xd0);
setclock(sec,0xd0);
setclock(min,0xd0);
setclock(hrs,0xd0);
setclock(day1,0xd0);
setclock(day,0xd0);
setclock(month,0xd0);
setclock(year,0xd0);
end();
readclock();
init_timer();
while(1);
}
void main()
{
char ch;
init_lcd();
dispmenu();
while(1)
{
ch=release_key();
switch(ch)
{
case'1':cal_1();
break;
case'2':ser_2();
break;
case'3':adc_3();
break;
case'4':rtc_4();
break;
default:printf("exit\n");
}
}
}
*******************End of Main Program********************
10.4 CONCLUSION
In future, I could use this way for controlling the temperature also and the RTC for setting the time intervals also and Scientific Calculator is also Implement, and normal Serial Communication replace wireless communication Zigbee and R.F is used. Since this communication through the SPI and I2C are wire based we would like to perform in wireless technologies also which will be more effective, Further it can be used for controlling and monitoring all other Parameters used in industries, appliances, etc.
BIBLIOGRAPHY
REFERENCE BOOKS
The 8051 Microcontroller and Embedded Systems - Muhammad Ai Mazidi & Co.
Embedded Systems – Raj Kamal.
Embedded Software Primer – David E Simon.
Microcontrollers and Microprocessors
WEBSITES
www.gsmworld.com
www.iec.org
www.google.com
www.raisonance.com
SINGLE BOARD COMPUTER PROJECT REPORT
RAJESHS, Monday, October 26, 2009
Subscribe to:
Post Comments (Atom)
Comments :
Post a Comment