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

1.

INTRODUCTION
1.1 EMBEDDED SYSTEMS:
One of the more surprising developments of the last few decades has been the ascendance to a position of prevalence in human affairs. Today they are more computers in our homes and offices then there are people who live and work in them. Yet many of these computers are not recognized as such by their users. In this project, we will explain what embedded systems are and where they are found. We will also introduce the subject of embedded programming and explain why we have selected assembly programming as languages for our project. An embedded system is a combination of computer hardware and software, and perhaps additional mechanical or other part, designed to perform a specific function .a good example is the microwave oven. Many people use the term general purpose computer to make this distinction clear .as shipped, general purpose computer is a blank slate; the manufacture does not know what the customer will do with it. One customer may use it for a network file server, another may use it exclusively for playing games, and other may use it to write the great American novel. Frequently, an embedded system is component with in some larger system. For example, modern cars and trucks contain many embedded system. One embedded system controls the anti-lock brakes, another monitor and controls the vehicles emissions and a third displays information on the dashboard .in some cases this embedded systems are connected by some sort of a communications network, but that is certainly not a requirement. If an embedded system is designed well, the existence of the processor and software could be completely unnoticed by a user of device, such as in the case for a microwave oven, VCR, or alarm clock in some cases, it would be even be possible to build equivalent devices that do not contain in the processor and software. This could be done by replacing the combination with a custom integrated circuit that performs the same functions in hardware could do this. However a lot of flexibility is lost when a design is hard coded in this way. it is much easier, and cheaper, to change a few lines of software than to redesign a piece of custom hardware.

1.2 History and Future:


Given the definition of embedded systems earlier in this chapter, the first such systems could not possibly have appeared before 1971.That was the year Intel introduced the worlds first microprocessor. This chip, the 4004, was designed for use in a line of business calculators produced by the Japanese company busicom. In 1969, busicom asked Intel to design a set custom integrated circuits one for each of their new calculator models. The 4004 were Intels response. Rather than design custom hardware for each calculator, Intel proposed a general-purpose circuit that could be used throughout the entire line of calculators. This general purpose processor was designed to read and execute a set of instruction -softwarestored in an external memory chip. Intels idea was that the software would give each calculator its unique set of features. The microprocessor was an overnight success, and its use increased steadily over the next decade. Early embedded application included unmanned space probes, computerized traffic lights, and aircraft light control systems. In the 1980s, embedded systems quietly rode the waves of the microcomputer age and brought microprocessor into every part of our personal and professional lives. many of the electronic devices in our kitchens (bread machine, food processors, and microwaves ovens), living rooms (televises, stereos, and remote controls), and workplaces (fax machines, pagers, laser printers, cash registers, and credit card readers) are embedded systems, It seems inevitable that the number of embedded systems will continue to increase rapidly. Already there are promising new embedded devices that have enormous market potential: light switches and thermostats that can be controlled by a central computer, intelligent air-bag systems that dont inflate when children or small adults are present, palmsized electronics organizers and personal digital assistance (PDAS), digital cameras,and dashboard navigation systems.

1.3 Processing power:


The amount of processing power necessary to get the job done, a common way to compare processing power s the MIPS (millions of instructions per second) rating. If two processors have rating of 25 MIPS and MIPS, the latter is said to be the more powerful of the two. However, other important features of the processor need to be considered. One of these is the register width, which typically ranges from 8 to 64 bit processors exclusively, but embedded systems are still commonly built with older and less costly 8 and 16 bit processors. 2

1.4 Memory:
The amount of memory (Rom and Ram) required holding the executable software and the data it manipulates. Here the hardware designer must usually make his best estimate up front and be prepared to increase or decrease the actual amount as the software is being developed. In general, the register width of a processor established the upper limit of the amount of memory it can access (e.g., an 8 bit address register can select one of only 256 unique memory locations). A few hundred bytes just arent enough to do much of anything. Several thousand bytes is a more likely minimum, even for an 8-bit processor.

1.5 Reliability:
How reliable must the final products be? If it is childrens toy, it doesnt always have to work right, but if its a part of a space shuttle or a car, it had sure better do what it is supposed to each and every time. In addition to these general requirements, there are the detailed functional requirements of the system itself. These are the things that give the embedded system its unique identity as a microwave oven, pacemaker, or pager. In order to simultaneously demonstrate the variation from one embedded system to the next and the possible effects of these design requirements on the hardware, I will now take some time to describe three embedded systems in some detail. My goal is to put you in the system designers shoes for a few moments before beginning to narrow our discussion to embedded software development.

1.6 KNOWLEDGE:
Your knowledge of assembly language will help you write better programs, even when using HLLs.Assembly language is the uncontested speed champion among programming languages. An expert assembly language programmer will almost always produce a faster program than an expert C programmer. While certain programs may not benefit much from implementation in assembly, you can speed up many programs why a factor of five or ten over their HLL counterparts by careful coding in assembly language; even greater improvements is possible if youre not using an optimizing compiler. Alas, speedups on the order of five to ten times are generally not achieved by beginning assembly language programmers. However, if you spend the time to learn well, you too can achieve these impressive performance gains. assembly language really

Despite some peoples claim that programmers no longer have to worry about memory constraints there are many programmers who need to write smaller programs, assembly language programs are of often less than one half the size of comparable HLL programs, this is especially impressive when you consider the fact that data items generally consume the same amount of space by a typical application saving space saves money. Pure and simple if a program requires 1.5 megabytes; it will not fit on a 1.44 Mbytes floppy. Likewise, if an application requires 2 Mbytes RAM, the user will have to install an extra Byte if there is only one available in the machine. Even on big machines with 32 or more Mbytes, writing gigantic applications isnt excusable. Most users put more than eight megabytes in their machine so they can run multiple programs from memory at one time. The bigger a program is, the fewer applications will be able to co-exist in memory with it. Virtual memory isnt a particularly attractive solution either. With virtual memory, the bigger an application is, the slower the system will run as a result of that programs size. Capability is another reason people resort to assembly language. HLLs are an abstraction of typical machine architecture; as a result, they rarely take into account any special features of the machine, features which are available to assembly language programmers. If you want to use such features, you will need to use assembly language. A really good example is the input/output instructions available on the 80x86 microprocessors. These instructions let you directly access certain I/O devices on the computer. In general, such access is not part of any high level language. Indeed some languages like C pride themselves on not supporting any specific I/O operations 8 in assembly language you have no such restrictions. Anything you can do on the machine you can do in assembly language. This is definitely not the case with most HLLs. Of course, another reason for learning assembly language is just for the knowledge. Now some of you may be thinking. Gee, that would be wonderful, but Ive got lot to do. My time would be better spent writing code than learning assembly language. There are some practical reasons for learning assembly, even if you never intend to right a single line of assembly code. If you know assembly language well, youll have an appreciation for the complier, and youll know exactly what the complier is doing with all those HLL statements. Once you see how compliers translate seemingly innocuous statements into a ton of machine code, youll want to search for better ways to accomplish the same thing.

Good assembly language programmers make better HLL programmers because they understand the limitations of the compiler and they know what its doing with their code. Those who dont know assembly language will accept the poor performance their compiler produces and simply shrug it off. Yes assembly language is definitely worth the effort. The only sear thing is that once you learn it really well, youll probably start using it far more than you ever dreamed you would. That is a common malady among assembly language programmers. Seems they cant stand what the compilers are doing with their programs.

CHAPTER2:
2. MICROCONTROLLERS
2.1 MICROPROCESSORS VS MICROCONTROLLERS: The Microprocessors (Intels X86 family8086, 80286, 80386, 80486, and Pentium OR Motorolas 68000, 68010, 68020 etc) contains no RAM, no ROM, and no I/O ports on the chip itself. When using these types of General purpose Microprocessors one must add RAM, ROM, I/O ports and timers externally to make them functional. If the tasks demand the greater amount of RAM, ROM, and I/O ports we need to go to these Microprocessors. It also leads to the systems bulkier and more expensive. The case of Microcontrollers is entirely different. Microcontrollers has a CPU (microprocessor) in Addition to a fixed amount of RAM, ROM, I/O ports, and a timer all are embedded together on a single chip. Therefore the designer need not add any external memory, RAM, I/O ports and timer to it. That is the main advantage of microcontrollers than microprocessors, which makes them ideal for many applications in where cost and space are critical. For this reason the microcontrollers are widely used in many applications like TV remote control, Intercom, Telephones, security systems, Fax machines, Cellular phones, Electronic Toys, Cameras, laser printers, Paging, Instrumentation, Keyless entry etc. The AT89S52 is a low-power, high-performance CMOS 8-bit microcontroller with 8K bytes of in system Programmable Flash memory. The device is manufactured using Atmels high-density nonvolatile Memory technology and is compatible with the indus-trystandard 80C51 instruction set and pin out. The on-chip Flash allows the program memory to be reprogrammed in-system or by a conventional Nonvolatile memory pro-grammar. By combining a versatile 8-bit CPU with in-system programmable Flash on a monolithic chip, the Atmel AT89S52 is a powerful microcontroller which provides a highly-flexible and Costeffective solution to many embedded control applications.

2.2 DESCRIPTION:
The 89C51/89C52/89C54/89C58 contains a non-volatile FLASH program memory that is parallel programmable. Both families are Single-Chip 8-bit Microcontrollers manufactured in advanced CMOS process and are derivatives of the 80C51 microcontroller family. All the devices have the same instruction set as the 80C51. 6

2.3 FEATURES:
80C51 Central Processing Unit On-chip FLASH Program Memory Speed up to 33 MHz Full static operation RAM expandable externally to 64 k bytes 4 level priority interrupt 6 interrupt sources Four 8-bit I/O ports Full-duplex enhanced UART Framing error detection Automatic address recognition Power control modes Clock can be stopped and resumed Idle mode Power down mode Programmable clock out Second DPTR register Asynchronous port reset Low EMI (inhibit ALE) 3 16-bit timers Wake up from power down by an external interrupt

2.4 PIN DESCRIPTION:


This microcontroller has 4 ports with each port having 8 pins. We use pull up resistors near the ports which we are using so that they are not damaged.

Figure 2.4.1 Microcontroller Pin diagram 8

Fig 2.4.2 Block diagram of Micro controller


PIN 40 Power supply, 5v from voltage regulator to drive the IC. PIN 20 Ground Point.

Port 0: Port 0 is an 8-bit open-drain bi-directional I/O port as shown in figure 2.1. 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. Port0 may 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 pull-ups. Port0 also receives the code bytes during flash programming, and outputs the code bytes during program verification. External pull-ups are required during program verification. Port 1: Port 1 is an 8-bit bi-directional I/O port with internal pull-ups. 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 pull-ups 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 pull-ups. 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 pull-ups. 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 pull-ups 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 pull-ups. Port 2 emits the high-order address byte during fetches from external program memory and during accesses to external data memory that uses 16-bit addresses (MOVX @ DPTR). In this application, it uses strong internal pull-ups when emitting 1s. During accesses to external data memory that uses 8-bit addresses (MOVX @ RI), Port 2 emits the contents of the P2 Special Function Register. Port2 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 pull-ups. 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 pull-ups and can be used as inputs. As inputs, Port 3 pins that are externally being pulled low will source current (IIL) because of the pull-ups. Port 3 also serves the functions of various special features of the AT89s52 as listed. Port3 also receives some Control signals for Flash programming and verification.

Port Pin P3.0 P3.1 P3.2

Alternate Functions RXD (serial input port) TXD (serial output port) INT0 (external interrupt 0) 10

P3.3 P3.4 P3.5 P3.6 P3.7

INT1 (external interrupt 1) T0 (timer 0 external input). T1 (timer 1 external input). WR (external data memory write strobe). RD (external data memory read strobe).

Here we use Port 0 as Input Port and Port 2 as Output Port and Port 3.4 as Interrupt Port RST Reset input. A high on this pin for two machine cycles while the oscillator is running resets the device. ALE/PROG: Address Latch Enable output pulse for latching the low byte of the address during accesses to external memory. This pin is also the program pulse input (PROG) during Flash programming. In normal operation ALE is emitted at a constant rate of 1/6 the oscillator frequency, and may be used for external timing or clocking purposes. Note, however, that one ALE pulse is skipped during each access to external Data Memory. If desired, ALE operation can be disabled by setting bit 0 of SFR location 8EH. With the bit set, ALE is active only during a MOVX or MOVC instruction. Otherwise, the pin is weakly pulled high. Setting the ALE disable bit has no effect if the microcontroller is in external execution mode. PSEN Program Store Enable is the read strobe to external program memory. When the AT89S52 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. EA/VPP: 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. Note, however, that if lock bit 1 is programmed, EA will be internally latched on reset. EA should be strapped to VCC for internal program executions. This pin also receives the 12-volt programming enable voltage (VPP) during Flash programming, for parts that require 12-volt VPP.

XTAL1: Input to the inverting oscillator amplifier and input to the internal clock operating circuit. XTAL2: Output from the inverting oscillator amplifier.

2.5 INTERRUPTS:
EA _ _ ES 11 ET1 EX1 ET0 EX0

Enable bit = 1 enables the interrupt.

Enable bit =0 disables the interrupt.

The AT89S52 has a total of five interrupt vectors: two external interrupts (INT0 and INT1), two timer interrupts (Timers 0 and 1), and the serial port interrupt. These interrupts are all shown in Table 2.5.1. Symbol EA Position IE.7 Function Disables all interrupts. If EA = 0, no interrupt is acknowledged. If EA = 1, each interrupt source is individually enabled or disabled by setting or clearing its enable bit. ES ET1 EX1 ET0 EX0 IE.6 IE.5 IE.4 IE.3 IE.2 IE.1 IE.0 Reserved Reserved Serial port interrupt enable bit Timer 1 interrupt enable bit External interrupt 1 enable bit Timer 0 interrupt enable bit External interrupt 0 enable bit

User software should never write 1s to reserved bits, because they may be used in future AT89 products. Table 2.5.1 Interrupts Each of these interrupt sources can be individually enabled or disabled by setting or clearing a bit in special Function register IE.. Note that table shows that bit positions IE.6 and IE.5 are unimplemented. User software should not write 1s to these bit positions, since they may be used in future PT89 products. The Timer 0 and Timer 1 flags, TF0 and TF1, are set at S5P2 of the cycle in which the timers overflow. Timer 0 and 1: Timer 0 and Timer 1 in the P89S51 operate the same way as Timer 0 and Timer 1 in the P89C51. The Timer 1 flags, TF) and TF1, are set at S5P2 of the cycle in which the timers overflow. The values are then polled by the circuitry in the next cycle.

12

2.6 SPECIAL FUNCTION REGISTERS:


A map of the on chip memory area called the Special Function Register (SFR) space is shown in Table. Note that not all of the addresses are occupied, and unoccupied addresses may not be implemented on the chip. Read accesses to these addresses will in general return random data, and write accesses will have an indeterminate effect.

2.7 OSCILLATOR CHARACTERISTICS:


XTAL1 and XTAL2 are the input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillator, as shown in Figure 3.1.6-1. Either a quartz crystal or ceramic resonant or may be used. To drive the device from an external clock source, XTAL2 should be left unconnected while XTAL1 is driven as shown in Figure 3.1.62. There are no requirements on the duty cycle of the external clock signal, since the input to the internal clocking circuitry is through a divide-by-two flip-flop, but minimum and maximum voltage high and low time specifications must be observed.

Figure 2.7.1 Oscillator Characteristics

Figure 2.7.2 Oscillator Connections

13

2.8 MODES:
Idle Mode: In idle mode, the CPU puts itself to sleep while all the on-chip peripherals remain active. The mode is invoked by software. The content of the on-chip RAM and all the special functions registers remain unchanged during this mode. The idle mode can be terminated by any enabled interrupt or by a hardware reset. It should be noted that when idle is terminated by a hardware reset, the device normally resumes program execution, from where it left off, up to two machine cycles before the internal reset algorithm takes control. On-chip hardware inhibits access to internal RAM in this event, but access to the port pins is not inhibited. To eliminate the possibility of an unexpected write to a port pin when Idle is terminated by reset, the instruction following the one that invokes Idle should not be one that writes to a port pin or to external memory. Power-down mode: In the power-down mode, the oscillator is stopped, and the instruction that invokes power-down is the last instruction executed. The on-chip RAM and Special Function Registers retain their values until the power-down mode is terminated. The only exit from power-down is a hardware reset. Reset redefines the SFRs but does not change the on-chip RAM. The reset should not be activated before VCC is restored to its normal operating level and must be held active long enough to allow the oscillator to restart and stabilize.

Table 2.8.1 Status of External Pins during Idle and Power-down Mode

14

CHAPTE
THE POWE ET CAL ANAL PPL

The power suppl required to controller circuits is 5VDC So available 2 0V AC should be stepped down and recti ied to produce required DC After rectifying the stepped down AC in order to ensure stability in supply this voltage is fed to 78XX series regulator so that voltage will be invariant with ti e. The IC7805 voltage regulator is to get the supply for the circuitry

T ANSFORMER:
A transformer is a electrical device with one winding of wire placed close to one or more other windings, used to couple two or more alternating -current circuits together by -1. employing the induction between the windings as shown in figure .2 A transformer in which the secondary voltage is higher than primary is called a step transformer. The -up product of current times voltage is constant in each set of windings, so that in set -up transformer, the voltage increase in the secondary is accompanied by corr sponding decrease e in current. If secondary voltage is less than primary, then its a step -down transformer. The step-down transformer is designed to reduce the voltage from the primary winding to secondary winding. Transformers play a vital role as they a llow us to step-up and step-down the voltage of an AC electric signal very efficiently (a well designed transformer typically has a power loss which is only few percent of total power flowing through it .

Fi

3.2-1 Ci

i symbol

Fi

3.2-2 T

sformer

Most power supplies use a step-down transformer to reduce the dangerously high mains voltage (2 0V in UK) to a safer low voltage. The input coil is called the primary a the nd output coil is called the secondary. There is no electrical connection between the two coils; instead they are linked by an alternating magnetic field created in the softiron core of the transformer. The two lines in the middle of the circuit symbol represent the core.

15

Transformers waste very little power so the power out is (almost) equal to the power in. Note that as voltage is stepped down current is stepped up. The ratio of the number of turns on each coil, called the turns ratio, determines the ratio of the voltages. A step-down transformer has a large number of turns on its primary (input) coil which is connected to the high voltage mains supply, and a small number of turns on its secondary (output) coil to give a low output voltage. Vp turns ratio = Vs Vp = primary (input) voltage Ns = number of turns on secondary coil Is = secondary (output) current = Ns Np and Vs Is = Vp Ip Vs = secondary (output) voltage Np = number of turns on primary coil Ip = primary (input) current power out = power in

A supply voltage of 2 0V and a 12V AC step down transformer is used.

3.3 BRIDGE RECTIFIER:


A bridge rectifier makes use of four diodes in a basic arrangement to achieve full wave rectification as shown in figure . . This is a widely used configuration, both with individual diodes wired as shown and with single component bridges where the diode bridge is wired internally. The supply voltage for bridge rectifier is 12V DC.

Fi

re 3.3.1 Bri

e rectifier

16

3.3.1 BASIC OPERATION:


When the input connected at the left corner of the diamond is positive with respect to the one connected at the right hand corner, current flows to the right along the upper colored path to the output, and returns to the input supply via the lower one as shown in figure 3.3.11.

Figure 3.3.1-1 Operation 1 When the right hand corner is positive relative to the left hand corner, current flows along the upper colored path and returns to the supply via the lower colored path as shown in figure 3.3.1-2.

Figure 3.3.1-2 Operation 2

17

Figure 3.3.1-3 Output Waveform

3.3.2 OUTPUT SMOOTHING:


For many applications, especially with single phase Ac where the full wave bridge serves to convert an AC input into DC output, the addition of a capacitor may be important because the bridge alone supplies an output of fixed polarity put pulsating magnitude (see figure above). The function of this capacitor, known as a smoothing capacitor is to lessen the variation in (or smooth) the raw output voltage waveform from the bridge. One explanation of smoothing is that the capacitor provides a low impedance path to the AC component of the output, reducing theca voltage across, and AC current through, the resistive load. In less technical terms any drop in the output voltage and current of the bridge tends to be cancelled by loss of charge in capacitor. This charge flows out as additional current through the load. Thus the change of load current and voltage is reduced relative to what would occur without the capacitor. Increases of voltage correspondingly store excess charge in the capacitor, thus moderating the change in output voltage / current The capacitor and the load resistance have a typical time constant = RC where C

and R are the capacitance and load resistance respectively. As long as the loa resistor is d large enough so that this time constant is much longer than the time of one ripple cycle, the above configuration will produce a well smoothed DC voltage across the load resistance. 18

CHAPTER 4: 4.1 AND GATE 74LS21N 4.1.1 DESCRIPTION


These devices contain two independent 4-input AND gates. The SN54LS21N is characterized for operation over the full military temperature range of -55oC to 125 oC. The SN74LS21N is characterized for operation from 0oC to 70oC 74LS21N is a 14 pin Dual Inline Package (DIP). It functions similar to an AND gate. The maximum supply voltage for SN74LS21N is 5.25V and minimum supply voltage is 4.75V The Pin diagram and logic table of this gate is as given below

Figure 4.1.1-1 Pin Diagram of 74LS21N

Table 4.1.1-1 Logic Table

19

4.2 VOLTAGE REGULATOR 4.2.1 DESCRIPTION


The L7800 series of three-terminal positive regulators is available in TO-220, TO220FP, TO-3 and D2PAK packages and several fixed output voltages, making it useful in a wide range of applications. These regulators can provide local on-card regulation, eliminating the distribution problems associated with single point regulation. Each type employs internal current limiting, thermal shut-down and safe area protection, making it essentially indestructible. If adequate heat sinking is provided, they can deliver primarily as fixed voltage regulators, these devices can be used with external components to obtain adjustable voltage and currents.
y y y y y

Output current to 1.5A Output voltages of 5; 5.2; 6; 8; 8.5; 9; 12; 15; 18; 24V Thermal overload protection Short circuit protection Output transition SOA protection

Table 4.2.1-1 Electrical Characteristics of L7805CV

20

BLOCK DIAGRAM

Figure 4.2.1-1 Block Diagram of L7805CV

Figure 4.2.1-2 Pin Representation of L7805CV

4.3 CRYSTAL OSCILLATOR 4.3.1 DESCRIPTION


A crystal oscillator is an electronic circuit that uses the mechanical resonance of a vibrating crystal of piezoelectric material to create an electrical signal with a very precise frequency. This frequency is commonly used to keep track of time (as in quartz wristwatches), to provide a stable clock signal for digital integrated circuits, and to stabilize frequencies for radio transmitters and receivers. The most common type of piezoelectric resonator used is the quartz crystal, so oscillator circuits designed around them were called "crystal oscillators. Quartz crystals are manufactured for frequencies from a few tens of kilohertz to tens of megahertz.

21

Figure 4.3.1-1 crystal equivalent circuit and Plot

A crystal is a solid in which the constituent atoms, molecules, or ions are packed in a regularly ordered, repeating pattern extending in all three spatial dimensions. Almost any object made of an elastic material could be used like a crystal, with appropriate transducers, since all objects have natural resonant frequencies of vibration. For example, steel is very elastic and has a high speed of sound. It was often used in mechanical filters before quartz. The resonant frequency depends on size, shape, elasticity, and the speed of sound in the material. High-frequency crystals are typically cut in the shape of a simple, rectangular plate. Low-frequency crystals, such as those used in digital watches, are typically cut in the shape of a tuning fork. For applications not needing very precise timing, a low-cost ceramic resonator is often used in place of a quartz crystal.

22

When a crystal of quartz is properly cut and mounted, it can be made to distort in an electric field by applying a voltage to an electrode near or on the crystal. This property is known as piezoelectricity. When the field is removed, the quartz will generate an electric field as it returns to its previous shape, and this can generate a voltage. The result is that a quartz crystal behaves like a circuit composed of an inductor, capacitor and resistor, with a precise resonant frequency. Quartz has the further advantage that its elastic constants and its size change in such a way that the frequency dependence on temperature can be very low. The specific characteristics will depend on the mode of vibration and the angle at which the quartz is cut (relative to its crystallographic axes). Therefore, the resonant frequency of the plate, which depends on its size, will not change much, either. This means that a quartz clock, filter or oscillator will remain accurate. For critical applications the quartz oscillator is mounted in a temperature-controlled container, called a crystal oven, and can also be mounted on shock absorbers to prevent perturbation by external mechanical vibrations.

Figure 4.3.1-2 Schematic symbol and equivalent circuit for a quartz crystal in an oscillator.

The series resonant frequency is given by

The parallel resonant frequency is given by

23

Figure 4.3.1-3 crystal oscillator circuit

The optimum load capacitance (CL) for crystal oscillator is specified by the manufacturer.

The equation to calculate C1 and C2 is

Crystal oscillator is used for clock and the frequency is 11.0592 MHz For executing one line it requires 12 clock periods.

4.4 TRANSISTOR AS NOT GATE 547B 4.4.1 DESCRIPTION


A transistor is a semiconductor device used to amplify and switch electronic signals. It is made of a solid piece of semiconductor material, with at least three terminals for connection to an external circuit. A voltage or current applied to one pair of the transistor's terminals changes the current flowing through another pair of terminals. Because the controlled (output) power can be much more than the controlling (input) power, the transistor provides amplification of a signal. 24

Here the transistor is used a NOT gate near the LEDs.

Figure 4.4.1-1 Transistor

Figure 4.4.1-2 V-I Characteristics of a Transistor

4.5 LIGHT EMITTING DIODE


LEDs are semiconductor devices. Like transistors, and other diodes, LEDs are made out of silicon. What makes an LED give off light are the small amounts of chemical impurities that are added to the silicon, such as gallium, arsenide, indium, and nitride. When current passes through the LED, it emits photons as a byproduct as shown in figure 3.4. Normal light bulbs produce light by heating a metal filament until it's white hot. Because LEDs produce photons directly and not via heat, they are far more efficient than incandescent bulbs.

25

Not long ago LEDs were only bright enough to be used as indicators on dashboards or electronic equipment. But recent advances have made LEDs bright enough to rival traditional lighting technologies. Modern LEDs can replace incandescent bulbs in almost any application. LEDs with a voltage range of 1.2V 3.3V are used for power supply and signal posts. At the signal posts resistors (450 Ohms) are used near LEDs to convert the LEDs to 5V.

4.6 RESISTORS:
A resistor is a two-terminal electronic component designed to oppose an electric current by producing a voltage drop between its terminals in proportion to the current, that is, in accordance with Ohm's law: V = IR Resistors are used as part of electrical networks and electronic circuits. They are extremely commonplace in most electronic equipment. Practical resistors can be made of various compounds and films, as well as resistance wire (wire made of a high-resistivity alloy, such as nickel/chrome). The primary characteristics of resistors are their resistance and the power they can dissipate. Other characteristics include temperature coefficient, noise, and inductance. Less well-known is critical resistance, the value below which power dissipation limits the maximum permitted current flow, and above which the limit is applied voltage. Critical resistance depends upon the materials constituting the resistor as well as its physical dimensions; it's determined by design. Resistors can be integrated into hybrid and printed circuits, as well as integrated circuits. Size, and position of leads (or terminals) are relevant to equipment designers; resistors must be physically large enough not to overheat when dissipating their power.

4.7 CAPACITORS:
A capacitor or condenser is a passive electronic component consisting of a pair of conductors separated by a dielectric. When a voltage potential difference exists between the Conductors, an electric field is present in the dielectric. This field stores energy and produces a mechanical force between the plates.

26

An ideal capacitor is characteri ed by a single constant value, capacitance, which is measured in farads. This is the ratio of the electric charge on each conductor to the potential difference between them. In practice, the dielectric between the plates passes a small amount of leakage current. The conductors and leads introduce an equivalent series resistance and the dielectric has an electric field strength limit resulting in a breakdown voltage. The properties of capacitors in a circuit may determine the resonant frequency and quality factor of a resonant circuit, power dissipation and operating frequency in a digital logic circuit, energy capacity in a high-power system, and many other important aspects. We use the capacitors to absorb the ripples.

4.8 DIODES:
A diode is a semiconductor device which allows current to flow through it in only one direction. Although a transistor is also a semiconductor device, it does not operate the way a diode does. A diode is specifically made to allow current to flow through it in only one direction. Some ways in which the diode can be used are listed here. y y y A diode can be used as a rectifier that converts AC (Alernating Current) to DC t (Direct Current) for a power supply device. Diodes can be used to separate the signal from radio frequencies. Diodes can be used as an on/off switch that controls current. is used to indicate a diode in a circuit diagram. (Anode) (Cathode).

This symbol

The meaning of the symbol is

Current flows from the anode side to the cathode side.

4.8.1 ELECTRICAL CHARACTERISTICS:


When a small voltage is applied to the diode in the forward direction current flows , easily. Because the diode has a certain amount of resistance, the voltage will drop slightly as current flows through the diode. A typical diode causes a voltage drop of about 0.6- 1V (VF) (In the case of silicon diode, almost 0.6V) as shown in figure 2.10.1 This voltage drop needs to be taken into consideration in a circuit which uses many diodes in series. Also, the amount of current passing through the diodes must be considered. When voltage is applied in the reverse direction through a diode, the diodewill have a great resistance to current flow. Different diodes have different characteristics when reverse biased. 27

Figure 4.8.1-1 Electrical Characteristics of Typical Diode

4.9 MAX 232:


_ Meets or Exceeds TIA/EIA-232-F and ITU recommendation V.28 _ Operates from a Single 5-V Power Supply With 1.0-_F Charge-Pump Capacitors _ Operates Up To 120 kbit/s _ Two Drivers and Two Receivers _ 30-V Input Levels _ Low Supply Current . . . 8 mA Typical _ ESD Protection Exceeds JESD 22 2000-V Human-Body Model (A114-A) _ Upgrade with Improved ESD (15-kV HBM) and 0.1-_F Charge-Pump Capacitors is Available With the MAX202 _ Applications TIA/EIA-232-F, Battery-Powered Systems, Terminals, Modems, and Computers absolute maximum ratings over operating free-air temperature range (unless otherwise noted) Input supply voltage range, VCC (see Note 1) . . . . . . . . . . . . . . . . . . . . 0.3 V to 6 V Positive output supply voltage range, VS+ . . . . . .. . . . . . . . . . . VCC 0.3 V to 15 V Negative output supply voltage range, VS . . . . . . . . .. . . . . . . . . . 0.3 V to 15 V 28

Input voltage range, VI: Driver . . . . . . . . . . . . . . . . . . . . . . . . . 0.3 V to VCC + 0.3 V Receiver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 V Output voltage range, VO: T1OUT, T2OUT . . . . . . . . . . VS 0.3 V to VS+ + 0.3 V R1OUT, R2OUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 0.3 V to VCC + 0.3 V Short-circuit duration: T1OUT, T2OUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . Unlimited Package thermal impedance, JA (see Notes 2 and 3): D package . . . . . . 73C/W DW package . . . . . . . . . . . . . . . . . . . . . . . . . . 57C/W N package . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67C/W NS package . . . . . . . . . . . . . . . . . . . . . . . . . . . 64C/W Operating virtual junction temperature, TJ . . . . . . . . . . . . . . . . . . . . . . . . . 150C Storage temperature range, Tstg . . . . . . . . . . . . . . . . . . . . . . . . . 65C to 150C

29

4.10 LIQUID CRYSTAL DISPLAY:


A liquid crystal display (LCD) is a thin, flat electronic visual display that uses the light modulating properties of liquid crystals (LCs). LCs do not emit light directly.They are used in a wide range of applications, including computer monitors, television, instrument panels, aircraft cockpit displays, signage, etc. They are common in consumer devices such as video players, gaming devices, clocks, watches, calculators, and telephones. LCDs have displaced cathode ray tube (CRT) displays in most applications. They are usually more compact, lightweight, portable, less expensive, more reliable, and easier on the eyes. They are available in a wider range of screen sizes than CRT and plasma displays, and since they do not use phosphors, they cannot suffer image burn-in. LCDs are more energy efficient and offer safer disposal than CRTs. Its low electrical power consumption enables it to be used in battery-powered electronic equipment. It is an electronically-modulated optical device made up of any number of pixels filled with liquid crystals and arrayed in front of a light source (backlight) or reflector to produce images in color or monochrome. The earliest discovery leading to the development of LCD technology, the discovery of liquid crystals, dates from 1888. By 2008, worldwide sales of televisions with LCD screens had surpassed the sale of CRT units. Each pixel of an LCD typically consists of a layer of molecules aligned between two transparent electrodes, and two polarizing filters, the axes of transmission of which are (in most of the cases) perpendicular to each other. With no actual liquid crystal between the polarizing filters, light passing through the first filter would be blocked by the second (crossed) polarizer. In most of the cases the liquid crystal has double refraction. The surface of the electrodes that are in contact with the liquid crystal material are treated so as to align the liquid crystal molecules in a particular direction. This treatment typically consists of a thin polymer layer that is unidirectionally rubbed using, for example, a cloth. The direction of the liquid crystal alignment is then defined by the direction of rubbing. Electrodes are made of a transparent conductor called Indium Tin Oxide (ITO).

30

Passive-matrix and active-matrix addressed LCDs

fig 4.10.1 LIQUID CRYSTAL DISPLAY

LCDs with a small number of segments, such as those used in digital watches and pocket calculators, have individual electrical contacts for each segment. An external dedicated circuit supplies an electric charge to control each segment. This display structure is unwieldy for more than a few display elements.

4.10.1 Advantages and disadvantages of LCD


y y y y y y y y

Very compact and light Low power consumption No geometric distortion Little or no flicker depending on backlight technology Not affected by screen burn-in No high voltage or other hazards present during repair/service Can be made in almost any size or shape No theoretical resolution limit

31

4.10.2 Limitations
y

Limited viewing angle, causing color, saturation, contrast and brightness to vary, even within the intended viewing angle, by variations in posture.

Bleeding and uneven backlighting in some monitors, causing brightness distortion, especially toward the edges.

Slow response times, which cause smearing and ghosting artifacts. However, this is mainly a problem with passive-matrix displays. Current generation active-matrix LCDs have response times of 6 ms for TFT panels and 8 ms for S-IPS.

Only one native resolution. Displaying resolutions either requires a video scalar, lowering perceptual quality, or display at 1:1 pixel mapping, in which images will be physically too large or won't fill the whole screen.

32

CHAPTER 5: MEMS SENSOR

5.1 3-Axis Orientation/Motion Detection Sensor:


The MMA7660FC is a 1.5 g 3-Axis Accelerometer with Digital Output (I C). It is a very low power, low profile capacitive MEMS sensor featuring a low pass filter, compensation for 0g offset and gain errors, and conversion to 6-bit digital values at a user configurable samples per second. The device can be used for sensor data changes, product orientation, and gesture detection through an interrupt pin (INT). The device is housed in a small 3mm x 3mm x 0.9mm DFN package.
2

5.2 Features

Digital Output (I C)

3mm x 3mm x 0.9mm DFN Package Low Power Current Consumption: Off Mode: 0.4 A, Standby Mode: 3 A, Active Mode: 47 A at 1 ODR Configurable Samples per Second from 1 to 120 samples a second. Low Voltage Operation: Analog Voltage: 2.4 V - 3.6 V Digital Voltage: 1.71 V - 3.6 V Auto-Wake/Sleep Feature for Low Power Consumption Tilt Orientation Detection for Portrait/Landscape Capability Gesture Detection Including Shake Detection and Tap Detection Robust Design, High Shocks Survivability (10,000 g) RoHS Compliant Halogen Free Environmentally Preferred Product Low Cost

33

5.3 Typical Applications:


Mobile Phone/ PMP/PDA: Orientation Detection (Portrait/ andscape), Image Stability, Text Scroll, Motion Dialing, Tap to Mute

Laptop PC: Anti-Theft Gaming: Motion Detection, Auto-Wake/Sleep For Low Power Consumption Digital Still Camera: image stability

Figure 5.3.1 Pin diagram Of Mems sensor

5.4 ELECTRO STATIC DISCHARGE (ESD)


Although the Free scale accelerometer contains internal 2000 V ESD protection circuitry, extra precaution must be taken by the user to protect the chip from ESD. A charge of over 2000 V can accumulate on the human body or associated test equipment. A charge of this magnitude can alter the performance or cause failure of the chip. When handling the accelerometer, proper ESD precautions should be followed to avoid exposing the device to discharges which may be detrimental to its performance.

34

5.5 PRINCIPLE OF OPERATION The Freescale Accelerometer consists of a MEMS capacitive sensing g-cell and a signal conditioning ASIC contained in a single package. The sensing element is sealed hermetically at the wafer level using a bulk micro machined cap wafer. The g -cell is a mechanical structure formed from semiconductor materials (polysilicon) using masking and etching processes. The sensor can be modeled as a movable beam that moves between two mechanically fixed beams (Figure 4). Two gaps are formed; one being between the movable beam and the first stationary beam and the second between the movable beam and the second stationary beam. The ASIC uses switched capacitor techniques to measure the g-cell capacitors and extract the acceleration data from the difference between the two capacitors. The ASIC also signal conditions and filters (switched capacitor) the signal, providing a digital output that is proportional to acceleration.

5.6 MODES OF OPERATION The sensor has three power modes: Off Mode, Standby Mode, and Active Mode to offer the customer different power consumption options. The sensor is only capable of running in one of these modes at a time. The Off Mode offers the lowest power

consumption, approximately 0.4 A and can only be reached by powering down the analog supply. See Figure 5. In this mode, there is no analog supply and all I 2C activity is ignored. The Standby Mode is ideal for battery operated products. When Standby Mode is active the device outputs are turned off providing a significant reduction in operating current. When the device is in Standby Mode the current will be reduced to approximately 3 A. Standby Mode is entered as soon as both analog and digital power supplies are up. In this mode, the device can read and write to the registers with I 2C, but no new measurements can be taken. The mode of the device is controlled through the MODE (0x07) control register by accessing the mode bit in the Mode register. During the Active Mode, continuous

measurement on all three axes is enabled. In addition, the user can choose to enable: Shake Detection, Tap Detection, Orientation Detection, and/or Auto-Wake/Sleep Feature and in this mode the digital analysis for any of these functions is done. The user can configure the samples per second to any of the following: 1 sample/second, 2 samples/second, 4 samples/second, 8 samples/second, 16 samples/second, 32 samples/second, 64

samples/second, and 120 samples/second, for the Auto-Sleep state.

35

CHAPTER 6: SOFTWARE DEVELOPMENT


6.1 Introduction: In this chapter the software used and the language in which the program code is defined is mentioned and the program code dumping tools are explained. The chapter also documents the development of the program for the application. This program has been termed as Source code. Before we look at the source code we define the two header files that we have used in the code.

6.2 Tools Used:

Figure 6.2.1 Keil Software- internal stages

36

Keil development tools for the 8051 Microcontroller Architecture support every level of software developer from the professional applications

6.3 C51 Compiler & A51 Macro Assembler: Source files are created by the Vision IDE and are passed to the C51 Compiler or A51 Macro Assembler. The compiler and assembler process source files and create replaceable object files. The Keil C51 Compiler is a full ANSI implementation of the C programming language that supports all standard features of the C language. In addition, numerous features for direct support of the 8051 architecture have been added.

6.3.1 VISION What's New in Vision3? Vision3 adds many new features to the Editor like Text Templates, Quick Function Navigation, and Syntax Coloring with brace high lighting Configuration Wizard for dialog based startup and debugger setup. Vision3 is fully compatible to Vision2 and can be used in parallel with Vision2. What is Vision3? Vision3 is an IDE (Integrated Development Environment) that helps you write, compile, and debug embedded programs. It encapsulates the following components:
y y y y y

A project manager. A make facility. Tool configuration. Editor. A powerful debugger. To help you get started, several example programs (located in the \C51\Examples, \C251\Examples, \C166\Examples, and \ARM\...\Examples) are provided.

y y y

HELLO is a simple program that prints the string "Hello World" using the Serial Interface. MEASURE is a data acquisition system for analog and digital systems. TRAFFIC is a traffic light controller with the RTX Tiny operating system. 37

y y y

SIEVE is the SIEVE Benchmark. DHRY is the Dhrystone Benchmark. WHETS is the Single-Precision Whetstone Benchmark. Additional example programs not listed here are provided for each device architecture. BUILDING AN APPLICATION IN VISION To build (compile, assemble, and link) an application in Vision2, you must:

1. Select Project -(forexample,166\EXAMPLES\HELLO\HELLO.UV2). 2. Select Project - Rebuild all target files or Build target. Vision2 compiles, assembles, and links the files in your project. Creating Your Own Application in Vision2 To create a new project in Vision2, you must: 1. Select Project - New Project. 2. Select a directory and enter the name of the project file. 3. Select Project - Select Device and select an 8051, 251, or C16x/ST10 device from the Device Database. 4. Create source files to add to the project. 5. Select Project - Targets, Groups, Files. Add/Files, select Source Group1, and add the source files to the project. 6. Select Project - Options and set the tool options. Note when you select the target device from the Device Database all special options are set automatically. You typically only need to configure the memory map of your target hardware. Default memory model settings are optimal for most applications. 7. Select Project - Rebuild all target files or Build target. Debugging an Application in Vision2 To debug an application created using Vision2, you must: 1. Select Debug - Start/Stop Debug Session. 2. Use the Step toolbar buttons to single-step through your program. You may enter G, main in the Output Window to execute to the main C function. 3. Open the Serial Window using the Serial #1 button on the toolbar. Debug your program using standard options like Step, Go, Break, and so on. Starting Vision2 and Creating a Project Vision2 is a standard Windows application and started by clicking on the program icon. To create a new project file select from the Vision2 menu Project New Project. This opens a standard Windows dialog that asks you 38

for the new project file name. We suggest that you use a separate folder for each project. You can simply use the icon Create New Folder in this dialog to get a new empty folder. Then select this folder and enter the file name for the new project, i.e. Project1. Vision2 creates a new project file with the name PROJECT1.UV2 which contains a default target and file group name. You can see these names in the Project Window Files. Now use from the menu Project Select Device for Target and select a CPU for your project. The Select Device dialog box shows the Vision2 device database. Just select the microcontroller you use. We are using for our examples the Philips 80C51RD+ CPU. This selection sets necessary tool options for the 80C51RD+ device and simplifies in this way the tool Configuration

6.3.2 Building Projects and Creating a HEX Files Typical, the tool settings under Options Target are all you need to start a new application. You may translate all source files and line the application with a click on the Build Target toolbar icon. When you build an application with syntax errors, Vision2 will display errors and warning messages in the Output Window Build page. A double click on a message line opens the source file on the correct location in a Vision2 editor window. Once you have successfully generated your application you can start debugging. After you have tested your application, it is required to create an Intel HEX file to download the software into an EPROM programmer or simulator. Vision2 creates HEX files with each build process when Create HEX files under Options for Target Output is enabled. You may start your PROM programming utility after the make process when you specify the program under the option Run User Program #1. 6.3.3 CPU Simulation Vision2 simulates up to 16 Mbytes of memory from which areas can be mapped for read, write, or code execution access. The Vision2 simulator traps and reports illegal memory accesses. In addition to memory mapping, the simulator also provides support for the integrated peripherals of the various 8051 derivatives. The on-chip peripherals of the CPU you have selected are configured from the Device

39

6.3.4 Database selection You have made when you create your project target. Refer to page 58 for more Information about selecting a device. You may select and display the on -chip peripheral components using the Debug menu. You can also change the aspects of each peripheral using the controls in the dialog boxes. 6.3.5 Start Debugging You start the debug mode of Vision2 with the Debug Start/Stop Debug Session command. Depending on the Options for Target Debug Configuration, Vision2 will load the application program and run the startup code Vision2 saves the editor screen layout and restores the screen layout of the last debug session. If the program execution stops, Vision2 opens an editor window with the source text or shows CPU instructions in the disassembly window. The next executable statement is marked with a yellow arrow. During debugging, most editor features are still available.

For example, you can use the find command or correct program errors. Program source text of your application is shown in the same windows. The Vision2 debug mode differs from the edit mode in the following aspects:
The Debug Menu and Debug Commands described below are available. The additional

debug windows are discussed in the following.


The project structure or tool parameters cannot be modified. All build Commands are

disabled. 6.3.6 Disassembly Window The Disassembly window shows your target program as mixed source and assembly program or just assembly code. A trace history of previously executed instructions may be displayed with Debug View Trace Records. To enable the trace history, set Debug Enable/Disable Trace Recording. If you select the Disassembly Window as the active window all program step commands work on CPU instruction level rather than program source lines. You can select a text line and set or modify code breakpoints using toolbar buttons or the context menu commands.

40

CHAPTER 7:
7 SCHEMATICS AND CODING :
7.1 SCHEMATICS:

41

7.2 CODING:
#include<regx52.h> #include<string.h> #include<INTRINS.h> #define NOP _nop_()

#define LCD P2

unsigned int i,j; unsigned char tilt=0,temp=0,temp1=0 ; //unsigned char temp2=0,temp3=0 ; //unsigned char temp4=0,temp5=0 ; //unsigned char temp6=0,temp7=0 ; sbit sda = P3^6; sbit scl = P3^5; sbit sw1 = P1^0; sbit sw2 = P1^1; sbit sw3 = P1^2; sbit sw4 = P1^3; sbit sw5 = P1^4; sbit rely = P3^4; void init_lcd(void); void cmd_lcd(unsigned char); void write_lcd(unsigned char); void display_lcd(unsigned char *);

void i2c_start(void); void i2c_stop(void); void i2c_write(unsigned char); unsigned char i2c_read(void);

42

unsigned char mems_read(unsigned char); void mems_write(unsigned char,unsigned char); void delay_ms(unsigned int); unsigned int psw=0; void mymemset(char *buf) { char i; for(i=0;i<16;i++) buf[i] = ' '; } void init_lcd(void) { delay_ms(10); cmd_lcd(0x28); cmd_lcd(0x0e ); cmd_lcd(0x06); cmd_lcd(0x0C); cmd_lcd(0x01); cmd_lcd(0x0C); } void cmd_lcd(unsigned char c) { unsigned char temp; temp=c>>4; LCD=temp<<4|0x08; LCD=0; LCD=c<<4|0x08; LCD=0; delay_ms(2); } void write_lcd(unsigned char c) { unsigned char temp; temp=c>>4; LCD=temp<<4|0x0a;

43

LCD=0; LCD=c<<4|0x0a; LCD=0; delay_ms(2); } void display_lcd(unsigned char *s) { while(*s) write_lcd(*s++); }

void delay_ms(unsigned int x) { unsigned int y,z; for(z=0;z<x;z++) for(y=0;y<114;y++); }

void main() { char buff[6]; char index=0; // buzzer=0; rely = 0; tilt = 0x00; init_lcd(); cmd_lcd(0x80); display_lcd(" cmd_lcd(0xc0); display_lcd(" Technologies "); delay_ms(1000); delay_ms(1000); delay_ms(1000); cmd_lcd(0x01); cmd_lcd(0x80); Innovative ");

44

display_lcd("Safty Auto Break"); cmd_lcd(0xc0); display_lcd("for Vech on Hill"); delay_ms(1000); delay_ms(1000); cmd_lcd(0x01); cmd_lcd(0x80); display_lcd(" delay_ms(1000); delay_ms(1000); cmd_lcd(0x01); cmd_lcd(0x80); display_lcd("Rama Krishna 4B 6"); cmd_lcd(0xc0); display_lcd(" cmd_lcd(0x01); cmd_lcd(0x80); display_lcd("NagarjunReddy4C7"); delay_ms(1000); cmd_lcd(0x01); mems_write(0x07,0x00); delay_ms(100); mems_write(0x07,0x01); delay_ms(100); // mems_write( 0x08,0x3f); // delay_ms(100); while(1) { tilt = mems_read(0x00); cmd_lcd(0xc0); temp = (tilt/10)+0x30; Prem Sagar 4B5"); delay_ms(1000); H I T A M ");

45

write_lcd(temp); temp1 = (tilt%10)+0x30; //write_lcd(temp1); delay_ms(50); delay_ms(1000); cmd_lcd(0x01); cmd_lcd(0x80); display_lcd("Normal"); rely = 1; if(temp == '2') { rely = 0; cmd_lcd(0x01); cmd_lcd(0x80); display_lcd("WARNING"); cmd_lcd(0xc0); while(1) { if(sw1 == 0) { while(sw1 == 0); write_lcd('1'); buff[i++] = '1'; } if(sw2 == 0) { while(sw2 == 0); write_lcd('2'); buff[i++] = '2'; } if(sw3 == 0) { while(sw3 == 0); //cmd_lcd(0xc0); write_lcd('3'); buff[i++] = '3';

46

} if(sw4 == 0) { while(sw4 == 0); //cmd_lcd(0xc0); write_lcd('4'); buff[i++] = '4'; } if(sw5 == 0) { while(sw5 == 0); i=0; if((strcmp(buff,"1234")) == 0) { for(i=0;i<6;i++) buff[i] = '\0'; cmd_lcd(0x01); cmd_lcd(0x80); display_lcd("pwd correct"); delay_ms(1000); cmd_lcd(0x01); cmd_lcd(0x80); display_lcd("NORMAL"); rely = 1; while(1); } else { cmd_lcd(0x01); cmd_lcd(0x80); display_lcd("pwd wrong"); cmd_lcd(0xc0); display_lcd("enter pw d"); } break; } }

47

} } unsigned char mems_read(unsigned char addr) { unsigned char memsdata = 0x00; i2c_start(); i2c_write(0x98); NOP;NOP; NOP;NOP; NOP;NOP; i2c_write(addr); NOP;NOP; NOP;NOP; i2c_start(); i2c_write(0x99); memsdata=i2c_read(); i2c_stop(); return memsdata; } void mems_write(unsigned char ad,unsigned char dat) { i2c_start(); i2c_write(0x98); NOP;NOP; NOP;NOP; NOP;NOP; i2c_write(ad); NOP;NOP; NOP;NOP; i2c_write(dat); i2c_stop(); }

48

void i2c_start() { scl = 1; sda = 1; NOP; NOP; sda = 0; scl = 0; } void i2c_stop() { scl = 1; sda = 0; NOP; NOP; sda = 1; scl = 0; } void i2c_write(unsigned char byte) { unsigned char count; for(count = 0; count < 8; count++) { if(byte & 0x80) { sda = 1; } else sda = 0; scl = 1; NOP;NOP; scl = 0; byte <<= 1; } sda=1; NOP;NOP; scl=1; //sda high after the 8 bits transmission completed // 1micro sec and slave pulls down this sda pin. // 1micro sec

49

NOP;NOP; scl=0;

// 1micro sec

} unsigned char i2c_read(void) { unsigned char count,TmpByte; sda = 1; for(count=0; count<8; count++) { scl = 0; NOP;NOP; scl = 1; TmpByte=TmpByte|sda; if(count<=6) TmpByte=TmpByte<<1; } scl = 0; delay_ms(10); return TmpByte; } // 1micro sec

50

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