Introduction To Embedded Systems: What Is An Embedded System?

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 80

1.

INTRODUCTION TO EMBEDDED SYSTEMS


What is an Embedded System? An embedded system can be defined as a computing device that does a specific focused job. Appliances such as the air-conditioner, VCD player, DVD player, printer, fax machine, mobile phone etc. are examples of embedded systems. Each of these appliances will have a processor and special hardware to meet the specific requirement of the application along with the embedded software that is executed by the processor for meeting that specific requirement. The embedded software is also called firm ware. The desktop/laptop computer is a general purpose computer. You can use it for a variety of applications such as playing games, word processing, accounting, software development and so on. In contrast, the software in the embedded systems is always fixed.

1.1 History:
In the earliest years of computers in the 1940s, computers were sometimes dedicated to a single task, but were too large to be considered "embedded". Over time however, the concept of programmable controllers developed from a mix of computer technology, solid state devices, and traditional electromechanical sequences. The first recognizably modern embedded system was the Apollo Guidance Computer, developed by Charles Stark Draper at the MIT Instrumentation Laboratory. At the project's inception, the Apollo guidance computer was considered the riskiest item in the Apollo project. The use of the then new monolithic integrated circuits, to reduce the size and weight, increased this risk. The first mass-produced embedded system was the Autonetics D-17 guidance computer for the Minuteman (missile), released in 1961. It was built from transistor logic and had a hard disk for main memory. When the Minuteman II went into production in 1966, the D-17 was replaced with a new computer that was the first high-volume use of integrated circuits. This program alone reduced prices on quad nand gate ICs from $1000/each to $3/each, permitting their use in commercial products.

Since these early applications in the 1960s, embedded systems have come down in price. There has also been an enormous rise in processing power and functionality. For example the first microprocessor was the Intel 4004, which found its way into calculators and other small systems, but required external memory and support chips. In 1978 National Engineering Manufacturers Association released the standard for a programmable microcontroller. The definition was an almost any computer-based controller. They included single board computers, numerical controllers, and sequential controllers in order to perform event-based instructions. By the mid-1980s, many of the previously external system components had been integrated into the same chip as the processor, resulting in integrated circuits called microcontrollers, and widespread use of embedded systems became feasible. As the cost of a microcontroller fell below $1, it became feasible to replace expensive knob-based analog components such as potentiometers and variable capacitors with digital electronics controlled by a small microcontroller with up/down buttons or knobs. By the end of the 80s, embedded systems were the norm rather than the exception for almost all electronics devices, a trend which has continued since.

1.2 Embedded systems are characterized by some special features listed below:

Embedded systems do a very specific task; they cannot be programmed to do different things. . Embedded systems have very limited resources, particularly the memory. Generally, they do not have secondary storage devices such as the C DROM or the floppy disk. Embedded systems have to work against some deadlines. A specific job has to be completed within a specific time. In some embedded systems, called real-time systems, the deadlines are stringent. Missing a deadline may cause a catastrophe-loss of life or damage to property. Embedded systems are constrained for power. As many embedded systems operate through a battery, the power consumption has to be very low.

Embedded systems need to be highly reliable. Once in a while, pressing ALTCTRL-OEL is OK on your desktop, but you cannot afford to reset your embedded system.
2

Some embedded systems have to operate in extreme environmental conditions such as very high temperatures and humidity. Embedded systems that address the consumer market (for exam-ple, electronic toys) are very cost-sensitive: Even a reduction of $0.1 is lot of cost saving, because thousands or millions systems may be sold.

Unlike desktop computers in which the hardware platform is dominated by Intel and the operating system is dominated by Microsoft, there is a wide variety of processors and operating systems for the embedded systems. So, choosing the right plat-form is the most complex task.

1.3 Categories of Embedded Systems


Based on functionality and performance requirements, embedded systems can be categorized as: Stand-alone embedded systems Real-time systems Networked information appliances Mobile devices

1.3.1 Stand alone Embedded Systems: As the name implies, stand-alone systems work in stand-alone mode. They take inputs, process them and produce the desired output. The input can be electrical signals from transducers or commands from a human being such as the pressing of a button. The output can be electrical signals to drive another system, an LED display or LCD display for displaying of information to the users. Embedded systems used in process co~1rol, automobiles, consumer electronic items etc. fall into this category. In a process control system, the inputs are from sensors that convert a physical entity such as temperature or pressure into its equivalent electrical signal. These electrical signals are processed by the system and the appropriate electrical signals are produced using which an action is taken such as opening a valve. A few embedded systems used at home are shown in fig

Fig: 1.1 1.3.2 REAL TIME SYSTEMS Embedded systems in which some specific work has to be done in a specific time period are called real-time systems. For example, consider a system that has to open a valve within 30 milliseconds when the humidity crosses a particular threshold. If the valve is not opened within 30 milliseconds, a catastrophe may occur. Such systems with strict deadlines are called hard real time systems. In some embedded systems, deadlines are imposed, but not adhering to them once in a while may not lead to a catastrophe. For example, consider a DVD player. Suppose, you give a command to the DVD player from a remote control, and there is a delay of a few milliseconds in executing that command. But, this delay wont lead to a serious implication. Such systems are called soft real-time systems.

Fig: 1.2

1.3.3 NETWORKED INFORMATION APPLIANCES Embedded systems that are provided with network interfaces and accessed by networks such as Local Area Network or the Internet are called networked information appliances. Such embedded systems are connected to a network, typically a network running TCP/IP (Transmission Control Protocol! Internet Protocol) protocol suite, such as the Internet or a companys Intranet. These systems have emerged in recent years These systems run the protocol TCP/IP stack and get connected either through PPP or Ethernet to a network and communicate with other nodes in the network. Here are some examples of such systems:

Fig: 1.3 1.3.4 MOBILE DEVICES Mobile devices such as mobile phones, Personal Digital Assistants (PDAs), smart phones etc. are a special category of embedded systems. Though the PDAs do many general purpose tasks, they need to be designed just like the conventional embedded systems. The limitations of the mobile devices- memory constraints, small size, lack of good user interfaces such as full-fledged keyboard and display etc.-are same as those found in the embedded systems discussed above. Hence, mobile devices are considered as embedded systems. However, the PDAs are now capable of supporting generalpurpose application software such as word processors, games, etc. User interfaces Embedded systems range from no user interface at all - dedicated only to one task - to full user interfaces similar to desktop operating systems in devices such as PDAs. Simple systems Simple embedded devices use buttons, LEDs, and small character- or digit-only displays, often with a simple menu system. In more complex systems A full graphical screen, with touch sensing or screen-edge buttons provides flexibility while minimizing space used: the meaning of the buttons can change with the screen, and selection involves the natural behavior of pointing at what's desired. Handheld systems often have a screen with a "joystick button" for a pointing device. The rise of the World Wide Web has given embedded designers another quite different option: providing a web page interface over a network connection. This avoids the cost of a sophisticated display, yet provides complex input and display capabilities when needed,
6

on another computer. This is successful for remote, permanently installed equipment. In particular, routers take advantage of this ability. CPU platform Embedded processors can be broken into two distinct categories: microprocessors (P) and micro controllers (C). Micro controllers have built-in peripherals on the chip, reducing size of the system. There are many different CPU architectures used in embedded designs such as ARM, MIPS, Cold fire/68k, PowerPC, x86, PIC, 8051, Atmel AVR, Renesas H8, SH, V850, FR-V, M32R, Z80, Z8, etc. This in contrast to the desktop computer market, which is currently limited to just a few competing architectures. PC/104 and PC/104+ are a typical base for small, low-volume embedded and rugged system design. These often use DOS, Linux, NetBSD, or an embedded real-time operating system such as QNX or VxWorks. A common configuration for very-high-volume embedded systems is the system on a chip (SoC), an application-specific integrated circuit (ASIC), for which the CPU core was purchased and added as part of the chip design. A related scheme is to use a field-programmable gate array (FPGA), and program it with all the logic, including the CPU.

1.4 Peripherals:
Embedded Systems talk with the outside world via peripherals, such as:

Serial Communication Interfaces (SCI): RS-232, RS-422, RS-485 etc Synchronous Serial Communication Interface: I2C, JTAG, SPI, SSC and ESSI Universal Serial Bus (USB) Networks: Controller Area Network, Lon Works, etc Timers: PLL(s), Capture/Compare and Time Processing Units Discrete IO: aka General Purpose Input Output (GPIO)

Tools As for other software, embedded system designers use compilers, assemblers, and debuggers to develop embedded system software. However, they may also use some more specific tools:

An in-circuit emulator (ICE) is a hardware device that replaces or plugs into the microprocessor, and provides facilities to quickly load and debug experimental code in the system.

Utilities to add a checksum or CRC to a program, so the embedded system can check if the program is valid.

For systems using digital signal processing, developers may use a math workbench such as MathCAD or Mathematic to simulate the mathematics.

Custom compilers and linkers may be used to improve optimization for the particular hardware. An embedded system may have its own special language or design tool, or add enhancements to an existing language.

Software tools can come from several sources:

Software companies that specialize in the embedded market Ported from the GNU software development tools Sometimes, development tools for a personal computer can be used if the embedded processor is a close relative to a common PC processor

1.5 Debugging:
Embedded Debugging may be performed at different levels, depending on the facilities available, ranging from assembly- or source-level debugging with an in-circuit emulator or in-circuit debugger, to output from serial debug ports or JTAG/Nexus interfaces, to an emulated environment running on a personal computer. As the complexity of embedded systems grows, higher level tools and operating systems are migrating into machinery where it makes sense. For example, cell phones, personal digital assistants and other consumer computers often need significant software that is purchased or provided by a person other than the manufacturer of the electronics.
8

In these systems, an open programming environment such as Linux, NetBSD, OSGi or Embedded Java is required so that the third-party software provider can sell to a large market. Reliability Embedded systems often reside in machines that are expected to run continuously for years without errors and in some cases recover by themselves if an error occurs. Therefore the software is usually developed and tested more carefully than that for personal computers, and unreliable mechanical moving parts such as disk drives, switches or buttons are avoided. Recovery from errors may be achieved with techniques such as a watchdog timer that resets the computer unless the software periodically notifies the watchdog. Specific reliability issues may include: 1. The system cannot safely be shut down for repair, or it is too inaccessible to repair. Solutions may involve subsystems with redundant spares that can be switched over to, or software "limp modes" that provide partial function. Examples include space systems, undersea cables, navigational beacons, borehole systems, and automobiles. 2. The system must be kept running for safety reasons. "Limp modes" are less tolerable. Often backups are selected by an operator. Examples include aircraft navigation, reactor control systems, safety-critical chemical factory controls, train signals, engines on single-engine aircraft. 3. The system will lose large amounts of money when shut down: Telephone switches, factory controls, bridge and elevator controls, funds transfer and market making, automated sales and service. High vs. Low Volume For high volume systems such as portable music players or mobile phones, minimizing cost is usually the primary design consideration. Engineers typically select hardware that is just good enough to implement the necessary functions.

For low-volume or prototype embedded systems, general purpose computers may be adapted by limiting the programs or by replacing the operating system with a real-time operating system. Embedded software architectures There are several different types of software architecture in common use. Simple control loop In this design, the software simply has a loop. The loop calls subroutines, each of which manages a part of the hardware or software. Interrupt controlled system Some embedded systems are predominantly interrupt controlled. This means that tasks performed by the system are triggered by different kinds of events. An interrupt could be generated for example by a timer in a predefined frequency, or by a serial port controller receiving a byte. These kinds of systems are used if event handlers need low latency and the event handlers are short and simple. Usually these kinds of systems run a simple task in a main loop also, but this task is not very sensitive to unexpected delays. The tasks performed in the interrupt handlers should be kept short to keep the interrupt latency to a minimum. Some times longer tasks are added to a queue structure in the interrupt handler to be processed in the main loop later. This method brings the system close to a multitasking kernel with discrete processes. Cooperative multitasking A no preemptive multitasking system is very similar to the simple control loop scheme, except that the loop is hidden in an API. The programmer defines a series of tasks, and each task gets its own environment to "run" in. Then, when a task is idle, it calls an idle routine (usually called "pause", "wait", "yield", etc.). The advantages and disadvantages are very similar to the control loop, except that adding new software is easier, by simply writing a new task, or adding to the queue-interpreter.

10

Preemptive multitasking In this type of system, a low-level piece of code switches between tasks based on a timer. This is the level at which the system is generally considered to have an "operating system", and introduces all the complexities of managing multiple tasks running seemingly at the same time. Any piece of task code can damage the data of another task; they must be precisely separated. Access to shared data must be controlled by some synchronization strategy, such as message queues, semaphores or a non-blocking synchronization scheme. Because of these complexities, it is common for organizations to buy a real-time operating system, allowing the application programmers to concentrate on device functionality rather than operating system services.

4. MICRO CONTROLLER
PHILIPS MICRO CONTROLLER 4.1 INTRODUCTION
The 89C51RD2xx is a low-power, high-performance CMOS 8-bit microcomputer with 4K bytes of Flash programmable and erasable read only memory (PEROM). The device is manufactured using Philips high-density nonvolatile memory technology and is compatible with industry-standard MCS-51 instruction set and pin out. The on-chip Flash allows the program memory to be reprogrammed in-system or by a conventional nonvolatile memory programmer. By combining a versatile 8-bit CPU with Flash on a monolithic chip, the P89C51RD2xx is a powerful microcomputer which provides a highly-flexible and cost-effective solution to many embedded control applications.

11

Features Compatible with MCS-51 Products 4K Bytes of In-System Reprogrammable Flash Memory Endurance: 1000 Write/Erase Cycles. Fully Static Operation: 0Hz to 24MHz Three-level Program Memory Lock 128 x 8- bit Internal RAM 32 Programmable I/O Lines Two 16-bit Timer/Counters Six Interrupt Sources Programmable Serial Channel Low-power Idle and Power-down Modes

4.2 Block Diagram of the AT89C core


EXTERNAL INTERRUPTS ONCHIP TIMER 1 TIMER 0 COUNTER INPUTS

INTERRUP T

ON-CHIP

ON-CHIP FLASH

CPU

OSC

BUSCON TROL

4 I/O PORTS

SERIL PORT

12

PO P2 P1 P3

TXD

RXD

For more information on the individual devices and features, refer to the Hardware Descriptions and Data Sheets of the specific device.

Figure 4.1 Oscillator Connection. The P89C51 provides the following standard features: 4K bytes of Flash, 128 bytes of RAM, 32 I/O lines, two 16-bit timer/counters, five vector two-level interrupt architecture, a full duplex serial port, on-chip oscillator and clock circuitry. In addition,
13

the P89C51 is designed with static logic for operation down to zero frequency and supports two software selectable power saving modes. The Idle Mode stops the CPU while allowing the RAM, timer/counters, serial port and interrupt system to continue functioning. The Power-down Mode saves the RAM contents but freezes the oscillator disabling all other chip functions until the next hardware reset.

14

GND XTAL EXTERIOR NC 1 2 OSCILLAT OR SIGNAL

Figure 4.2 External Clock Drive Configuration

15

PROGRAM MEMORY
FFFFH

DATA MEMORY FFFFH

External

EXTERNAL

INTERNAL
FF

EA = 0

EA = 1
00

0000

PSEN

RD

WR

Figure4.3 Memory Structure of the 8051.

4.3 Memory Organization


Program Memory Figure 4 shows a map of the lower part of the program memory. After reset, the CPU begins execution from location 0000H. As shown in fig.4, each interrupt is assigned a fixed location in program memory. The interrupt causes the CPU to jump to that location, where it executes the service routine. External Interrupt 0, for example, is assigned to location 0003H. If External Interrupt 0 is used, its service routine must begin at location 0003H. If the interrupt is not used, its service location is available as general purpose.

16

RES INTERRU 8 (0033 ET PT bytes )H LOCATIO NS 002B H 0023 H 001B H 0013 H 000B H 0003 H 0000 H

Figure4.4 Program Memory. Program memory addresses are always 16 bits wide, even though the actual amount o program memory used may be less than 64Kbytes. External program execution sacrifices two of the 8-bit ports, P0 and P2, to the function of addressing the program memory. Data Memory The right half of Figure 3 shows the internal and external data memory spaces available on Philips Flash microcontrollers. Fig.6 shows a hardware configuration for accessing up to 2K bytes of external RAM. In this case, the CPU executes from internal flash. Port0 serves as a multiplexed address/data bus to the RAM, and 3 lines of Port 2 are used to page the RAM. The CPU generates RD and WR signals as needed during external RAM accesses. You can assign up to 64K bytes of external data memory. External data memory addresses can be either 1 or 2bytes wide. One-byte addresses are often used in conjunction with one or more other I/O lines to page the RAM, as shown in
17

Fig.6. Two-byte addresses can also be used, in which case the high address byte is emitted at Port2.

Special Internal Data Memory. FFH FF 00 80 Low Upp ACCESSIB ACCESSIB Ports Fig4.5 register H er BY LELE BY Status and function 7F 128 INDIRECT INDIRECT DIRECT control bits H ADDRESSI Timers Registers NG ONLY. NG ONLY NG AND Stack pointer 80H DIRECT Accumulator ADDRESSI (etc) NG

Internal data memory addresses are always 1 byte wide, which implies an address space of only 256bytes. However, the addressing modes for internal RAM can infact accommodate 384 bytes. Direct addresses higher than 7FH access one memory space and indirect addresses higher than 7FH access a different memory space. Thus, Figure.7 shows the Upper 128 and SFR space occupying the same block of addresses, 80H through FFH, although they are physically separate entities. Figure.8 shows how the lower 128 bytes of RAM are mapped. The lowest 32 bytes are grouped into 4 banks of 8 registers. Program instructions call out these registers as R0 through R7. Two bits in the Program Status Word (PSW) select which register bank is in use. This architecture allows more efficient use of code space, since register instructions are shorter than instructions that use direct addressing.

18

Fig.6 The lower 128 bytes of Internal RAM The next 16 bytes above the register banks form a block of bit-addressable memory space. The microcontroller instruction set includes a wide selection of single-bit instructions, and these instructions can directly address the 128 bits in this area. These bit addresses are 00H through 7FH. All of the bytes in the Lower 128 can be accessed by either direct or indirect addressing.

Special Function Register Map


19

F8 F0 E8 E0 D8 D0 C8 C0 B8 B0 A8 A0 98 90 88 80 PSW
(2) (1)

FF B ACC F7 EF E7 DF D7 RCAP2H(2) TL2(2) TH2(2) CF C7 BF B7 AF A7 SBUF TMOD SP


(1)

T2C0N(1) T2MOD(2) RCAP2L(2) IP(1) P3 IE(1) P2 SCON(1) PI TCON PO


(1)

9F 97 TLO DPL TLI DPH THO TH1 PCON(1) BF 87

8 Bytes Bit Addressable Notes: 1. SFRs converting mode or control bits 2. AT89C52only Power-on Reset The reset input is the RST pin, which is the input to a Schmitt Trigger. A reset is accomplished by holding the RST pin high for at least two machine cycles (24 oscillator periods), while the oscillator is running. The CPU responds by generating an internal reset. The external reset signal is asynchronous to the internal clock. The RST pin is sampled during State 5 Phase 2 of every machine cycle. The port pins will maintain their current activities for 19 oscillator periods after a logic 1 has been sampled at the RST pin; that is, for 19 to 31 oscillator periods after the external reset signal has been applied to the RST pin.
20

The internal reset algorithm writes 0s to all the SFRs except the port latches, the Stack Pointer and SBUF. The port latches are initialized to FFH, the Stack Pointer to 07H, and SBUF is indeterminate. The internal RAM is not affected by reset. On power up the RAM content is indeterminate. REGISTER PC ACC B PSW SP DPTR P0-P3 IP IE TMOD TCON TH0 TL0 TH1 SCON SBUF PCON (NMOS) PCON (CMOS) REST VALUE 0000H 00H 00H 00H 07H 0000H FFH XXX0000B 0XX0000B 00H 00H 00H 00H 00H 00H Indeterminate 0XXXXXXXB 0XXX0000B -------------------------------------------------------------------------

4.4 Interrupts

21

The P89C51 provides 5 interrupt sources. The External Interrupts INT0 and INT1 can each be either level-activated or transition-activated, depending on bits IT0 and IT1 in Register TCON. The flags that actually generate these interrupts are bits IE0 and IE1 in TCON. When an external interrupt is generated, the flag that generated it is cleared by the hardware when the service routine is vectored to only if the interrupt was transition-activated. If the interrupt was level-activated, then the external requesting source is what controls the request flag, rather than the on-chip hardware. The Timer0 and Timer 1 Interrupts are generated by TF0 and TF1, which are set by a rollover in their respective Timer/Counter registers (except see Timer0 in Mode3). When a timer interrupt is generated, the flag that generated it is cleared by the on-chip hardware when the service routine is vectored to. The Serial Port Interrupt is generated by the logical OR of RI and TI. Neither of these flags is cleared by hardware when the service routine is vectored to. In fact, the service routine will normally have to determine whether it was RI or TI that generated the interrupt, and the bit will have to be cleared in software. All of the bits that generate interrupts can be set or cleared by software, with the same result as thought it had been set or cleared by hardware. This is, interrupts can be generated or pending interrupts can be canceled in software. Each of these interrupt sources can be individually enabled or disabled by setting or clearing a bit in Special Function Register IE. IE also contains a global disable bit, EA, which disables all interrupts at once. The interrupt flags are sampled a S5P2 of every machine cycle. The samples are polled during the following machine cycle. If one of the flags was in a set condition at S5P2 of the preceding cycle, the polling cycle will find it and the interrupt system will generate an LCALL to the appropriate service routine, provided this hardware-generated LCALL is not blocked by any of the following conditions: 1. 2. 3. An interrupt of equal or higher priority level is already in progress. The current (polling) cycle is not the final cycle in the execution of the instruction in progress. The instruction in progress is RET1 or any write to the IE or IP registers.

22

Any of these three conditions will block the generation of the LCALL to the interrupt service routine. Condition 2 ensures that instruction in progress will be completed before vectoring to any service routine. Condition 3 ensures that if the instruction in progress is RET1 or any access to IE or IP, then at least one more instruction will be executed before any interrupt is vectored to. The poling cycle is repeated with each machine cycle, and the values polled are the values that were present at S5P2 of the previous machine cycle. Note that if any interrupt flag is active but not being responded for one of the above conditions, if the flag is not still active when the blocking condition is removed, the denied interrupt will not be serviced. In other words, the fact that the interrupt flag was once active but not serviced is not remembered. Every polling cycle is new. The processor acknowledges an interrupt request by executing hardware generated LCALL to the appropriate servicing routine. In some cases it also clears the flag that generated the interrupt, and in other cases it doesnt. It never clears the Serial Port flag. This has to be done in the users software. It clears an external interrupt flag (IE0 or IE1) only if it was transition-activated. The hardware generated LCALL pushes the contents of the Program Counter onto the Stack (but it does not save the PSW) and reloads the PC with an address that depends on the source of the interrupt being vectored to. Execution proceeds from that location until the RET1 instruction is encountered. The RET1 instruction informs the processor that this interrupt routine is no longer in progress, then pops the top two bytes from the stack and reloads the Program Counter. Exception of the interrupted program continues fro where it left off. Note that a simple RET instruction would also have returned execution to the interrupted program, but it would have left the interrupt control system thinking an interrupt was still in progress, making future interrupts impossible. External Interrupts The external sources can be programmed to be level-activated or transitionactivated by setting or clearing bit IT1 or IT0 in Register TCON. If ITx=0, external interrupt x is triggered by a detected low at the INTX pin. If ITx=1, external pin x is edge
23

triggered. In this mode if successive samples of the INTX pin show a high in one cycle and a low in the next cycle, interrupt request flag IEx in TCON is set. Flag bit IEx then request the interrupt. Since the external interrupt pins are sampled once each machine cycle, an input high or low should hold for at least 12 oscillator periods to ensure sampling. If the external interrupt is transition-activated, the external source has to hold the request pin high for at least once cycle, and then hold it low for at least one cycle. This is done to ensure that transition is seen so that interrupt request flag IEx will be set. The CPU will automatically clear IEx when the service routine is called. If the external interrupt is level-activated, the external source has to hold the request active until the requested interrupt is actually generated. Then it has to deactivate the request before the interrupt service routine is completed, or else another interrupt will be generated. To use any of the interrupts in the 89C51 Family, the following three steps must be taken. 1. Set the EA (enable all) bit in the IE register to 1. 2. Set the corresponding individual interrupt enable bit in the IE register to 1. 3. Begin the interrupt service routine at the corresponding vector. Address of that interrupt. See Table below. Interrupt Source IE0 TF0 IE1 TF1 RI & TI Vector Address 0003H 000BH 0013H 001BH 0023H ----------------------------------------------------------------

---------------------------------------------------------------In addition, for external interrupts, pins INT0 and INT1(P3.2 and P3.3) must be set to 1, and depending on whether the interrupt is to be level or transition activated, bits IT0 or IT1 in the TCON register may need to be set to 1. ITx=0 level activated
24

ITx=1 listed below: IE0 TF0 IE1 TF1R1 or T1 lowest priority

transition activated Priority within level is only to resolve

simultaneous requests of the same priority level. Form high to low, interrupt sources are highest priority

4.5 TIMERS AND COUNTERS


Timer Set-Up The tables below give some values for TMOD which can be used to set up Timer 0 and Timer 1 in different modes. It is assumed that only one timer is being used at a time. If it is desired to run Timers 0 and 1 simultaneously, in any mode the value in the TMOD for timer 0 must be ORed with value shown for Timer 1. For example, if it is desired to run Timer 0 in mode 1 GATE (external control), and Timer 1 in mode 2 COUNTER, then value that must be loaded into TMOD is 69H (09H from the table for Timer0, ORed with 60H from the table for Timer 1). Moreover, it is assumed that the user, at this point, is not ready to turn the timers on and will do that at a different point in the program by setting bit TRx (in TCON) to 1. TIMER/COUNTER 0 As a Timer: Mode 0 1 2 3 Function 13-bit Timer 16-bit Timer 8-bit Auto-Reload Two 8-bit Timers TMOD (internal control) 00H 01H 02H 03H TMOD (external control) 08H 09H 0AH 0BH

As a Counter: Mode Function TMOD (internal control)


25

TMOD (external control)

0 1 2 3

13-bit Counter 16-bit Counter 8-bit Auto-Reload One 8-bit Counter

04H 05H 06H 07H

0CH 0DH 0EH 0FH

TIMER/COUNTER 1 As a Timer: Mode 0 1 2 3 Function 13-bit Timer 16-bit Timer 8-bit Auto-Reload Does not run TMOD (internal control) 00H 10H 20H 30H TMOD (external control) 80H 90H A0H B0H

As a Counter Mode 0 1 2 3 Function 13-bit Counter 16-bit Counter 8-bit Auto-Reload Not available TMOD (internal control) 40H 50H 60H --TMOD (external control) C0H D0H A0H ---

4.6 Serial Port Set-Up


The serial port is full duplex, meaning it can transmit and receive simultaneously. It is also receive-buffered, meaning it can commence reception of a second byte before a previously received byte has been read form the register. (However, if the first byte still hasnt been read by the time reception of the second byte is complete, one of the bytes will be lost.) The serial port receive and transmit registers are both accessed at Special Function Register SBUF. Writing to SBUF loads the transmit register, and reading SBUF accesses a physically separate receive register.
26

The serial port can operate in 4 modes: Mode 0: Serial data enters and exits through RxD. TxD outputs the shift clock. 8 bits are transmitted/received (LSB first). The baud rate is fixed at 1/12th oscillator frequency. Mode 1: 10 bits are transmitted (through TxD) or received (through RxD): a start bit (0), 8 data bits (LSB first), and a stop bit (1). On receive; the stop bit goes into RB8 in Special Function Register SCON. The baud rate is variable. Mode 2: 11 bits are transmitted (trough TxD) or received (through RxD): start bit (0), 8 data bits (LSB first), a programmable 9th data bit, and a stop bit (1). On transmit, the 9th data bit (TB is SCON) can be assigned the value of 0 or 1. Or, for example, the parity bit (P, in the PSW) could be moved into TB8. On receive; the 9th data bit goes into RB8 in Special Function Register SCON, while the stop bit is ignored. The baud rate is programmable to either 1/32 or 1/64th oscillator frequency. Mode 3: 11 bits are transmitted (through TxD) or received (through RxD): a start bit (0), 8 data bits (LSB first), a programmable 9th data bit, and a stop bit (1). In fact, Mode 3 is the same as Mode2 in all aspects except baud rate. The baud rate in Mode 3 is variable.

Timer 1 Generated Commonly Used Baud Rages The values for the different modes of operation of the serial port are shown in the table below: MODESCON SM2 Variation 0 1 10H 50H Single Processor Environment
27

2 3 0 1 2 3

90H D0H

(SM2 = 0)

Not Available Multiprocessor 70H B0H F0H Environment (SM2 =1) -------------

GENERATING BAUD RATES Serial Port in Mode 0: Mode 0 has a fixed baud rate, which is 1/12th oscillator frequency. To run the serial port in this mode none of the Timer/Counters need to be set up. Only the SCON register needs to be defined. Baud Rate = Oscillator Frequency /12 Serial Port in Mode 1: Mode1 has a variable baud rate. The baud rate is generated by Timer 1. For this purpose, Timer 1 is used in mode2 (Auto-Reload). Baud Rate = (K x Osc.Freq) / (32 x 12 x [256 (TH1)]) If SMOD =0, then K=1. If SMOD =1, then K =2 (SMOD is in the PCON register). Most of the time the user knows the baud rate and needs to know the reload value for TH1. TH1 = 256 (K x Osc.Freq) / (384 x baud rate) TH1 must be an integer value. Rounding off TH1 to the nearest integer may not produce the desired baud rate. In this case, the user may have to choose another crystal frequency.

28

Since the PCON register is not bit addressable, one way to set the bit is logical ORing the PCON register (i.e. ORL PCON, #80H). The address of PCON is 87H. Serial Port in Mode2: The baud rate is fixed in this mode and is 1/32 or 1/64 of the oscillator frequency, depending on the value of the SMOD bit in the PCON register. In this mode none of the Timers are used and the clock comes form the internal phase 2 clock. SMOD = 1, Baud Rate = 1/32 Osc.Freq. SMOD =0, Baud Rate = 1/64 Osc.Freq.

5. SOFTWARE
5.1 Overview of KEIL C cross Compiler
Keil is a cross compiler. So first we have to understand the concept of compilers and cross compilers. After then we shall learn how to work with keil.

Concept of compiler: Compilers are programs used to convert a High Level Language to object code. Desktop compilers produce an output object code for the underlying microprocessor,
29

but not for other microprocessors. I.E the programs written in one of the HLL like C will compile the code to run on the system for a particular processor like x86 (underlying microprocessor in the computer). For example compilers for Dos platform is different from the Compilers for Unix platform So if one wants to define a compiler then compiler is a program that translates source code into object code. The compiler derives its name from the way it works, looking at the entire piece of source code and collecting and reorganizing the instruction. See there is a bit little difference between compiler and an interpreter. Interpreter just interprets whole program at a time while compiler analyzes and execute each line of source code in succession, without looking at the entire program. The advantage of interpreters is that they can execute a program immediately. Secondly programs produced by compilers run much faster than the same programs executed by an interpreter. However compilers require some time before an executable program emerges. Now ascompilers translate source code into object code, which is unique for each type of computer, many compilers are available for the same language.

Concept of cross compiler: A cross compiler is similar to the compilers but we write a program for the target processor (like 8051 and its derivatives) on the host processors (like computer of x86) It means being in one environment you are writing a code for another environment is called cross development. And the compiler used for cross development is called cross compiler So the definition of cross compiler is a compiler that runs on one computer but produces object code for a different type of computer. Cross compilers are used to generate software that can run on computers with a new architecture or on special30

purpose devices that cannot host their own compilers. Cross compilers are very popular for embedded development, where the target probably couldn't run a compiler. Typically an embedded platform has restricted RAM, no hard disk, and limited I/O capability. Code can be edited and compiled on a fast host machine (such as a PC or Unix workstation) and the resulting executable code can then be downloaded to the target to be tested. Cross compilers are beneficial whenever the host machine has more resources (memory, disk, I/O etc) than the target. Keil C Compiler is one such compiler that supports a huge number of host and target combinations. It supports as a target to 8 bit microcontrollers like Atmel and Motorola etc.

Why do we need cross compiler?


There are several advantages of using cross compiler. Some of them are described as follows By using this compilers not only can development of complex embedded systems be completed in a fraction of the time, but reliability is improved, and maintenance is easy. Knowledge of the processor instruction set is not required. A rudimentary knowledge of the 8051s memory architecture is desirable but not necessary. Register allocation and addressing mode details are managed by the compiler. The ability to combine variable selection with specific operations improves program readability. Keywords and operational functions that more nearly resemble the human thought process can be used. Program development and debugging times are dramatically reduced when compared to assembly language programming.

31

The library files that are supplied provide many standard routines (such as formatted output, data conversions, and floating-point arithmetic) that may be incorporated into your application.

Existing routine can be reused in new programs by utilizing the modular programming techniques available with C.

The C language is very portable and very popular. C compilers are available for almost all target systems. Existing software investments can be quickly and easily converted from or adapted to other processors or environments.

Now after going through the concept of compiler and cross compilers lets we start with Keil C cross compiler.

Keil C cross compiler: Keil is a German based Software development company. It provides several development tools like IDE (Integrated Development environment) Project Manager Simulator Debugger C Cross Compiler , Cross Assembler, Locator/Linker

32

Keil Software provides you with software development tools for the 8051 family of microcontrollers. With these tools, you can generate embedded applications for the multitude of 8051 derivatives. Keil provides following tools for 8051 development 1. 2. 3. 4. 5. C51 Optimizing C Cross Compiler, A51 Macro Assembler, 8051 Utilities (linker, object file converter, library manager), Source-Level Debugger/Simulator, Vision for Windows Integrated Development Environment.

The keil 8051 tool kit includes three main tools, assembler, compiler and linker. An assembler is used to assemble your 8051 assembly program A compiler is used to compile your C source code into an object file A linker is used to create an absolute object module suitable for your in-circuit emulator.

8051 project development cycle: - these are the steps to develop 8051 project
using keil Create source files in C or assembly. 1. Compile or assemble source files. 2. Correct errors in source files. 3. Link object files from compiler and assembler. 4. Test linked application. now let us start how to work with keil.

6. Applications of Embedded Systems

33

Nearly 99 per cent of the processors manufactured end up in embedded systems. The embedded system market is one of the highest growth areas as these systems are used in very market segment- consumer electronics, office automation, industrial automation, biomedical engineering, wireless communication, data communication, telecommunications, transportation, military and so on. Consumer appliances: At home we use a number of embedded systems which include digital camera, digital diary, DVD player, electronic toys, microwave oven, remote controls for TV and air-conditioner, VCO player, video game consoles, video recorders etc. Todays hightech car has about 20 embedded systems for transmission control, engine spark control, air-conditioning, navigation etc. Even wristwatches are now becoming embedded systems. The palmtops are powerful embedded systems using which we can carry out many general-purpose tasks such as playing games and word processing. Office automation: The office automation products using embedded systems are copying machine, fax machine, key telephone, modem, printer, scanner etc. Industrial automation: Today a lot of industries use embedded systems for process control. These include pharmaceutical, cement, sugar, oil exploration, nuclear energy, electricity generation and transmission. The embedded systems for industrial use are designed to carry out specific tasks such as monitoring the temperature, pressure, humidity, voltage, current etc., and then take appropriate action based on the monitored levels to control other devices or to send information to a centralized monitoring station. In hazardous industrial environment, where human presence has to be avoided, robots are used, which are programmed to do specific jobs. The robots are now becoming very powerful and carry out many interesting and complicated tasks such as hardware assembly

EMBEDDED APPLICATIONS: Navigation system using a GPS receiver;Communications systems for protocol conversion and VoIP; Mobile data applications using BREWMP3 player and salary
34

survey; Real-time systems using RTLinuxprinting, messaging and more; Windows CE database applications salary survey and energy meter reading; Networked information appliances using the HP Chai Appliance PlatformCRM, location-based services and more; Mobile Java applianceselectronic city guide, Jini appliance control, ACRemote application;Windows XP embedded applications air conditioner remote control, audio player remote control, typing speed indicator, database application, electronic voting.

POWER SUPPLY
TYPES OF POWER SUPPLY There are many types of power supply. Most are designed to convert high voltage AC mains electricity to a suitable low voltage supply for electronics circuits and other devices. A power supply can by broken down into a series of blocks, each of which performs a particular function. For example a 5V regulated supply:

35

Figure3.4 Each of the blocks is described in more detail below:


Transformer - steps down high voltage AC mains to low voltage AC. Rectifier - converts AC to DC, but the DC output is varying. Smoothing - smooths the DC from varying greatly to a small ripple. Regulator - eliminates ripple by setting DC output to a fixed voltage.

Transformer only

Figure3.5 The low voltage AC output is suitable for lamps, heaters and special AC motors. It is not suitable for electronic circuits unless they include a rectifier and a smoothing capacitor and regulator to get pure type of regulated smooth DC signal without any ripples .So after the process of smoothening this DC signal can be used in various electronic circuits.

Transformer + Rectifier + Smoothing+ Regulator

figure3.6

36

From the above graph pure type of regulated smooth DC signal can be achieved.

Interfacing to LCD Display


Liquid Crystal Display also called as LCD is very helpful in providing user interface as well as for debugging purpose. The most common type of LCD controller is HITACHI 44780 which provides a simple interface between the controller & an LCD. These LCD's are very simple to interface with the controller as well as are cost effective. The most commonly used ALPHANUMERICdisplays are 1x16 (Single Line & 16 characters),2x16 (Double Line & 16 character per line) &4x20 (four lines & Twenty characters per line). The LCD requires 3 control lines (RS, R/W & EN) & 8 (or 4) data lines. The number on data lines depends on the mode of operation. If operated in 8-bit mode then 8 data lines + 3 control lines i.e. total 11 lines are required. And if operated in 4-bit mode then 4 data lines + 3 control lines i.e. 7 lines are required. How do we decide which mode to use? Its simple if you have sufficient data lines you can go for 8 bit mode & if there is a time constrain i.e. display should be faster then we have to use 8-bit mode because basically 4bit mode takes twice as more time as compared to 8-bit mode.

37

Most projects you create with the 8051 CPU require some form of display. The most common way to accomplish this is with the LCD (Liquid Crystal Display). LCDs have become a cheap and easy way to get text display for embedded system Common displays are set up as 16 to 20 characters by 1 to 4 lines. When RS is low (0), the data is to be treated as a command. When RS is high (1), the data being sent is considered as text data which should be displayed on the screen. When R/W is low (0), the information on the data bus is being written to the LCD. When RW is high (1), the program is effectively reading from the LCD. Most of the times there is no need to read from the LCD so this line can directly be connected to Gnd thus saving one controller line. The ENABLE pin is used to latch the data present on the data pins. A HIGH - LOW signal is required to latch the data. The LCD interprets and executes our command at the instant the EN line is brought low. If you never bring EN low, your instruction will never be executed.

UNDERSTANDING LCD :

Pinout 8 data pins D7:D0


38

Bi-directional data/command pins. Alphanumeric characters are sent in ASCII format.

RS: Register Select


RS = 0 -> Command Register is selected RS = 1 -> Data Register is selected

R/W: Read or Write


0 -> Write, 1 -> Read

E: Enable (Latch data)


Used to latch the data present on the data pins. A high-to-low edge is needed to latch the data. VEE : contrast control NOTE: When writing to the display, data is transferred only on the high to low transition of this signal. However, when reading from the display, data will become available shortly after the low to high transition and remain available until the signal falls low again.

Display Data RAM (DDRAM)


Display data RAM (DDRAM) is where you send the characters (ASCII code) you want to see on the LCD screen. It stores display data represented in 8-bit character codes. Its capacity is 80 characters (bytes). Below you see DD RAM address layout of a 2*16 LCD.In the above memory map, the area shaded in black is the visible display (For 16x2 display) . For first line addresses for first 15 characters is from 00h to 0Fh. But for second line address of first character is 40h and so on up to 4Fh for the 16th character. So if you want to display the text at specific positions of LCD , we require to manipulate address and then to set cursor position accordingly .

39

Character Generator RAM (CGRAM)-User defined character RAM


In the character generator RAM, we can define our own character patterns by program. CG RAM is 64 bytes ,allowing for eight 5*8 pixel, character patterns to be defined. However how to define this and use it is out of scope of this tutorial. So I will not talk any more about CGRAM

Registers
The HD44780 has two 8-bit registers, an instruction register (IR) and a data register (DR). The IR stores instruction codes. The DR temporarily stores data to be written into DDRAM or CGRAM and temporarily stores data to be read from DDRAM or CGRAM. Data written into the DR is automatically written into DDRAM or CGRAM by an internal operation. . These two registers can be selected by the register selector (RS) signal. See the table below:
Register Selection RS R/W Operation

0 0 1 1

0 IR write as an internal operation (display clear, etc.) 1 Read busy flag (DB7) and address counter (DB0 to DB6) 0 DR write as an internal operation (DR to DDRAM or CGRAM) 1 DR read as an internal operation (DDRAM or CGRAM to DR)

40

Busy Flag (BF)


When the busy flag is 1, the LCD is in the internal operation mode, and the next instruction will not be accepted. When RS = 0 and R/W = 1 (see the table above), the busy flag is output to DB7 (MSB of LCD data bus). The next instruction must be written after ensuring that the busy flag is 0.

LCD Commands
The LCDs internal controller accept several commands and modify the display accordingly. These commands would be things like: Clear screen Return home Shift display right/left
Instruction Decimal 56 48 40 32 See Below 28 24 2 16 20 14 15 12 8 12 1 41 HEX 38 30 28 20 See Below 1E 18 2 10 14 0E 0F 0C 08 0C 01

Function set (8-bit interface, 2 lines, 5*7 Pixels) Function set (8-bit interface, 1 line, 5*7 Pixels) Function set (4-bit interface, 2 lines, 5*7 Pixels) Function set (4-bit interface, 1 line, 5*7 Pixels) Entry mode set Scroll display one character right (all lines) Scroll display one character left (all lines) Home (move cursor to top/left character position) Move cursor one character left Move cursor one character right Turn on visible underline cursor Turn on visible blinking-block cursor Make cursor invisible Blank the display (without clearing) Restore the display (with cursor hidden) Clear Screen

Set cursor position (DDRAM address) Set pointer in character-generator RAM (CG RAM address)

128 + addr 64 + addr

80+ addr 40+ addr

Entry mode set


This command sets cursor move direction and display shift ON/OFF. There are 4 possible function set commands;04, 05, 06, and 07. This command changes the direction the cursor moves by setting the address counter to increment or decrement. This command is very important. If you do not understand it you may not see anything or what you actually wanted to see on LCD screen. I have created 4 animated gifs to demonstrate what the function set command is all about.

Set cursor position (DDRAM address)


As said earlier if we want to display the text at specific positions of LCD , we require to manipulate address and then to set cursor position accordingly. I want to display "MAHESH" in message "Hi MAHESH" at the right corner of first line then I should start from 10th character. So referring to table 80h+0Ah= 8Ah.

INTERFACING LCD TO 8051 :

42

The 44780 standard requires 3 control lines as well as either 4 or 8 I/O lines for the data bus. The user may select whether the LCD is to operate with a 4-bit data bus or an 8-bit data bus. If a 4-bit data bus is used, the LCD will require a total of 7 data lines. If an 8-bit data bus is used, the LCD will require a total of 11 data lines.The three control lines are EN, RS, and RW. Note that the EN line must be raised/lowered before/after each instruction sent to the LCD regardless of whether that instruction is read or write, text or instruction. In short, you must always manipulate EN when communicating with the LCD. EN is the LCD's

43

way of knowing that you are talking to it. If you don't raise/lower EN, the LCD doesn't know you're talking to it on the other lines.

Checking the Busy Flag


You can use subroutine for checking busy flag or just a big (and safe) delay.

1. Set R/W Pin of the LCD HIGH(read from the LCD) 2. Select the instruction register by setting RS pin LOW 3. Enable the LCD by Setting the enable pin HIGH
4. The most significant bit of the LCD data bus is the state of the busy

flag(1=Busy,0=ready to accept instructions/data). The other bits hold the current value of the address counter.
5. If the LCD never come out from "busy" status because of some problems ,The

program will "hang," waiting for DB7 to go low. So in a real applications it would be wise to put some kind of time limit on the delay--for example, a maximum of 100 attempts to wait for the busy signal to go low. This would guarantee that even if the LCD hardware fails, the program would not lock up.

ASSEMBLY LANGUAGE lcall Initialization lcall clear mov a,#'H' lcall data mov a,#'I' lcall data
44

mov a,#8ah lcall command mov a,#'M' lcall data mov a,#'A' lcall data mov a,#'H' lcall data mov a,#'E' lcall data mov a,#'S' lcall data mov a,#'H' lcall data

KEYPAD : Introduction:
Keypads are a part of HMI or Human Machine Interface and play really important role in a small embedded system where human interaction or human input is needed. Martix keypads are well known for their simple architecture and ease of interfacing with any microcontroller. In this part of tutorial we will learn how to interface a 4x4 matrix keypad with AVR and 8051 microcontroller. Also we will see how to program then in Assembly andC.

45

Constructing a Matrix Keypad


Construction of a keypad is really simple. As per the outline shown in the figure below we have four rows and four columns. In between each overlapping row and column line there is a key.

So keeping this outline we can construct a keypad using simple SPST Switches as shown below:

Now our keypad is ready, all we have to do is connect the rows and columns to a port of microcontroller and program the controller to read the input.

Scanning a Matrix Keypad:


There are many methods depending on how you connect your keypad with your
46

controller, but the basic logic is same. We make the columns as i/p and we drive the rows making them o/p, this whole procedure of reading the keyboard is called scanning. In order to detect which key is pressed from the matrix, we make row lines low one by one and read the columns. Lets say we first make Row1 low, then read the columns. If any of the key in row1 is pressed will make the corrosponding column as low i.e. if second key is pressed in Row1, then column2 will give low. So we come to know that key 2 of Row1 is pressed. This is how scanning is done. So to scan the keypad completely, we need to make rows low one by one and read the columns. If any of the button is pressed in a row, it will take the corrosponding column to a low state which tells us that a key is pressed in that row. If button 1 of a row is pressed then Column 1 will become low, if button 2 then column2 and so on...

Keypad Connections with 8051 Microcontroller:

47

How Stepper Motors Work


A stepper motor (or step motor) is a brushless, synchronous electric motor that can divide a full rotation into a large number of steps. The motor's position can be controlled precisely, without any feedback mechanism (see Open-loop controller). Stepper motors are similar to switched reluctance motors (which are very large stepping motors with a reduced pole count, and generally are closed-loop commutated.) Stepper motors consist of a permanent magnet rotating shaft, called the rotor, and electromagnets on the stationary portion that surrounds the motor, called the stator. Figure 1 illustrates one complete rotation of a stepper motor. At position 1, we can see that the rotor is beginning at the upper electromagnet, which is currently active (has voltage applied to it). To move the rotor clockwise (CW), the upper electromagnet is deactivated and the right electromagnet is activated, causing the rotor to move 90 degrees CW, aligning itself with the active magnet. This process is repeated in the same manner at the south and west electromagnets until we once again reach the starting position.

48

Figure 1
In the above example, we used a motor with a resolution of 90 degrees or demonstration purposes. In reality, this would not be a very practical motor for most applications. The average stepper motor's resolution -- the amount of degrees rotated per pulse -- is much higher than this. For example, a motor with a resolution of 5 degrees would move its rotor 5 degrees per step, thereby requiring 72 pulses (steps) to complete a full 360 degree rotation. You may double the resolution of some motors by a process known as "half-stepping". Instead of switching the next electromagnet in the rotation on one at a time, with half stepping you turn on both electromagnets, causing an equal attraction between, thereby doubling the resolution. As you can see in Figure 2, in the first position only the upper electromagnet is active, and the rotor is drawn completely to it. In position 2, both the top and right electromagnets are active, causing the rotor to position itself between the two active poles. Finally, in position 3, the top magnet is deactivated and the rotor is drawn all the way right. This process can then be repeated for the entire rotation.

Figure 2 There are several types of stepper motors. 4-wire stepper motors contain only two electromagnets, however the operation is more complicated than those with three or four magnets, because the driving circuit must be able to reverse the current after each step. For our purposes, we will be using a 6-wire motor.

49

Unlike our example motors which rotated 90 degrees per step, real-world motors employ a series of mini-poles on the stator and rotor to increase resolution. Although this may seem to add more complexity to the process of driving the motors, the operation is identical to the simple 90 degree motor we used in our example. An example of a multipole motor can be seen in Figure 3. In position 1, the north pole of the rotor's perminant magnet is aligned with the south pole of the stator's electromagnet. Note that multiple positions are alligned at once. In position 2, the upper electromagnet is deactivated and the next one to its immediate left is activated, causing the rotor to rotate a precise amount of degrees. In this example, after eight steps the sequence repeats.

Figure 3
The specific stepper motor we are using for our experiments (ST-02: 5VDC, 5 degrees per step) has 6 wires coming out of the casing. If we follow Figure 5, the electrical equivalent of the stepper motor, we can see that 3 wires go to each half of the coils, and that the coil windings are connected in pairs. This is true for all four-phase stepper motors.

50

Figure 5 However, if you do not have an equivalent diagram for the motor you want to use, you can make a resistance chart to decipher the mystery connections. There is a 13 ohm resistance between the center-tap wire and each end lead, and 26 ohms between the two end leads. Wires originating from separate coils are not connected, and therefore would not read on the ohm meter.

Stepper motor characteristics


1. Stepper motors are constant power devices. 2. As motor speed increases, torque decreases. 3. The torque curve may be extended by using current limiting drivers and increasing the driving voltage. 4. Steppers exhibit more vibration than other motor types, as the discrete step tends to snap the rotor from one position to another.
51

5. This vibration can become very bad at some speeds and can cause the motor to lose torque. 6. The effect can be mitigated by accelerating quickly through the problem speeds range, physically damping the system, or using a micro-stepping driver. 7. Motors with a greater number of phases also exhibit smoother operation than those with fewer phases.

Open-loop versus closed-loop commutation


Steppers are generally commutated open loop, ie. the driver has no feedback on where the rotor actually is. Stepper motor systems must thus generally be over engineered, especially if the load inertia is high, or there is widely varying load, so that there is no possibility that the motor will lose steps. This has often caused the system designer to consider the trade-offs between a closely sized but expensive servomechanism system and an oversized but relatively cheap stepper. A new development in stepper control is to incorporate a rotor position feedback (eg. an encoder or resolver), so that the commutation can be made optimal for torque generation according to actual rotor position. This turns the stepper motor into a high pole count brushless servo motor, with exceptional low speed torque and position resolution. An advance on this technique is to normally run the motor in open loop mode, and only enter closed loop mode if the rotor position error becomes too large -- this will allow the system to avoid hunting or oscillating, a common servo problem.

Types
There are three main types of stepper motors: 1. Permanent Magnet Stepper 2. Hybrid Synchronous Stepper 3. Variable Reluctance Stepper Permanent magnet motors use a permanent magnet (PM) in the rotor and operate on the attraction or repulsion between the rotor PM and the stator electromagnets. Variable reluctance (VR) motors have a plain iron rotor and operate based on the principle of that minimum reluctance occurs with minimum gap, hence the rotor points are attracted toward the stator magnet poles. Hybrid stepper motors are named because they use use a
52

combination of PM and VR techniques to achieve maximum power in a small package size.

Two-phase stepper motors


There are two basic winding arrangements for the electromagnetic coils in a two phase stepper motor: bipolar and unipolar.

Unipolar motors
A unipolar stepper motor has two windings per phase, one for each direction of magnetic field. Since in this arrangement a magnetic pole can be reversed without switching the direction of current, the commutation circuit can be made very simple (eg. a single transistor) for each winding. Typically, given a phase, one end of each winding is made common: giving three leads per phase and six leads for a typical two phase motor. Often, these two phase commons are internally joined, so the motor has only five leads. A microcontroller or stepper motor controller can be used to activate the drive transistors in the right order, and this ease of operation makes unipolar motors popular with hobbyists; they are probably the cheapest way to get precise angular movements.

Unipolar stepper motor coils :


(For the experimenter, one way to distinguish common wire from a coil-end wire is by measuring the resistance. Resistance between common wire and coil-end wire is always half of what it is between coil-end and coil-end wires. This is due to the fact that there is actually twice the length of coil between the ends and only half from center (common wire) to the end.) A quick way to determine if the stepper motor is working is to short circuit every two pairs and try turning the shaft, whenever a higher than normal resistance

53

is felt, it indicates that the circuit to the particular winding is closed and that the phase is working. Unipolar stepper motors with six or eight wires may be driven using bipolar drivers by leaving the phase commons disconnected, and driving the two windings of each phase together. It is also possible to use a bipolar driver to drive only one winding of each phase, leaving half of the windings unused.

Bipolar motor
Bipolar motors have a single winding per phase. The current in a winding needs to be reversed in order to reverse a magnetic pole, so the driving circuit must be more complicated, typically with an H-bridge arrangement. There are two leads per phase, none are common. Static friction effects using an H-bridge have been observed with certain drive topologies[citatio Because windings are better utilised, they are more powerful than a unipolar motor of the same weight.

8-lead stepper
An 8 lead stepper is wound like a unipolar stepper, but the leads are not joined to common internally to the motor. This kind of motor can be wired in several configurations: Unipolar. Bipolar with series windings. This gives higher inductance but lower current per winding. Bipolar with parallel windings. This requires higher current but can perform better as the winding inductance is reduced. Bipolar with a single winding per phase. This method will run the motor on only half the available windings, which will reduce the available low speed torque but require less current.

Higher-phase count stepper motors


Multi-phase stepper motors with many phases tend to have much lower levels of vibration, although the cost of manufacture is higher.
54

Stepper motor drive circuits


Stepper motor performance is strongly dependent on the drive circuit. Torque curves may be extended to greater speeds if the stator poles can be reversed more quickly, the limiting factor being the winding inductance. To overcome the inductance and switch the windings quickly, one must increase the drive voltage. This leads further to the necessity of limiting the current that these high voltages may otherwise induce.

L/R drive circuits


L/R drive circuits are also referred to as constant voltage drives because a constant positive or negative voltage is applied to each winding to set the step positions. However, it is winding current, not voltage that applies torque to the stepper motor shaft. The current I in each winding is related to the applied voltage V by the winding inductance L and the winding resistance R. The resistance R determines the maximum current according to Ohm's law I=V/R. The inductance L determines the maximum rate of change of the current in the winding according to the formula for an Inductor dI/dt = V/L. Thus when controlled by an L/R drive, the maximum speed of a stepper motor is limited by its inductance since at some speed, the voltage V will be changing faster than the current I can keep up. With an L/R drive it is possible to control a low voltage resistive motor with a higher voltage drive simply by adding an external resistor in series with each winding. This will waste power in the resistors, and generate heat. It is therefore considered a low performing option, albeit simple and cheap.

Chopper drive circuits


Chopper drive circuits are also referred to as constant current drives because they generate a somewhat constant current in each winding rather than applying a constant voltage. On each new step, a very high voltage is applied to the winding initially. This causes the current in the winding to rise quickly since dI/dt = V/L where V is very large. The current in each winding is monitored by the controller, usually by measuring the voltage across a small sense resistor in series with each winding. When the current exceeds a specified current limit, the voltage is turned off or "chopped", typically using power transistors. When the winding current drops below the specified limit, the voltage
55

is turned on again. In this way, the current is held relatively constant for a particular step position. This requires additional electronics to sense winding currents, and control the switching, but it allows stepper motors to be driven with higher torque at higher speeds than L/R drives. Integrated electronics for this purpose are widely available.

Phase current waveforms


A stepper motor is a polyphase AC synchronous motor (see Theory below), and it is ideally driven by sinusoidal current. A full step waveform is a gross approximation of a sinusoid, and is the reason why the motor exhibits so much vibration. Various drive techniques have been developed to better approximate a sinusoidal drive waveform: these are half stepping and microstepping.

Full step drive (two phases on)


This is the usual method for full step driving the motor. Both phases are always on. The motor will have full rated torque.

Wave drive
In this drive method only a single phase is activated at a time. It has the same number of steps as the full step drive, but the motor will have significantly less than rated torque. It is rarely used.

Half stepping
When half stepping, the drive alternates between two phases on and a single phase on. This increases the angular resolution, but the motor also has less torque at the half step position (where only a single phase is on). This may be mitigated by increasing the current in the active winding to compensate. The advantage of half stepping is that the drive electronics need not change to support it.

Micro stepping
What is commonly referred to as micro stepping is actual "sine cosine micro stepping" in which the winding current approximates a sinusoidal AC waveform. Sine cosine micro stepping is the most common form, but other waveforms are used . Regardless of the waveform used, as the micro steps become smaller, motor operation becomes more
56

smooth. However, the purpose of micro stepping is not usually to achieve smoothness of motion, but to achieve higher position resolution. A micro step driver may split a full step into as many as 256 micro steps. A typical motor may have 200 steps per revolution. Using such a motor with a 256 micro step controller (also referred to as a "divide by 256" controller) results in an angular resolution of 360/(200x256) = 0.00703125 or 51200 discrete positions per revolution. However, it should be noted that such fine resolution is rarely achievable in practice, regardless of the controller, due to mechanical stiction and other sources of error between the specified and actual positions. Step size repeatability is an important step motor feature and a fundamental reason for their use in positioning. Micro stepping can affect the step size repeatability of the motor. Example: many modern hybrid step motors are rated such that the travel of every Full step (example 1.8 Degrees per Full step or 200 Full steps per revolution) will be within 3% or 5% of the travel of every other Full step; as long as the motor is operated with in its specified operating ranges. Several manufacturers show that their motors can easily maintain the 3% or 5% equality of step travel size as step size is reduced from Full stepping down to 1/10th stepping. Then, as the micro stepping divisor number grows, step size repeatability degrades. At large step size reductions it is possible to issue many microstep commands before any motion occurs at all and then the motion can be a "jump" to a new position.

Theory
A step motor can be viewed as a synchronous AC motor with the number of poles (on both rotor and stator) increased, taking care that they have no common denominator. Additionally, soft magnetic material with many teeth on the rotor and stator cheaply multiplies the number of poles (reluctance motor). Modern steppers are of hybrid design, having both permanent magnets and soft iron cores. To achieve full rated torque, the coils in a stepper motor must reach their full rated current during each step. Winding inductance and reverse EMF generated by a moving rotor tend to resist changes in drive current, so that as the motor speeds up, less and less time is spent at full current -- thus reducing motor torque. As speeds further increase, the
57

current will not reach the rated value, and eventually the motor will cease to produce torque.

Pull-in torque
This is the measure of the torque produced by a stepper motor when it is operated without an acceleration state. At low speeds the stepper motor can synchronise itself with an applied step frequency, and this Pull-In torque must overcome friction and inertia.

Pull-out torque
The stepper motor pull-out torque is measured by accelerating the motor to the desired speed and then increasing the torque loading until the motor stalls or "pulls out of synchronism" with the step frequency. This measurement is taken across a wide range of speeds and the results are used to generate the stepper motor's dynamic performance curve. As noted below this curve is affected by drive voltage, drive current and current switching techniques. It is normally recommended to use a safety factor of between 50% and 100% when comparing your desired torque output to the published "pull-Out" torque performance curve of a step motor.

Detent torque
Synchronous electric motors using permanent magnets have a remnant position holding torque (called detent torque, and sometimes included in the specifications) when not driven electrically. Soft iron reluctance cores do not exhibit this behavior.

Stepper motor ratings and specifications


Stepper motors nameplates typically give only the winding current and occasionally the voltage and winding resistance. The rated voltage will produce the rated winding current at DC: but this is mostly a meaningless rating, as all modern drivers are current limiting and the drive voltages greatly exceed the motor rated voltage. A stepper's low speed torque will vary directly with current. How quickly the torque falls off at faster speeds depends on the winding inductance and the drive circuitry it is attached to, especially the driving voltage.

58

Steppers should be sized according to published torque curve, which is specified by the manufacturer at particular drive voltages and/or using their own drive circuitry. It is not guaranteed that you will achieve the same performance given different drive circuitry, so the pair should be chosen with great care.

Applications
Computer-controlled stepper motors are one of the most versatile forms of positioning systems. They are typically digitally controlled as part of an open loop system, and are simpler and more rugged than closed loop servo systems. Industrial applications are in high speed pick and place equipment and multi-axis machine CNC machines often directly driving lead screws or balls crews. In the field of lasers and optics they are frequently used in precision positioning equipment such as linear actuators, linear stages, rotation stages, goniometers, and mirror mounts. Other uses are in packaging machinery, and positioning of valve pilot stages for fluid control systems. Commercially, stepper motors are used in floppy disk drives, flatbed scanners, computer printers, plotters, slot machines, and many more devices.

INTERFACING TO 8051.
To cause the stepper to rotate, we have to send a pulse to each coil in turn. The 8051 does not have sufficient drive capability on its output to drive each coil, so there are a number of ways to drive a stepper, Stepper motors are usually controlled by transistor or driver IC like ULN2003. Driving current for each coil is then needed about 60mA at +5V supply. A Darlington transistor array, ULN2003 is used to increase driving capacity of the 2051 chip. Four 4.7k resistors help the 2051 to provide more sourcing current from the +5V supply.

59

Coil A 0 0 1 1

Coil B 1 0 0 1

Coil C 1 1 0 0

Coil D 0 1 1 0

Step 1 2 3 4

Connecting Unipolar stepper using ULN2003/2004 :

2-wire connection for Unipolar Stepper Motor :

60

61

EEPROM- ELECTRICALLY ERASABLE PROGRAMMABLE READ ONLY MEMORY Features


Low-voltage and Standard-voltage Operation 2.7 (VCC = 2.7V to 5.5V) 1.8 (VCC = 1.8V to 3.6V) Internally Organized 16,384 x 8 and 32,768 x 8 Two-wire Serial Interface Schmitt Trigger, Filtered Inputs for Noise Suppression Bidirectional Data Transfer Protocol 1 MHz (5V), 400 kHz (2.7V, 2.5V) and 100 kHz (1.8V) Compatibility Write Protect Pin for Hardware and Software Data Protection 64-byte Page Write Mode (Partial Page Writes Allowed) Self-timed Write Cycle (5 ms Max) High Reliability Endurance: One Million Write Cycles Data Retention: 40 Years Extended Temperature and Lead-free/Halogen-free Devices Available 8-lead JEDEC PDIP, 8-lead JEDEC and EIAJ SOIC, 8-lead MAP, 8-lead TSSOP, 8lead SAP and 8-ball dBGA2 Packages Die Sales: Wafer Form, Waffle Pack, and Bumped Wafers

Description :
The AT24C128/256 provides 131,072/262,144 bits of serial electrically erasable and programmable read only memory (EEPROM) organized as 16,384/32,768 words of 8 bits each. The devices cascadable feature allows up to 4 devices to share a common Twowire bus.
62

The device is optimized for use in many industrial and commercial applications where low power and low voltage operation are essential. The devices are available in spacesaving 8-lead JEDEC PDIP, 8-lead JEDEC SOIC, 8-lead EIAJ SOIC, 8-lead MAP (24C128), 8-lead TSSOP, 8-lead SOIC Array Package and 8-ball dBGA2 package In addition, the entire family is available in 2.7V (2.7V to 5.5V) and 1.8V (1.8V to 3.6V) versions.

63

*NOTICE: Stresses beyond those listed under Absolute Maximum Ratings may cause permanent damage to the device. This is a stress rating only and functional operation of the device at these or any other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability.

64

BLOCK DIAGRAM

Pin Description SERIAL CLOCK (SCL):


The SCL input is used to positive edge clock data into each EEPROM device and negative edge clock data out of each device.

SERIAL DATA (SDA):


The SDA pin is bidirectional for serial data transfer. This pin is opendrain driven and may be wire-ORed with any number of other open-drain or open collector devices.

65

DEVICE/ADDRESSES (A1, A0):


The A1 and A0 pins are device address inputs that are hardwired or left not connected for hardware compatibility with other AT24CXX devices. When the pins are hardwired, as many as four 128K/256K devices may be addressed on a single bus system (device addressing is discussed in detail under the Device Addressing section). If the pins are left floating, the A1 and A0 pins will be internally pulled down to GND if the capacitive coupling to the circuit board VCC plane is <3 pF. If coupling is >3 pF, Atmel recommends connecting the address pins to GND.

WRITE PROTECT (WP):


The write protect input, when connected to GND, allows normal write operations. When WP is connected high to VCC, all write operations to the memory are inhibited. If the pin is left floating, the WP pin will be internally pulled down to GND if the capacitive coupling to the circuit board VCC plane is <3 pF. If coupling is >3 pF, Atmel recommends connecting the pin to GND.

Memory Organization AT24C128/256, 128K/256K SERIAL EEPROM:


The 128K/256K is internally organized as 256/512 pages of 64-bytes each. Random word addressing requires a 14/15-bit data word address.

Device Operation CLOCK and DATA TRANSITIONS:


The SDA pin is normally pulled high with an external device. Data on the SDA pin may change only during SCL low time periods (see Figure 4 on page 9). Data changes during SCL high periods will indicate a start or stop condition as defined below.

66

START CONDITION:
A high-to-low transition of SDA with SCL high is a start condition which must precede any other command (see Figure 5 on page 9).

STOP CONDITION:
A low-to-high transition of SDA with SCL high is a stop condition. After a read sequence, the stop command will place the EEPROM in a standby power mode (see Figure 5 on page 9).

ACKNOWLEDGE:
All addresses and data words are serially transmitted to and from the EEPROM in 8-bit words. The EEPROM sends a zero during the ninth clock cycle to acknowledge that it has received each word.

STANDBY MODE:
The AT24C128/256 features a low power standby mode which is enabled: a) upon power-up and b) after the receipt of the STOP bit and the completion of any internal operations.

MEMORY RESET:
After an interruption in protocol, power loss or system reset, any two-wire part can be reset by following these steps: (a) Clock up to 9 cycles, (b) look for SDA high in each cycle while SCL is high and then (c) create a start condition as SDA is high.

67

68

69

Device Addressing
The 128K/256K EEPROM requires an 8-bit device address word following a start condition to enable the chip for a read or write operation (see Figure 7 on page 11). The device address word consists of a mandatory one, zero sequence for the first five most significant bits as shown. This is common to all two-wire EEPROM devices. The 128K/256K uses the two device address bits A1, A0 to allow as many as four devices on the same bus. These bits must compare to their corresponding hardwired input pins. The A1 and A0 pins use an internal proprietary circuit that biases them to a logic low condition if the pins are allowed to float. The eighth bit of the device address is the read/write operation select bit. A read operation is initiated if this bit is high and a write operation is initiated if this bit is low. Upon a compare of the device address, the EEPROM will output a zero. If a compare is not made, the device will return to a standby state.

DATA SECURITY:
The AT24C128/256 has a hardware data protection scheme that allows the user to write protect the whole memory when the WP pin is at VCC.

Write Operations BYTE WRITE:


A write operation requires two 8-bit data word addresses following the device address word and acknowledgment. Upon receipt of this address, the EEPROM will again respond with a zero and then clock in the first 8-bit data word. Following receipt of the 8bit data word, the EEPROM will output a zero. The addressing device, such as a microcontroller, then must terminate the write sequence with a stop condition. At this time the EEPROM enters an internally-timed write cycle, tWR, to the nonvolatile memory. All inputs are disabled during this write cycle and the EEPROM will not respond until the write is complete .

70

PAGE WRITE:
The 128K/256K EEPROM is capable of 64-byte page writes. A page write is initiated the same way as a byte write, but the microcontroller does not send a stop condition after the first data word is clocked in. Instead, after the EEPROM acknowledges receipt of the first data word, the microcontroller can transmit up to 63 more data words. The EEPROM will respond with a zero after each data word received. The microcontroller must terminate the page write sequence with a stop condition . The data word address lower 6 bits are internally incremented following the receipt of each data word. The higher data word address bits are not incremented, retaining the memory page row location. When the word address, internally generated, reaches the page boundary, the following byte is placed at the beginning of the same page. If more than 64 data words are transmitted to the EEPROM, the data word address will roll over and previous data will be overwritten. The address roll over during write is from the last byte of the current page to the first byte of the same page.

ACKNOWLEDGE POLLING:
Once the internally-timed write cycle has started and the EEPROM inputs are disabled, acknowledge polling can be initiated. This involves sending a start condition followed by the device address word. The read/write bit is representative of the operation desired. Only if the internal write cycle has completed will the EEPROM respond with a zero, allowing the read or write sequence to continue.

Read Operations
Read operations are initiated the same way as write operations with the exception that the read/write select bit in the device address word is set to one. There are three read operations: current address read, random address read and sequential read.

CURRENT ADDRESS READ:


71

The internal data word address counter maintains the last address accessed during the last read or write operation, incremented by one. This address stays valid between operations as long as the chip power is maintained. The address roll over during read is from the last byte of the last memory page, to the first byte of the first page. Once the device address with the read/write select bit set to one is clocked in and acknowledged by the EEPROM, the current address data word is serially clocked out. The microcontroller does not respond with an input zero but does generate a following stop condition

RANDOM READ:
A random read requires a dummy byte write sequence to load in the data word address. Once the device address word and data word address are clocked in and acknowledged by the EEPROM, the microcontroller must generate another start condition. The microcontroller now initiates a current address read by sending a device address with the read/write select bit high. The EEPROM acknowledges the device address and serially clocks out the data word. The microcontroller does not respond with a zero but does generate a following

stop condition . SEQUENTIAL READ:


Sequential reads are initiated by either a current address read or a random address read. After the microcontroller receives a data word, it responds with an acknowledge. As long as the EEPROM receives an acknowledge, it will continue to increment the data word address and serially clock out sequential data words. When the memory address limit is reached, the data word address will roll over and the sequential read will continue. The sequential read operation is terminated when the microcontroller does not respond with a zero but does generate a following stop condition .

72

73

74

BUZZER- How

the Buzzer Works

For a better understanding of the buzzers operation, look at the circuit diagram. Imagine youve just pressed the code key down. Lets see what happens, starting at the corner terminal of the battery.

Circuit Diagram

Instantly, current shoots downward to the brass contactor screw. Since the screw is touching the vibrator arm, the cur- rent continues on its way into the coil. Out of the coil it streaks past the closed code key and back to the battery. As in the electric pencil, this flow of current creates a magnetic field around the iron bolt. Having become an electro- magnet, the bolt attracts the vibrator arm. But as the arm starts to swing toward the bolt, it opens the circuit. Hence, the current stops. As a result, the magnetic field collapses, allowing the vibrator arm to spring back against the contactor. With the circuit now restored, current starts flowing again . . .and the cycle starts anew. No matter how quickly we press and release the code key, the current will still make hundreds of round trips through the circuit. And because of the resulting rapid motions of
75

the vibrator arm, a buzzing sound is heard. Not only is the code set fun to build, but it is even more fun to use, especially with a fellow operator. So that both of you can send as well as receive messages, you will want to build two identical sets of buzzers and code keys. Theyre really not hard to make. For each set you will need the following materials.

76

L293d - DRIVER

600mA OUTPUT CURRENT CAPABILITY PER CHANNEL 1.2A PEAK OUTPUT CURRENT (non repetitive) PER CHANNEL ENABLE FACILITY OVERTEMPERATUREPROTECTION LOGICAL 0 INPUT VOLTAGE UP TO 1.5 V (HIGH NOISE IMMUNITY) INTERNAL CLAMP DIODES

77

DESCRIPTION
The Device is a monolithic integrated high voltage, high current four channel driver designed to accept standard DTL or TTL logic levels and drive inductive loads (such as relays solenoides, DC and stepping motors) and switching power transistors. To simplify use as two bridges each pair of channels is equipped with an enable input. A separate supply input is provided for the logic, allowing operation at a lower voltage and internal clamp diodes are included. This device is suitable for use in switching applications at frequencies up to 5 kHz. The L293D is assembled in a 16 lead plastic package which has 4 center pins connected togetherand used for heats inking The L293DD is assembled in a 20 lead surface mount which has 8 center pins connected together and used for heat sinking

78

CONCLUSION
In this report we have provided an overview of some important issue of accessing a given system by providing passwords. Here the passwords are stored in EEPROM to which the input is given through a MATRIX KEYBOARD .Emphasizing directions explored at our laboratory from hardware to software development. The success of the concept behind the EEPROM and KEYBOARD interfacing is indeed to take the input from keypad and store in EEPROM and to access when it is required. This can be used in various applications of research development, industrial application and people from other disciplines. In this project we have provided an overview of how EEPROM and KEYPAD interfacing with integrated circuit.

79

REFERENCES
The 8051 Microcontroller and Embedded Systems

M.A Mazidi & J.G Mazidi John Axelson -Matt Gilliland

The Microcontroller Idea Book

The Microcontroller Application Cookbook


Digital design -Morris Mano

80

You might also like