Microcontrollers and their application

71
Introduction A digital computer typically consists of 3 major components: the central processing unit (CPU),program and data memory, and an input output system. The CPU controls the flow of information among the components of the computer. It also processes the data by performing digital operations. Most of the processing is done in the Arithmetic-Logic Unit(ALU) within the CPU. When the CPU of a computer is build on a single printed circuit board, the computer is called a mini computer. A microprocessor is a CPU i.e. compacted into a single chip semiconductor device. Microprocessors are general purpose devices, suitable for many application. A computer built around a microprocessor is called a microcomputer. The choice of i/o and memory devices of a microcomputer depends on the specific application. For example, most personal computer contain a keyboard and a monitor as a standard input and output devices. A microcontroller is an entire computer manufactured on a single chip. Microcontrollers usually dedicated devices embedded within an application, for example microcontrollers are used as engine controllers in automobiles and as exposure and focus controllers in cameras. In order to serve these applications, they have a high concentration of on chip facilities such as serial ports, parallel input output ports, timers, counters ,interrupt control, analog to digital converters, random access memory, read only memory, etc. The i/o memory and on-chip peripherals of a microcontroller are selected depending on the specifics of the target application. Since microcontrollers are powerful digital processors, the degree of control and programmability they provide significantly enhances the effectiveness of the application.

description

About micro controllers and micro processors with their applications.

Transcript of Microcontrollers and their application

Page 1: Microcontrollers and their application

IntroductionA digital computer typically consists of 3 major components: the central processing unit (CPU),program and data memory, and an input output system. The CPU controls the flow of information among the components of the computer. It also processes the data by performing digital operations. Most of the processing is done in the Arithmetic-Logic Unit(ALU) within the CPU. When the CPU of a computer is build on a single printed circuit board, the computer is called a mini computer. A microprocessor is a CPU i.e. compacted into a single chip semiconductor device. Microprocessors are general purpose devices, suitable for many application. A computer built around a microprocessor is called a microcomputer. The choice of i/o and memory devices of a microcomputer depends on the specific application. For example, most personal computer contain a keyboard and a monitor as a standard input and output devices.

A microcontroller is an entire computer manufactured on a single chip. Microcontrollers usually dedicated devices embedded within an application, for example microcontrollers are used as engine controllers in automobiles and as exposure and focus controllers in cameras. In order to serve these applications, they have a high concentration of on chip facilities such as serial ports, parallel input output ports, timers, counters ,interrupt control, analog to digital converters, random access memory, read only memory, etc.

The i/o memory and on-chip peripherals of a microcontroller are selected depending on the specifics of the target application. Since microcontrollers are powerful digital processors, the degree of control and programmability they provide significantly enhances the effectiveness of the application.

Microcontroller vs MicroprocessorMicroprocessor and microcontroller are two popular terms in world of computer. However, microprocessor and microcontroller has different functions and features.

Microprocessor generally requires external components or circuits to implement program memory, RAM memory and input/output Intel’s 8085,80386 and Pentium are examples of microprocessors. Microcontrollers incorporate program memory, RAM memory and input output port into one chip. Microchip’s PIC series and Atmel’s AVR series are examples of microcontrollers.

Page 2: Microcontrollers and their application

One of the main difference is that microcontrollers are usually designed to perform a small set of specific functions, for example, as in the case of a automatic braking system which performs a small set of input processing functions, whereas microprocessors tend to be designed to perform a wider set of general purpose functions. For example, microcontrollers are widely used in modem cars which they will each perform a dedicated task, that is, a microcontroller to regulate the brakes on all four wheels, or a microcontroller to regulate the car air conditioning, or a microcontroller for automatic gate system.

These microcontrollers will perform few other tasks (if any) other than those specified.Compare to a microprocessor in a PC which performs a wide range of the task related to the general requirements of a PC such as performing the necessary calculations for a wide set of software

applications, performing input output for the main subsystems, peripheral control and etc.

Embedded SystemsAn embedded system is a computer system designed to perform one or a few dedicated functions,often with real time computing constraints,It is embedded as a part of complete device often including hardware and mechanical parts.In contrast, general purpose computer , such as personal computer, is designed to be flexible and to meet a wide range of a users need. Embedded system control many of the common devices in use today.

Embedded systems are controlled by a main processing core that is typically either a microcontroller or a digital signal processor(DSP).

Page 3: Microcontrollers and their application

Since the embedded system is dedicated to specific task, design engineers can optimize if reducing the size and the cost of the product and increasing the reliability and performance. Some embedded systems are mass produced, benefiting from economies of the scale.

Physically, embedded systems range from portable devices such as digital watches and MP3 players, to large stationary installations like traffic lights, factory controllers, or the systems controlling nuclear power plants. Complexity varies from low with a single microcontroller or enclosure.

In general embedded system is not an exactly defined term, as many systems have element of programmability. For example, hand held computers share some elements with embedded systems such as the OS and the microprocessors which powers them, but are not truly embedded systems , because they allow different applications to be loaded and peripherals to be connected.

Varieties of embedded systems:-

Embedded systems span all aspects of a model lift and there are many examples of their use.

Telecommunication systems employ numerous embedded systems from telephone switches for the network to mobile phones at the end user.

Computer networking uses dedicated routers and network bridges to route data.

Transportation system from flight to automobiles increasingly use embedded systems. New airplanes contain advance avionics such as inertial guidance systems and GPS receivers that also have considerable safety requirements.

Medical equipments containing to advance with more embedded systems for vital signs monitoring, electronics stethoscopes for amplifying sounds and various medical imaging (PET,SPECT,CT,MRI) for non invasive inertial inspections.

Embedded systems are designed to do some specific tasks, rather than to be general purpose computer for multiple task. Some also have real time performance constraints that must be met, for reasons such as safety and usability and others may have low or no performance requirements, allowing the system hardware to be simplified to reduce costs hardware resources: little memory, small or non existent keyboard or screen.

Harvard and von Neumann architecture

Page 4: Microcontrollers and their application

The Harvard architecture is a computer architecture with physically separate storage and signal pathways for instructions and data. The term originated from the Harvard Mark Irelay-based computer, which stored instructions on punched tape (24 bits wide) and data in electro-mechanical counters. These early machines had data storage entirely contained within the central processing unit, and provided no access to the instruction storage as data. Programs needed to be loaded by an operator; the processor could not boot itself.

Today, most processors implement such separate signal pathways for performance reasons but actually implement a Modified Harvard architecture, so they can support tasks such as loading a program from disk storage as data and then executing it.

The term Von Neumann architecture, also known as the Von Neumann model or the Princeton architecture, derives from a 1945 computer architecture proposal by the mathematician and early computer scientist John von Neumann and others. This describes a design architecture for an electronic digital computer with subdivisions of a processing unit consisting of an arithmetic logic unit and processor registers, a control unit containing an instruction register and program counter, a memory to store both data and instructions, external mass storage, and input and output mechanisms. The meaning of the term has evolved to mean a stored-program computer in which an instruction fetch and a data operation cannot occur at the same time because they share a common bus. This is referred to as the Von Neumann bottleneck and often limits the performance of the system.

The design of a Von Neumann architecture is simpler than the more modern Harvard architecture which is also a stored-program system but has one dedicated set of address and data buses for memory, and another set of address and data buses for fetching instructions.

Under pure von Neumann architecture the CPU can be either reading an instruction or reading/writing data from/to the memory. Both cannot occur at the same time since the instructions and data use the same bus system. In a computer using the Harvard architecture, the CPU can both read an instruction and perform a data memory access at the same time, even without a cache. A Harvard architecture computer can thus be faster for a given circuit complexity because instruction fetches and data access do not contend for a single memory pathway.

Also, a Harvard architecture machine has distinct code and data address spaces: instruction address zero is not the same as data address zero. Instruction address zero might identify a twenty-four bit value, while data address zero might indicate an eight bit byte that isn't part of that twenty-four bit value.

A modified Harvard architecture machine is very much like a Harvard architecture machine, but it relaxes the strict separation between instruction and data while still letting the CPU concurrently access two (or more) memory buses. The most common modification includes separate instruction and data caches backed by a common address space. While the CPU executes from cache, it acts as a pure Harvard machine. When accessing backing memory, it acts like a von Neumann machine (where code can be moved around like data, a powerful technique).

Page 5: Microcontrollers and their application

RISC and CISCCISC:-The primary goal of CISC architecture is to complete a task in as few lines of assembly as possible. This is achieved by building processor hardware that is capable of understanding and executing a series of operations. For this particular task, a CISC processor would come prepared with a specific instruction (we'll call it "MULT"). When executed, this instruction loads the two values into separate registers, multiplies the operands in the execution unit, and then stores the product in the appropriate register. Thus, the entire task of multiplying two numbers can be completed with one instruction:

MULT 2:3, 5:2

MULT is what is known as a "complex instruction." It operates directly on the computer's memory banks and does not require the programmer to explicitly call any loading or storing functions. It closely resembles a command in a higher level language. For instance, if we let "a" represent the value of 2:3 and "b" represent the value of 5:2, then this command is identical to the C statement "a = a * b."

One of the primary advantages of this system is that the compiler has to do very little work to translate a high-level language statement into assembly. Because the length of the code is relatively short, very little RAM is required to store instructions. The emphasis is put on building complex instructions directly into the hardware.

RISC:-RISC processors only use simple instructions that can be executed within one clock cycle. Thus, the "MULT" command described above could be divided into three separate commands: "LOAD," which moves data from the memory bank to a register, "PROD," which finds the product of two operands located within the registers, and "STORE," which moves data from a

Page 6: Microcontrollers and their application

register to the memory banks. In order to perform the exact series of steps described in the CISC approach, a programmer would need to code four lines of assembly:

LOAD A, 2:3LOAD B, 5:2PROD A, BSTORE 2:3, A

At first, this may seem like a much less efficient way of completing the operation. Because there are more lines of code, more RAM is needed to store the assembly level instructions. The compiler must also perform more work to convert a high-level language statement into code of this form.

However, the RISC strategy also brings some very important advantages. Because each instruction requires only one clock cycle to execute, the entire program will execute in approximately the same amount of time as the multi-cycle "MULT"

command. These RISC "reduced instructions" require less transistors of hardware space than the complex instructions, leaving more room for general purpose registers. Because all of the instructions execute in a uniform amount of time (i.e. one clock), pipelining is possible.

Types of MicrocontrollersThe predominant family of microcontrollers are 8 bit types since this word size has proved popular for the vast majority of task the devices have been required to perform. The microcontroller family would have a common instruction subset but family members differ in the amount,and type of memory,timer facility and port options possessed, thus producing cost effective devices suitable for particular manufacturing requirements.

There are 4 major 8 bit microcontrollers. They are Freescale’s 6811, Intel’s 8051, Ziglog’s ZS and PIC 16x from microchip technology. Each of these microcontrollers have a unique set of instructions and register set, therefore they are not compatible with each other.

CISC RISCEmphasis on hardware Emphasis on softwareIncludes multi-clockcomplex instructions

Single-clock,reduced instruction only

Memory-to-memory:"LOAD" and "STORE"incorporated in instructions

Register to register:"LOAD" and "STORE"are independent instructions

Small code sizes,high cycles per second

Low cycles per second,large code sizes

Transistors used for storingcomplex instructions

Spends more transistorson memory registers

Page 7: Microcontrollers and their application

8051 MicrocontrollerThe Intel MCS-51 (commonly referred to as 8051) is a Harvard architecture, single chip microcontroller (µC) series which was developed by Intel in 1980 for use in embedded systems. Intel's original versions were popular in the 1980s and early 1990s. While Intel no longer manufactures the MCS-51, binary compatible derivatives remain popular today. In addition to these physical devices, several companies also offer MCS-51 derivatives as IP cores for use in FPGAs or ASICs designs.

Intel's original MCS-51 family was developed using NMOS technology, but later versions, identified by a letter C in their name (e.g., 80C51) used CMOS technology and consumed less power than their NMOS predecessors. This made them more suitable for battery-powered devices.

Comparison of 8051 Family MembersFeatures 8051 8052 8031

ROM 4K 8K 0K

RAM(bytes) 128 256 128

Timers 2 3 2

I/o pins 32 32 32

Serial port 1 1 1

Interrupt sources 6 8 6

Important features and applications

Page 8: Microcontrollers and their application

The 8051 architecture provides many functions (CPU, RAM, ROM, I/O, interrupt logic, timer, etc.) in a single package

8-bit ALU, Accumulator and 8-bit Registers; hence it is an 8-bit microcontroller 8-bit data bus – It can access 8 bits of data in one operation 16-bit address bus – It can access 216 memory locations – 64 KB (65536 locations) each of

RAM and ROM On-chip RAM – 128 bytes (data memory) On-chip ROM – 4 kByte (program memory) Four byte bi-directional input/output port UART (serial port) Two 16-bit Counter/timers Two-level interrupt priority Power saving mode (on some derivatives)

One particularly useful feature of the 8051 core was the inclusion of a Boolean processing engine which allows bit-level Boolean logic operations to be carried out directly and efficiently on select internal registers and select RAM locations. This advantageous feature helped cement the 8051's popularity in industrial control applications because it reduced code size by as much as 30%. Another valued feature is the inclusion of four bank selectable working register sets which greatly reduce the amount of time required to complete an interrupt service routine. With a single instruction the 8051 can switch register banks as opposed to the time consuming task of transferring the critical registers to the stack or designated RAM locations. These registers also allowed the 8051 to quickly perform a context switch which is essential for time sensitive real-time applications.

The MCS-51 UARTs make it simple to use the chip as a serial communications interface. External pins can be configured to connect to internal shift registers in a variety of ways, and the internal timers can also be used, allowing serial communications in a number of modes, both synchronous and asynchronous. Some modes allow communications with no external components. A mode compatible with an RS-485 multi-point communications environment is achievable, but the 8051's real strength is fitting in with existing ad-hoc protocols (e.g., when controlling serial-controlled devices).

Once a UART, and a timer if necessary, have been configured, the programmer needs only to write a simple interrupt routine to refill the send shift register whenever the last bit is shifted out by the UART and/or empty the full receive shift register (copy the data somewhere else). The main program then performs serial reads and writes simply by reading and writing 8-bit data to stacks.

MCS-51 based microcontrollers typically include one or two UARTs, two or three timers, 128 or 256 bytes of internal data RAM (16 bytes of which are bit-addressable), up to 128 bytes of I/O, 512 bytes to 64 kB of internal program memory, and sometimes a quantity of extended data RAM (ERAM) located in the external data space. The original 8051 core ran at 12 clock cycles per machine cycle, with most instructions executing in one or two machine cycles. With a 12 MHz clock frequency, the 8051 could thus execute 1 million one-cycle instructions per

Page 9: Microcontrollers and their application

second or 500,000 two-cycle instructions per second. Enhanced 8051 cores are now commonly used which run at six, four, two, or even one clock per machine cycle, and have clock frequencies of up to 100 MHz, and are thus capable of an even greater number of instructions per second. All SILabs, some Dallas and a few Atmel devices have single cycle cores.

Features of the modern 8051 include built-in reset timers with brown-out detection, on-chip oscillators, self-programmable Flash ROM program memory, built-in external RAM, extra internal program storage, bootloader code in ROM, EEPROM non-volatile data storage, I²C, SPI, and USB host interfaces, CAN or LIN bus, PWM generators, analog comparators,A/D and D/A converters, RTCs, extra counters and timers, in-circuit debugging facilities, more interrupt sources, and extra power saving modes.

Memory architecture

The MCS-51 has four distinct types of memory – internal RAM, special function registers, program memory, and external data memory.

Internal RAM (IRAM) is located from address 0 to address 0xFF. IRAM from 0x00 to 0x7F can be accessed directly, and the bytes from 0x20 to 0x2F are also bit-addressable. IRAM from 0x80 to 0xFF must be accessed indirectly, using the @R0 or @R1 syntax, with the address to access loaded in R0 or R1.

Special function registers (SFR) are located from address 0x80 to 0xFF, and are accessed directly using the same instructions as for the lower half of IRAM. Some of the SFR's are also bit-addressable.

Program memory (PMEM, though less common in usage than IRAM and XRAM) is located starting at address 0. It may be on- or off-chip, depending on the particular model of chip being used. Program memory is read-only, though some variants of the 8051 use on-chip flash memory and provide a method of re-programming the memory in-system or in-application. Aside from storing code, program memory can also store tables of constants that can be accessed by MOVC A, @DPTR, using the 16-bit special function register DPTR.

External data memory (XRAM) also starts at address 0. It can also be on- or off-chip; what makes it "external" is that it must be accessed using the MOVX (Move external) instruction. Many variants of the 8051 include the standard 256 bytes of IRAM plus a few KB of XRAM on the chip. If more XRAM is required by an application, the internal XRAM can be disabled, and all MOVX instructions will fetch from the external bus

8051 Instruction Set ACALL : Absolute Call ADD, ADDC : Add Accumulator (With Carry) AJMP : Absolute Jump ANL : Bitwise AND CJNE : Compare and Jump if Not Equal

Page 10: Microcontrollers and their application

CLR : Clear Register CPL : Complement Register DA : Decimal Adjust DEC : Decrement Register DIV : Divide Accumulator by B DJNZ : Decrement Register and Jump if Not Zero INC : Increment Register JB : Jump if Bit Set JBC : Jump if Bit Set and Clear Bit JC : Jump if Carry Set JMP : Jump to Address JNB : Jump if Bit Not Set JNC : Jump if Carry Not Set JNZ : Jump if Accumulator Not Zero JZ : Jump if Accumulator Zero LCALL : Long Call LJMP : Long Jump MOV : Move Memory MOVC : Move Code Memory MOVX : Move Extended Memory MUL : Multiply Accumulator by B NOP : No Operation ORL : Bitwise OR POP : Pop Value From Stack PUSH : Push Value Onto Stack RET : Return From Subroutine RETI : Return From Interrupt RL : Rotate Accumulator Left RLC : Rotate Accumulator Left Through Carry RR : Rotate Accumulator Right RRC : Rotate Accumulator Right Through Carry SETB : Set Bit SJMP : Short Jump SUBB : Subtract From Accumulator With Borrow SWAP : Swap Accumulator Nibbles XCH : Exchange Bytes XCHD : Exchange Digits XRL : Bitwise Exclusive OR Undefined : Undefined Instruction

Page 11: Microcontrollers and their application

ADDRESSING MODESAn "addressing mode" refers to how you are addressing a given memory location. In summary, the addressing modes are as follows, with an example of each:

Immediate Addressing MOV A,#20h

Direct Addressing MOV A,30h

Indirect Addressing MOV A,@R0

External Direct MOVX A,@DPTR

Code Indirect MOVC A,@A+DPTR

Each of these addressing modes provides important flexibility.

Immediate Addressing

Immediate addressing is so-named because the value to be stored in memory immediately follows the operation code in memory. That is to say, the instruction itself dictates what value will be stored in memory.

For example, the instruction:

MOV A,#20h

This instruction uses Immediate Addressing because the Accumulator will be loaded with the value that immediately follows; in this case 20 (hexidecimal).

Immediate addressing is very fast since the value to be loaded is included in the instruction. However, since the value to be loaded is fixed at compile-time it is not very flexible.

Direct Addressing

Direct addressing is so-named because the value to be stored in memory is obtained by directly retrieving it from another memory location. For example:

MOV A,30h

This instruction will read the data out of Internal RAM address 30 (hexidecimal) and store it in the Accumulator.

Page 12: Microcontrollers and their application

Direct addressing is generally fast since, although the value to be loaded isnt included in the instruction, it is quickly accessable since it is stored in the 8051s Internal RAM. It is also much more flexible than Immediate Addressing since the value to be loaded is whatever is found at the given address--which may be variable.

Also, it is important to note that when using direct addressing any instruction which refers to an address between 00h and 7Fh is referring to Internal Memory. Any instruction which refers to an address between 80h and FFh is referring to the SFR control registers that control the 8051 microcontroller itself.

The obvious question that may arise is, "If direct addressing an address from 80h through FFh refers to SFRs, how can I access the upper 128 bytes of Internal RAM that are available on the 8052?" The answer is: You cant access them using direct addressing. As stated, if you directly refer to an address of 80h through FFh you will be referring to an SFR. However, you may access the 8052s upper 128 bytes of RAM by using the next addressing mode, "indirect addressing."

Indirect Addressing

Indirect addressing is a very powerful addressing mode which in many cases provides an exceptional level of flexibility. Indirect addressing is also the only way to access the extra 128 bytes of Internal RAM found on an 8052.

Indirect addressing appears as follows:

MOV A,@R0

This instruction causes the 8051 to analyze the value of the R0 register. The 8051 will then load the accumulator with the value from Internal RAM which is found at the address indicated by R0.

For example, lets say R0 holds the value 40h and Internal RAM address 40h holds the value 67h. When the above instruction is executed the 8051 will check the value of R0. Since R0 holds 40h the 8051 will get the value out of Internal RAM address 40h (which holds 67h) and store it in the Accumulator. Thus, the Accumulator ends up holding 67h.

Indirect addressing always refers to Internal RAM; it never refers to an SFR. Thus, in a prior example we mentioned that SFR 99h can be used to write a value to the serial port. Thus one may think that the following would be a valid solution to write the value 1 to the serial port:

MOV R0,#99h ;Load the address of the serial portMOV @R0,#01h ;Send 01 to the serial port -- WRONG!!

This is not valid. Since indirect addressing always refers to Internal RAM these two instructions would write the value 01h to Internal RAM address 99h on an 8052. On an

Page 13: Microcontrollers and their application

8051 these two instructions would produce an undefined result since the 8051 only has 128 bytes of Internal RAM.

External Direct

External Memory is accessed using a suite of instructions which use what I call "External Direct" addressing. I call it this because it appears to be direct addressing, but it is used to access external memory rather than internal memory.

There are only two commands that use External Direct addressing mode:

MOVX A,@DPTRMOVX @DPTR,A

As you can see, both commands utilize DPTR. In these instructions, DPTR must first be loaded with the address of external memory that you wish to read or write. Once DPTR holds the correct external memory address, the first command will move the contents of that external memory address into the Accumulator. The second command will do the opposite: it will allow you to write the value of the Accumulator to the external memory address pointed to by DPTR.

External Indirect

External memory can also be accessed using a form of indirect addressing which I call External Indirect addressing. This form of addressing is usually only used in relatively small projects that have a very small amount of external RAM. An example of this addressing mode is:

MOVX @R0,A

Once again, the value of R0 is first read and the value of the Accumulator is written to that address in External RAM. Since the value of @R0 can only be 00h through FFh the project would effectively be limited to 256 bytes of External RAM. There are relatively simple hardware/software tricks that can be implemented to access more than 256 bytes of memory using External Indirect addressing; however, it is usually easier to use External Direct addressing if your project has more than 256 bytes of External RAM.

TimersThe 8051 comes equipped with two timers, both of which may be controlled, set, read, and configured individually. The 8051 timers have three general functions: 1) Keeping time and/or calculating the amount of time between events, 2) Counting the events themselves, or 3) Generating baud rates for the serial port.Obviously, one of the primary

Page 14: Microcontrollers and their application

uses of timers is to measure time. When a timer is used to measure time it is also called an "interval timer" since it is measuring the time of the interval between two events.

Timer SFRs

The 8051 has two timers which each function essentially the same way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and TCON) which control the timers, and each timer also has two SFRs dedicated solely to itself (TH0/TL0 and TH1/TL1).

The SFRs relating to timers are:

SFR Name Description SFR AddressTH0 Timer 0 High Byte 8ChTL0 Timer 0 Low Byte 8AhTH1 Timer 1 High Byte 8DhTL1 Timer 1 Low Byte 8BhTCON Timer Control 88hTMOD Timer Mode 89h

On entering the name of an SFR into an assembler, it internally converts it to a number. For example, the command:

MOV TH0,#25h

moves the value 25h into the TH0 SFR. However, since TH0 is the same as Saddress 8Ch this command is equivalent to:

MOV 8Ch,#25h

Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0. When Timer 0 has a value of 0, both TH0 and TL0 will contain 0. When Timer 0 has the value 1000, TH0 will hold the high byte of the value (3 decimal) and TL0 will contain the low byte of the value (232 decimal). Reviewing low/high byte notation, multiply the high byte by 256 and add the low byte to calculate the final value.

TH0 * 256 + TL0 = 10003 * 256 + 232 = 1000

Timer 1 works the exact same way, but its SFRs are TH1 and TL1.

Since there are only two bytes devoted to the value of each timer it is apparent that the maximum value a timer may have is 65,535. If a timer contains the value 65,535 and is subsequently incremented, it will reset--or overflow--back to 0.

Page 15: Microcontrollers and their application

The TMOD SFR

Control SFR: TMOD (Timer Mode). The TMOD SFR is used to control the mode of operation of both timers. Each bit of the SFR gives the microcontroller specific information concerning how to run a timer. The high four bits (bits 4 through 7) relate to Timer 1 whereas the low four bits (bits 0 through 3) perform the exact same functions, but for timer 0.

The individual bits of TMOD have the following functions:

TMOD (89h) SFRBit Name Explanation of Function Timer

7 GATE1When this bit is set the timer will only run when INT1 (P3.3) is high. When this bit is clear the timer will run regardless of the state of INT1.

1

6 C/T1When this bit is set the timer will count events on T1 (P3.5). When this bit is clear the timer will be incremented every machine cycle.

1

5 T1M1 Timer mode bit (see below) 14 T1M0 Timer mode bit (see below) 1

3 GATE0When this bit is set the timer will only run when INT0 (P3.2) is high. When this bit is clear the timer will run regardless of the state of INT0.

0

2 C/T0When this bit is set the timer will count events on T0 (P3.4). When this bit is clear the timer will be incremented every machine cycle.

0

1 T0M1 Timer mode bit (see below) 00 T0M0 Timer mode bit (see below) 0

The modes of operation are:TxM1 TxM0 Timer Mode Description of Mode0 0 0 13-bit Timer.0 1 1 16-bit Timer1 0 2 8-bit auto-reload1 1 3 Split timer mode

13-bit Time Mode (mode 0)

Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to maintain compatibility with its predecessor, the 8048. Generally the 13-bit timer mode is not used in new development.

Page 16: Microcontrollers and their application

When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is incremented from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two timer bytes are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in essence, the timer can only contain 8192 values. If a 13-bit timer is set to 0, it will overflow back to zero 8192 machine cycles later.

16-bit Time Mode (mode 1)

Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions just like 13-bit mode except that all 16 bits are used.

TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and causes THx to be incremented by 1. Since this is a full 16-bit timer, the timer may contain up to 65536 distinct values. If you set a 16-bit timer to 0, it will overflow back to 0 after 65,536 machine cycles.

8-bit Time Mode (mode 2)

Timer mode "2" is an 8-bit auto-reload mode. What is that, you may ask? Simple. When a timer is in mode 2, THx holds the "reload value" and TLx is the timer itself. Thus, TLx starts counting up. When TLx reaches 255 and is subsequently incremented, instead of resetting to 0 (as in the case of modes 0 and 1), it will be reset to the value stored in THx.

For example, TH0 holds the value FDh and TL0 holds the value FEh.

Machine Cycle TH0 Value TL0 Value1 FDh FEh2 FDh FFh3 FDh FDh4 FDh FEh5 FDh FFh6 FDh FDh7 FDh FEh

What is the benefit of auto-reload mode? If we want the timer to always have a value from 200 to 255 and we use mode 0 or 1, we have to check in code to see if the timer had overflowed and, if so, reset the timer to 200. This takes precious instructions of execution time to check the value and/or to reload it. When we use mode 2 the microcontroller takes care of this for us. Once we configured a timer in mode 2 we don’t have to worry about checking to see if the timer has overflowed nor do you have to worry about resetting the value--the microcontroller hardware will do it all.

Page 17: Microcontrollers and their application

The auto-reload mode is very commonly used for establishing a baud rate.

Split Timer Mode (mode 3)

Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially becomes two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0. Both timers count from 0 to 255 and overflow back to 0. All the bits that are related to Timer 1 will now be tied to TH0.

While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into modes 0, 1 or 2 normally--however, you may not start or stop the real timer 1 since the bits that do that are now linked to TH0. The real timer 1, in this case, will be incremented every machine cycle no matter what.

The only real use I can see of using split timer mode is if you need to have two separate timers and, additionally, a baud rate generator. In such case you can use the real Timer 1 as a baud rate generator and use TH0/TL0 as two separate timers.

The TCON SFR

Finally, theres one more SFR that controls the two timers and provides valuable information about them. The TCON SFR has the following structure:

TCON (88h) SFR

Bit Name Bit Address

Explanation of Function Timer

7 TF1 8Fh Timer 1 Overflow. This bit is set by the microcontroller when Timer 1 overflows.

1

6 TR1 8Eh Timer 1 Run. When this bit is set Timer 1 is turned on. When this bit is clear Timer 1 is off.

1

5 TF0 8Dh Timer 0 Overflow. This bit is set by the microcontroller when Timer 0 overflows.

0

4 TR0 8Ch Timer 0 Run. When this bit is set Timer 0 is turned on. When this bit is clear Timer 0 is off.

0

As you may notice, weve only defined 4 of the 8 bits. Thats because the other 4 bits of the SFR dont have anything to do with timers--they have to do with Interrupts and they will be discussed in the chapter that addresses interrupts.

A new piece of information in this chart is the column "bit address." This is because this SFR is "bit-addressable." What does this mean? It means if you want to set the bit TF1--which is the highest bit of TCON--you could execute the command:

MOV TCON, #80h

Page 18: Microcontrollers and their application

... or, since the SFR is bit-addressable, you could just execute the command:

SETB TF1

This has the benefit of setting the high bit of TCON without changing the value of any of the other bits of the SFR. Usually when you start or stop a timer you dont want to modify the other values in TCON, so you take advantage of the fact that the SFR is bit-addressable.

Programming languages

ASSEMBLY

When an 8051 is first initialized, it resets the PC to 0000h. The 8051 then begins to execute instructions sequentially in memory unless a program instruction causes the PC to be otherwise altered. There are various instructions that can modify the value of the PC; specifically, conditional branching instructions, direct jumps and calls, and "returns" from subroutines. Additionally, interrupts, when enabled, can cause the program flow to deviate from its otherwise sequential scheme.

Conditional Branching

The 8051 contains a suite of instructions which, as a group, are referred to as "conditional branching" instructions. These instructions cause program execution to follow a non-sequential path if a certain condition is true.

For example, the JB instruction. This instruction means "Jump if Bit Set." An example of the JB instruction might be:

JB 45h,HELLO

NOP

HELLO: ....

In this case, the 8051 will analyze the contents of bit 45h. If the bit is set program execution will jump immediately to the label HELLO, skipping the NOP instruction. If the bit is not set the conditional branch fails and program execution continues, as usual, with the NOP instruction which follows.

Page 19: Microcontrollers and their application

Conditional branching is really the fundamental building block of program logic since all "decisions" are accomplished by using conditional branching. Conditional branching can be thought of as the "IF...THEN" structure in 8051 assembly language.

An important note worth mentioning about conditional branching is that the program may only branch to instructions located within 128 bytes prior to or 127 bytes following the address which follows the conditional branch instruction. This means that in the above example the label HELLO must be within +/- 128 bytes of the memory address which contains the conditional branching instruction.

Direct Jumps

While conditional branching is extremely important, it is often necessary to make a direct branch to a given memory location without basing it on a given logical decision. This is equivalent to saying "Goto" in BASIC. In this case you want the program flow to continue at a given memory address without considering any conditions.

This is accomplished in the 8051 using "Direct Jump and Call" instructions. As illustrated in the last paragraph, this suite of instructions causes program flow to change unconditionally.

Consider the example:

LJMP NEW_ADDRESS

.

.

.

NEW_ADDRESS: ....

The LJMP instruction in this example means "Long Jump." When the 8051 executes this instruction the PC is loaded with the address of NEW_ADDRESS and program execution continues sequentially from there.

The obvious difference between the Direct Jump and Call instructions and the conditional branching is that with Direct Jumps and Calls program flow always changes. With conditional branching program flow only changes if a certain condition is true.

Direct Calls

Another operation that will be familiar to seasoned programmers is the LCALL instruction.

Page 20: Microcontrollers and their application

When the 8051 executes an LCALL instruction it immediately pushes the current Program Counter onto the stack and then continues executing code at the address indicated by the LCALL instruction.

Returns from Routines

Another structure that can cause program flow to change is the "Return from Subroutine" instruction, known as RET in 8051 Assembly Language.

The RET instruction, when executed, returns to the address following the instruction that called the given subroutine. More accurately, it returns to the address that is stored on the stack.

The RET command is direct in the sense that it always changes program flow without basing it on a condition, but is variable in the sense that where program flow continues can be different each time the RET instruction is executed depending on from where the subroutine was called originally.

Program To Blink A LED

org 0hstart: Clr P0.0 ; send '0' to P0.0 call delay; call delay timeSetb P0.0 ; send '1' to P0.0 call delay; call delay timesjmp start; loop forever to start;=============================================;subroutine delay created to rise delay time;=============================================delay: mov R1,#255del1: mov R2,#255del2: djnz R2,del2djnz R1,del1 retend

C LANGUAGEC is a general-purpose programming language initially developed by Dennis Ritchie between

1969 and 1973 at Bell Labs. Its design provides constructs that map efficiently to typical

machine instructions, and therefore it found lasting use in applications that had formerly been

coded in assembly language—most notably system software like the Unix operating system. C is

Page 21: Microcontrollers and their application

one of the most widely used programming languages of all time, and there are very

few computer architectures for which a C compiler does not exist.

C is an imperative (procedural) systems implementation language. It was designed to be compiled using a relatively straight forward compiler, to provide low-level access to memory, to provide language constructs that map efficiently to machine instructions, and to require minimal run-time support. C was therefore useful for many applications that had formerly been coded in assembly language.

Despite its low-level capabilities, the language was designed to encourage cross-platform programming. A standards-compliant and portably written C program can be compiled for a very wide variety of computer platforms and operating systems with few changes to its source code. The language has become available on a very wide range of platforms, from embedded microcontrollers to supercomputers.

C is often used for "system programming", including implementing operating

systems and embedded system applications, due to a combination of desirable characteristics

such as code portability and efficiency, ability to access specific hardware addresses, ability

to pun types to match externally imposed data access requirements, and low run-time demand on

system resources. C can also be used for website programming using CGI as a "gateway" for

information between the Web application, the server, and the browser. Some reasons for

choosing C over interpreted languages are its speed, stability, and near-universal availability.

Sample Program In C

#include<stdio.h> //header file inclusion

main() //main function declaration

{ // main function definition starts here

printf(“Hello World\n”); //calling the functions declared in header files

return(0); //returning 0 means the program has

//successfully terminated

}

EMBEDDED C

Page 22: Microcontrollers and their application

Embedded C is a set of language extensions for the C Programming language by the C Standards committee to address commonality issues that exist between C extensions for different embedded systems. Historically, embedded C programming requires nonstandard extensions to the C language in order to support exotic features such as fixed-point arithmetic, multiple distinct memory banks, and basic I/O operations.

In 2008, the C Standards Committee extended the C language to address these issues by providing a common standard for all implementations to adhere to. It includes a number of features not available in normal C, such as, fixed-point arithmetic, named address spaces, and basic I/O hardware addressing.

Embedded C use most of the syntax and semantics of standard C, e.g., main() function, variable definition, datatype declaration, conditional statements (if, switch. case), loops (while, for), functions, arrays and strings, structures and union, bit operations, macros, etc.

The use of C language to program microcontrollers is becoming too common. And most of the time it is not easy to build an application in assembly which instead you can make easily in C.

So it is important that you know C language for microcontroller which is commonly known as Embedded C. In case of 8051, we use Keil C51 Compiler, part of keil uvision4 IDE ,hence we also call it Keil C.

Data Types

A good understanding of C data types for 8051 can help programmers to create smaller hex files

unsigned char

signed char

unsigned int

signed int

sbit (single bit)

bit and sfr

The character data type is the most natural choice

8051 is an 8-bit microcontroller

Unsigned char is an 8-bit data type in the range of 0 – 255 (00 – FFH)

One of the most widely used data types for the 8051

- Counter value

- ASCII characters

Page 23: Microcontrollers and their application

C compilers use the signed char as the default if we do not put the keyword unsigned

Header Files/Libraries

Reg51.h

Regx51.h

AT89C51.h etc

, which defines both the peripherals and registers of 8051.

Embedded C is highly compiler dependent as, the extensions required for embedded systems is

generally provided by compiler only.

Input / Output Operation

Point to Remember

The four 8-bit I/O ports P0, P1, P2 and P3 each uses 8 pins.

All the ports upon RESET are configured as input, ready to be used as input ports

When the first 0 is written to a port, it becomes an output.

To reconfigure it as an input, a 1 must be sent to the port.

To use any of these ports as an input port, it must be programmed.

Sending Data | 1 Bit operation using Delay

#include <reg51.h>

sbit led=P1^0; //defining Port 1.0 as Led output port

voidMSDelay(unsigned int); //defining a delay function

void main(void) // Main function

{

led=0;

while (1) //repeat forever

Page 24: Microcontrollers and their application

{

led=0; // sending 0 at P1.0

MSDelay(250); // function call

Led=1;

MSDelay(250);

}

}

voidMSDelay(unsigned intitime) // delay function

{

unsignedinti,j;

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

for (j=0;j<1275;j++);}

Interfacing The process of interconnecting two or more devices to each other in order to exchange

data is called hardware interfacing. Interfacing includes :

The design of the interfacing circuit. The type of medium used for data transfer (wired or wireless).

The protocol on which the data transfer or communication is taking place (RS232, Bluetooth, TCP/IP).

LED INTERFACING

// Program to blink a LED in Port 2.0 [1 bit operation]

Page 25: Microcontrollers and their application

#include<reg51.h> // Including header file

voidmsdelay(unsigned int a);

sbit led = P2^0; // Defining Port 2.0 as Led port

void main() // Main function

{ while(1) // infinite loop

{ led=0;

msdelay(500);

led=1;

msdelay(500); } }

// delay function

voidmsdelay(unsigned int a)

{ unsignedinti,j;

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

for(j=0;j<1275;j++); }

Interfacing 7 segment display:-

Page 26: Microcontrollers and their application

Seven segment display is a basic type of output device, which can display numbers from 0 to 9. Driving a 7 segment display is as simple as driving LEDs, but here the difference is we are lighting up 7+1 LEDs in a specific pattern. The 7 segment display module has 8 LEDs (7 segments to display number and one segment for decimal point or dot) arranged in a 10 pin module as shown in the image below.

By driving (in the sense controlling ON and OFF conditions) these LEDs in various combinations, we can display the numbers 0 to 9. There are basically two types of 7 segment displays, they are common cathode and common anode. In common cathode, the cathodes of all the LED segments are connected together, we should apply a logic 1 or high input to a segment pin to light up that particular segment, and in common cathode the case is opposite. Table below shows the combinations of inputs to be applied to 7 segment display for digits 0 to 9

Page 27: Microcontrollers and their application

For common cathode displays

Digit binary input value hex input value

0 11111100 FC1 01100000 602 11011010 DA3 11110010 F24 01100110 665 10110110 B66 10111110 BE7 11100000 E08 11111110 FE9 11110110 F6

For common anode displays

Digit binary input value hex input value

0 00000011 031 10011111 9F2 00100101 253 00001101 0D4 10011001 995 01001001 496 01000001 417 00011111 1F8 00000001 019 00001001 09

The assembly language source code for interfacing 7 segment display is given below.

;*************************************************;;Program: Driving seven segment display

;Main programorg 0000hljmp mainorg 30h

main:mov r0,#08hmov a,#00000001b ;test all segments of dispup: rr amov port,aacall delaydjnz r0,up

again:mov port,#11111100b ;'0'acall delaymov port,#01100000b ;'1'acall delaymov port,#11011010b ;'2'acall delaymov port,#11110010b ;'3'acall delaymov port,#01100110b ;'4'acall delaymov port,#10110110b ;'5'acall delay

Page 28: Microcontrollers and their application

mov port,#10111110b ;'6'acall delaymov port,#11100000b ;'7'acall delaymov port,#11111110b ;'8'acall delaymov port,#11110110b ;'9'acall delaysjmp again

;*************************************************

delay:mov r2,#0ffh ;delay subroutineup3: mov r4,#03fhup2: mov r3,#0fhup1: djnz r3,up1djnz r4,up2djnz r2,up3ret

;*************************************************

end

Interfacing dc motor:-

The first thing comes to mind when making a robot is making the robot move on the ground. And there are always two options in front of the designer whether to use a DC motor or a stepper motor. When it comes to speed, weight, size, cost... DC motors are always preffered over stepper motors. There are many things which you can do with your DC motor when interfaced with a microcontroller. For example you can control the speed of motor, you can control the direction of rotation, you can also do encoding of the rotation made by DC motor i.e. keeping track of how many turns are made by your motors etc. So you can see DC motors are no less than a stepper motor.

Usually H-bridge is preferred way of interfacing a DC motor. These days many IC manufacturers have H-bridge motor drivers available in the market like L293D is most used H-Bridge driver IC. H-bridge can also be made with the help of transistors and MOSFETs etc. rather of being cheap, they only increase the size of the design board, which is sometimes not required so using a small 16 pin IC is preferred for this purpose.

The name "H-Bridge" is derived from the actual shape of the switching circuit which control the

Page 29: Microcontrollers and their application

motion of the motor. It is also known as "Full Bridge". Basically there are four switching elements in the H-Bridge as shown in the figure below.

In figure above there are four switching elements named as "High side left", "High side right", "Low side right", "Low side left". When these switches are turned on in pairs motor changes its

direction accordingly. Like, if we switch on High side left and Low side right then motor rotate in forward direction, as current flows from Power supply through the motor coil goes to ground

via switch low side right.

Similarly, when we switch on low side left and high side right, the current flows in opposite direction and motor rotates in backward direction.

CODE:

#include <AT89X51.H>#define L293D_A P2_0 //Positive of motor#define L293D_B P2_1 //Negative of motor#define L293D_E P2_2 //Enable of L293D

// Function Prototypesvoid rotate_f(void); //Forward run funtionvoid rotate_b(void); //Backward run functionvoid breaks(void); //Motor stop functionvoid delay(void); //Some delay

void main(){ //Our main function while(1){ //Infinite loop rotate_f(); //Run forward delay(); //Some delay breaks(); //Stop delay(); //Some delay rotate_b(); //Run Backwards delay(); //Some delay breaks(); //Stop delay(); //Some delay

Page 30: Microcontrollers and their application

} //Do this infinitely}

void rotate_f(){ L293D_A = 1; //Make positive of motor 1 L293D_B = 0; //Make negative of motor 0 L293D_E = 1; //Enable L293D}

void rotate_b(){ L293D_A = 0; //Make positive of motor 0 L293D_B = 1; //Make negative of motor 1 L293D_E = 1; //Enable L293D}

void breaks(){ L293D_A = 0; //Make positive of motor 0 L293D_B = 0; //Make negative of motor 0 L293D_E = 0; //Disable L293D}

void delay(){ //Some delay... unsigned char i,j,k; for(i=0;i<0x20;i++) for(j=0;j<255;j++) for(k=0;k<255;k++);

A simple schematic for interfacing a DC motor using L293D is shown below.

Page 31: Microcontrollers and their application

Interfacing LCD:-

The following table lists all pins of LCD module (JHD162A) along with their description.

Page 32: Microcontrollers and their application

Pin No Name Description1 Vss Ground2 Vdd +5V3 Vee Contrast Adjustment -2V to -5V4 RS Register Select5 RW 1 -Read , 0- Write6 E Enable Strobe7 D0 Data Line8 D1 Data Line9 D2 Data Line10 D3 Data Line11 D4 Data Line12 D5 Data Line13 D6 Data Line14 D7 Data Line15 LED+ Backlit LED +V Vdd (Optional signal)16 LED- Backlit LED –V Vss (Optional signal)LCD Pin Description (JHD162A)

1.1 Connecting Supplies:

Vss (Pin 1) is connected to board ground.

Vdd (Pin 2) is connected to + 5V supply.

Vee (Pin 3) is connected using a variable resistance for adjusting contrast.

LED- (Pin 16) is connected to GND

LED+ (Pin 15) is connected to Vdd

Page 33: Microcontrollers and their application

Connecting control and data signals:

Control signal RS, RW and E are connected to IO Port pins. For data lines we can have two configurations 8 bit mode and 4 bit mode. In 8 bit mode all lines D0-D7 are connected to IO port pins of microcontroller. In 4 bit mode only D4-D7 are connected to IO port pins. The example code available in source section(at bottom of this article) uses the 4 bit mode as default, however 8 bit mode is also supported.

Detailed function description:

InitializeLCDPrototype void InitializeLCD();Input parameters NoneDescription Initializes LCD hardware. Configures data interface(4bit or 8 bit). Clears the display and places cursor at home with blinking mode

ClearScreenPrototype void ClearScreen();Input parameters NoneDescription Clear screen and moves cursor to home. This function takes approx 1.6 ms to complete.

MoveCursorToHomePrototype void MoveCursorToHome();Input parameters NoneDescription Moves the cursor to home position

Page 34: Microcontrollers and their application

SetCursorPosPrototype void SetCursorPos(unsigned char row, unsigned char col);Input parameters row: row number (first row = 0 and so on)col: Column number (first column = 0 and so on)Description Sets the cursor position to specified row and column position

SetCursorStatePrototype void SetCursorState(unsigned char isBlinking, unsigned char isOn);Input parameters isBlinking: 0 – no blinking, 1- blinkingisOn: 0 – cursor OFF, 1- cursor ONDescription Changes cursor state (Blinking and On/Off)

SetCursorBlinkPrototype void SetCursorBlink();Input parameters NoneDescription Sets cursor blinking

SetCursorNoBlinkPrototype void SetCursorNoBlink();Input parameters NoneDescription Disables cursor blinking

SetCursorOnPrototype void SetCursorOn();Input parameters NoneDescription Enables cursor

SetCursorOffPrototype void SetCursorOff();Input parameters NoneDescription Disables cursor

WriteCharAtPosPrototype void WriteCharAtPos(unsigned char row, unsigned char col, char ch);Input parameters row: row position, First row =0 and so oncol: column position, First column = 0 and so onch: character to be writtenDescription Writes a single character ch at specified row and column position

Page 35: Microcontrollers and their application

WriteStringAtPosPrototype void WriteStringAtPos(unsigned char row, unsigned char col, char *str);Input parameters row: row position, First row =0 and so oncol: column position, First column = 0 and so onstr: string to be writtenDescription Writes character string at specified row and column position

InterruptsAs the name implies, an interrupt is some event which interrupts normal program execution.

Program flow is always sequential, being altered only by those instructions which expressly cause program flow to deviate in some way. However, interrupts give us a mechanism to "put on hold" the normal program flow, execute a subroutine, and then resume normal program flow as if we had never left it. This subroutine, called an interrupt handler, is only executed when a certain event (interrupt) occurs. The event may be one of the timers "overflowing," receiving a character via the serial port, transmitting a character via the serial port, or one of two "external events." The 8051 may be configured so that when any of these events occur the main program is temporarily suspended and control passed to a special section of code which presumably would execute some function related to the event that occured. Once complete, control would be returned to the original program. The main program never even knows it was interrupted.

The ability to interrupt normal program execution when certain events occur makes it much easier and much more efficient to handle certain conditions. If it were not for interrupts we would have to manually check in our main program whether the timers had overflown, whether we had received another character via the serial port, or if some external event had occured. Besides making the main program ugly and hard to read, such a situation would make our program inefficient since wed be burning precious "instruction cycles" checking for events that usually dont happen.

For example, lets say we have a large 16k program executing many subroutines performing many tasks. Lets also suppose that we want our program to automatically toggle the P3.0 port every time timer 0 overflows. The code to do this isnt too difficult:

JNB TF0,SKIP_TOGGLECPL P3.0CLR TF0SKIP_TOGGLE: ...

Since the TF0 flag is set whenever timer 0 overflows, the above code will toggle P3.0 every time timer 0 overflows. This accomplishes what we want, but is inefficient. The JNB instruction consumes 2 instruction cycles to determine that the flag is not set and jump over the

Page 36: Microcontrollers and their application

unnecessary code. In the event that timer 0 overflows, the CPL and CLR instruction require 2 instruction cycles to execute. To make the math easy, lets say the rest of the code in the program requires 98 instruction cycles. Thus, in total, our code consumes 100 instruction cycles (98 instruction cycles plus the 2 that are executed every iteration to determine whether or not timer 0 has overflowed). If were in 16-bit timer mode, timer 0 will overflow every 65,536 machine cycles. In that time we would have performed 655 JNB tests for a total of 1310 instruction cycles, plus another 2 instruction cycles to perform the code. So to achieve our goal weve spent 1312 instruction cycles. So 2.002% of our time is being spent just checking when to toggle P3.0. And our code is ugly because we have to make that check every iteration of our main program loop.

Luckily, this isnt necessary. Interrupts let us forget about checking for the condition. The microcontroller itself will check for the condition automatically and when the condition is met will jump to a subroutine (called an interrupt handler), execute the code, then return. In this case, our subroutine would be nothing more than:

CPL P3.0RETI

First, youll notice the CLR TF0 command has disappeared. Thats because when the 8051 executes our "timer 0 interrupt routine," it automatically clears the TF0 flag. Youll also notice that instead of a normal RET instruction we have a RETI instruction. The RETI instruction does the same thing as a RET instruction, but tells the 8051 that an interrupt routine has finished. You must always end your interrupt handlers with RETI.

Thus, every 65536 instruction cycles we execute the CPL instruction and the RETI instruction. Those two instructions together require 3 instruction cycles, and weve accomplished the same goal as the first example that required 1312 instruction cycles. As far as the toggling of P3.0 goes, our code is 437 times more efficient! Not to mention its much easier to read and understand because we dont have to remember to always check for the timer 0 flag in our main program. We just setup the interrupt and forget about it, secure in the knowledge that the 8051 will execute our code whenever its necessary.

The same idea applies to receiving data via the serial port. One way to do it is to continuously check the status of the RI flag in an endless loop. Or we could check the RI flag as part of a larger program loop. However, in the latter case we run the risk of missing characters--what happens if a character is received right after we do the check, the rest of our program executes, and before we even check RI a second character has come in. We will lose the first character. With interrupts, the 8051 will put the main program "on hold" and call our special routine to handle the reception of a character. Thus, we neither have to put an ugly check in our main code nor will we lose characters.

What Events Can Trigger Interrupts, and where do they go?

We can configure the 8051 so that any of the following events will cause an interrupt:

Page 37: Microcontrollers and their application

Timer 0 Overflow. Timer 1 Overflow. Reception/Transmission of Serial Character. External Event 0. External Event 1.

In other words, we can configure the 8051 so that when Timer 0 Overflows or when a character is sent/received, the appropriate interrupt handler routines are called.

Obviously we need to be able to distinguish between various interrupts and executing different code depending on what interrupt was triggered. This is accomplished by jumping to a fixed address when a given interrupt occurs.

Interrupt Flag Interrupt Handler AddressExternal 0 IE0 0003hTimer 0 TF0 000BhExternal 1 IE1 0013hTimer 1 TF1 001BhSerial RI/TI 0023h

By consulting the above chart we see that whenever Timer 0 overflows (i.e., the TF0 bit is set), the main program will be temporarily suspended and control will jump to 000BH. It is assumed that we have code at address 000BH that handles the situation of Timer 0 overflowing.

Setting Up Interrupts

By default at powerup, all interrupts are disabled. This means that even if, for example, the TF0 bit is set, the 8051 will not execute the interrupt. Your program must specifically tell the 8051 that it wishes to enable interrupts and specifically which interrupts it wishes to enable.

Your program may enable and disable interrupts by modifying the IE SFR (A8h):

Bit Name Bit Address Explanation of Function7 EA AFh Global Interrupt Enable/Disable6 - AEh Undefined5 - ADh Undefined4 ES ACh Enable Serial Interrupt3 ET1 ABh Enable Timer 1 Interrupt2 EX1 AAh Enable External 1 Interrupt1 ET0 A9h Enable Timer 0 Interrupt0 EX0 A8h Enable External 0 Interrupt

Page 38: Microcontrollers and their application

As you can see, each of the 8051s interrupts has its own bit in the IE SFR. You enable a given interrupt by setting the corresponding bit. For example, if you wish to enable Timer 1 Interrupt, you would execute either:

MOV IE,#08hor

SETB ET1Both of the above instructions set bit 3 of IE, thus enabling Timer 1 Interrupt. Once Timer 1 Interrupt is enabled, whenever the TF1 bit is set, the 8051 will automatically put "on hold" the main program and execute the Timer 1 Interrupt Handler at address 001Bh.

However, before Timer 1 Interrupt (or any other interrupt) is truly enabled, you must also set bit 7 of IE. Bit 7, the Global Interupt Enable/Disable, enables or disables all interrupts simultaneously. That is to say, if bit 7 is cleared then no interrupts will occur, even if all the other bits of IE are set. Setting bit 7 will enable all the interrupts that have been selected by setting other bits in IE. This is useful in program execution if you have time-critical code that needs to execute. In this case, you may need the code to execute from start to finish without any interrupt getting in the way. To accomplish this you can simply clear bit 7 of IE (CLR EA) and then set it after your time-critical code is done.

So, to sum up what has been stated in this section, to enable the Timer 1 Interrupt the most common approach is to execute the following two instructions:

SETB ET1SETB EA

Thereafter, the Timer 1 Interrupt Handler at 01Bh will automatically be called whenever the TF1 bit is set (upon Timer 1 overflow).

Polling Sequence

The 8051 automatically evaluates whether an interrupt should occur after every instruction. When checking for interrupt conditions, it checks them in the following order:

External 0 Interrupt Timer 0 Interrupt External 1 Interrupt Timer 1 Interrupt Serial Interrupt

This means that if a Serial Interrupt occurs at the exact same instant that an External 0 Interrupt occurs, the External 0 Interrupt will be executed first and the Serial Interrupt will be executed once the External 0 Interrupt has completed.What Happens When an Interrupt Occurs?

Page 39: Microcontrollers and their application

When an interrupt is triggered, the following actions are taken automatically by the microcontroller:

The current Program Counter is saved on the stack, low-byte first. Interrupts of the same and lower priority are blocked. In the case of Timer and External interrupts, the corresponding interrupt flag is cleared. Program execution transfers to the corresponding interrupt handler vector address. The Interrupt Handler Routine executes.

Take special note of the third step: If the interrupt being handled is a Timer or External interrupt, the microcontroller automatically clears the interrupt flag before passing control to interrupt handler routine.

 An interrupt must leave the processor in the same state as it was in when the interrupt initiated.

AT89S51

Pin diagram of AT89S51

The AT89S51 is a low-power, high-performance CMOS 8-bit microcontroller with 4K bytes of In-System Programmable Flash memory. The device is manufactured using Atmel’s high-density nonvolatile memory technology and is compatible with the indus-try-standard 80C51 instruction set and pinout. The on-chip Flash allows the program memory to be reprogrammed in-system or by a conventional nonvolatile memory pro-grammer. By combining a versatile 8-bit CPU with In-System Programmable Flash on a monolithic chip, the Atmel AT89S51 is a powerful microcontroller which provides a highly-flexible and cost-effective solution to many embedded control applications.

The AT89S51 provides the following standard features: 4K bytes of Flash, 128 bytes of RAM, 32 I/O lines, Watchdog timer, two data pointers, two 16-bit timer/counters, a five-vector two-

Page 40: Microcontrollers and their application

level interrupt architecture, a full duplex serial port, on-chip oscillator, and clock circuitry. In addition, the AT89S51 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 con-tents but freezes the oscillator, disabling all other chip functions until the next external interrupt or hardware reset.

Pin Description

1 VCC Supply voltage.

2 GND Ground.

3 Port 0 Port 0 is an 8-bit open drain bi-directional I/O port. As an output port, each pin can sink eight TTL inputs. When 1s are written to port 0 pins, the pins can be used as high-impedance inputs. Port 0 can also be configured to be the multiplexed low-order address/data bus during accesses to external program and data memory. In this mode, P0 has internal pull-ups. Port 0 also receives the code bytes during Flash programming and outputs the code bytes dur-ing program verification. External pull-ups are required during program verification.

4 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 inter-nal 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.

5 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 inter-nal 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 dur-ing accesses to external data memory that use 16-bit addresses (MOVX @ DPTR). In this application, Port 2 uses strong internal pull-ups when emitting 1s. During accesses to external data memory that use 8-bit addresses (MOVX @ RI), Port 2 emits the contents of the P2 Special Function Register. Port 2 also receives the high-order address bits and some control signals during Flash program-ming and verification.

6 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

Page 41: Microcontrollers and their application

inter- Port Pin Alternate Functions P1.5 MOSI (used for In-System Programming) P1.6 MISO (used for In-System Programming) P1.7 SCK (used for In-System Programming)5 2487D–MICRO–6/08 AT89S51 nal 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 receives some control signals for Flash programming and verification. Port 3 also serves the functions of various special features of the AT89S51, as shown in the fol-lowing table.

7 RST Reset input. A high on this pin for two machine cycles while the oscillator is running resets the device. This pin drives High for 98 oscillator periods after the Watchdog times out. The DIS-RTO bit in SFR AUXR (address 8EH) can be used to disable this feature. In the default state of bit DISRTO, the RESET HIGH out feature is enabled.

8 ALE/PROG Address Latch Enable (ALE) is an 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 dur-ing 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.

9 PSEN Program Store Enable (PSEN) is the read strobe to external program memory. When the AT89S51 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 exter-nal data memory.

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

11 XTAL1 Input to the inverting oscillator amplifier and input to the internal clock operating circuit.

12 XTAL2 Output from the inverting oscillator amplifier

Page 42: Microcontrollers and their application

Port Pin Alternate Functions P3.0 RXD (serial input port) P3.1 TXD (serial output port) P3.2 INT0 (external interrupt 0) P3.3 INT1 (external interrupt 1) P3.4 T0 (timer 0 external input) P3.5 T1 (timer 1 external input) P3.6 WR (external data memory write strobe) P3.7 RD (external data memory read strobe).

Serial CommunicationOne of the 8051s many powerful features is its integrated UART, otherwise known as a serial port. The fact that the 8051 has an integrated serial port means that you may very easily read and write values to the serial port. If it were not for the integrated serial port, writing a byte to a serial line would be a rather tedious process requring turning on and off one of the I/O lines in rapid succession to properly "clock out" each individual bit, including start bits, stop bits, and parity bits.

However, we do not have to do this. Instead, we simply need to configure the serial ports operation mode and baud rate. Once configured, all we have to do is write to an SFR to write a value to the serial port or read the same SFR to read a value from the serial port. The 8051 will automatically let us know when it has finished sending the character we wrote and will also let us know whenever it has received a byte so that we can process it. We do not have to worry about transmission at the bit level--which saves us quite a bit of coding and processing time.

Setting the Serial Port Mode

The first thing we must do when using the 8051s integrated serial port is, obviously, configure it. This lets us tell the 8051 how many data bits we want, the baud rate we will be using, and how the baud rate will be determined.

First, lets present the "Serial Control" (SCON) SFR and define what each bit of the SFR represents:

Bit Name Bit Addres Explanation of Function7 SM0 9Fh Serial port mode bit 06 SM1 9Eh Serial port mode bit 1.5 SM2 9Dh Mutliprocessor Communications Enable (explained later)

4 REN 9Ch Receiver Enable. This bit must be set in order to receive characters.

3 TB8 9Bh Transmit bit 8. The 9th bit to transmit in mode 2 and 3.2 RB8 9Ah Receive bit 8. The 9th bit received in mode 2 and 3.1 TI 99h Transmit Flag. Set when a byte has been completely transmitted.0 RI 98h Receive Flag. Set when a byte has been completely received.

Page 43: Microcontrollers and their application

Additionally, it is necessary to define the function of SM0 and SM1 by an additional table:

SM0 SM1 Serial Mode Explanation Baud Rate0 0 0 8-bit Shift Register Oscillator / 120 1 1 8-bit UART Set by Timer 1 (*)1 0 2 9-bit UART Oscillator / 64 (*)1 1 3 9-bit UART Set by Timer 1 (*)

(*) Note: The baud rate indicated in this table is doubled if PCON.7 (SMOD) is set.

The SCON SFR allows us to configure the Serial Port. Thus, well go through each bit and review its function.

The first four bits (bits 4 through 7) are configuration bits.

Bits SM0 and SM1 let us set the serial mode to a value between 0 and 3, inclusive. The four modes are defined in the chart immediately above. As you can see, selecting the Serial Mode selects the mode of operation (8-bit/9-bit, UART or Shift Register) and also determines how the baud rate will be calculated. In modes 0 and 2 the baud rate is fixed based on the oscillators frequency. In modes 1 and 3 the baud rate is variable based on how often Timer 1 overflows. Well talk more about the various Serial Modes in a moment.

The next bit, SM2, is a flag for "Multiprocessor communication." Generally, whenever a byte has been received the 8051 will set the "RI" (Receive Interrupt) flag. This lets the program know that a byte has been received and that it needs to be processed. However, when SM2 is set the "RI" flag will only be triggered if the 9th bit received was a "1". That is to say, if SM2 is set and a byte is received whose 9th bit is clear, the RI flag will never be set. This can be useful in certain advanced serial applications. For now it is safe to say that you will almost always want to clear this bit so that the flag is set upon reception of any character.

The next bit, REN, is "Receiver Enable." This bit is very straightforward: If you want to receive data via the serial port, set this bit. You will almost always want to set this bit.

The last four bits (bits 0 through 3) are operational bits. They are used when actually sending and receiving data--they are not used to configure the serial port.

The TB8 bit is used in modes 2 and 3. In modes 2 and 3, a total of nine data bits are transmitted. The first 8 data bits are the 8 bits of the main value, and the ninth bit is taken from TB8. If TB8 is set and a value is written to the serial port, the datas bits will be written to the serial line followed by a "set" ninth bit. If TB8 is clear the ninth bit will be "clear."

The RB8 also operates in modes 2 and 3 and functions essentially the same way as TB8, but on the reception side. When a byte is received in modes 2 or 3, a total of nine bits are received. In

Page 44: Microcontrollers and their application

this case, the first eight bits received are the data of the serial byte received and the value of the ninth bit received will be placed in RB8.

TI means "Transmit Interrupt." When a program writes a value to the serial port, a certain amount of time will pass before the individual bits of the byte are "clocked out" the serial port. If the program were to write another byte to the serial port before the first byte was completely output, the data being sent would be garbled. Thus, the 8051 lets the program know that it has "clocked out" the last byte by setting the TI bit. When the TI bit is set, the program may assume that the serial port is "free" and ready to send the next byte.

Finally, the RI bit means "Receive Interrupt." It funcions similarly to the "TI" bit, but it indicates that a byte has been received. That is to say, whenever the 8051 has received a complete byte it will trigger the RI bit to let the program know that it needs to read the value quickly, before another byte is read.

Setting the Serial Port Baud Rate

Once the Serial Port Mode has been configured, as explained above, the program must configure the serial ports baud rate. This only applies to Serial Port modes 1 and 3. The Baud Rate is determined based on the oscillators frequency when in mode 0 and 2. In mode 0, the baud rate is always the oscillator frequency divided by 12. This means if youre crystal is 11.059Mhz, mode 0 baud rate will always be 921,583 baud. In mode 2 the baud rate is always the oscillator frequency divided by 64, so a 11.059Mhz crystal speed will yield a baud rate of 172,797.

In modes 1 and 3, the baud rate is determined by how frequently timer 1 overflows. The more frequently timer 1 overflows, the higher the baud rate. There are many ways one can cause timer 1 to overflow at a rate that determines a baud rate, but the most common method is to put timer 1 in 8-bit auto-reload mode (timer mode 2) and set a reload value (TH1) that causes Timer 1 to overflow at a frequency appropriate to generate a baud rate.

To determine the value that must be placed in TH1 to generate a given baud rate, we may use the following equation (assuming PCON.7 is clear).

TH1 = 256 - ((Crystal / 384) / Baud)If PCON.7 is set then the baud rate is effectively doubled, thus the equation becomes:

TH1 = 256 - ((Crystal / 192) / Baud)For example, if we have an 11.059Mhz crystal and we want to configure the serial port to 19,200 baud we try plugging it in the first equation:

TH1 = 256 - ((Crystal / 384) / Baud)TH1 = 256 - ((11059000 / 384) / 19200 )TH1 = 256 - ((28,799) / 19200)TH1 = 256 - 1.5 = 254.5

Page 45: Microcontrollers and their application

As you can see, to obtain 19,200 baud on a 11.059Mhz crystal wed have to set TH1 to 254.5. If we set it to 254 we will have achieved 14,400 baud and if we set it to 255 we will have achieved 28,800 baud. Thus were stuck...

But not quite... to achieve 19,200 baud we simply need to set PCON.7 (SMOD). When we do this we double the baud rate and utilize the second equation mentioned above. Thus we have:

TH1 = 256 - ((Crystal / 192) / Baud)TH1 = 256 - ((11059000 / 192) / 19200)TH1 = 256 - ((57699) / 19200)TH1 = 256 - 3 = 253

Here we are able to calculate a nice, even TH1 value. Therefore, to obtain 19,200 baud with an 11.059MHz crystal we must:

1. Configure Serial Port mode 1 or 3.2. Configure Timer 1 to timer mode 2 (8-bit auto-reload).3. Set TH1 to 253 to reflect the correct frequency for 19,200 baud.4. Set PCON.7 (SMOD) to double the baud rate.

Writing to the Serial Port

Once the Serial Port has been propertly configured as explained above, the serial port is ready to be used to send data and receive data. If you thought that configuring the serial port was simple, using the serial port will be a breeze.

To write a byte to the serial port one must simply write the value to the SBUF (99h) SFR. For example, if you wanted to send the letter "A" to the serial port, it could be accomplished as easily as:

MOV SBUF,#AUpon execution of the above instruction the 8051 will begin transmitting the character via the serial port. Obviously transmission is not instantaneous--it takes a measureable amount of time to transmit. And since the 8051 does not have a serial output buffer we need to be sure that a character is completely transmitted before we try to transmit the next character.

The 8051 lets us know when it is done transmitting a character by setting the TI bit in SCON. When this bit is set we know that the last character has been transmitted and that we may send the next character, if any. Consider the following code segment:

CLR TI ;Be sure the bit is initially clearMOV SBUF,#A ;Send the letter A to the serial portJNB TI,$ ;Pause until the TI bit is set.

The above three instructions will successfully transmit a character and wait for the TI bit to be set before continuing. The last instruction says "Jump if the TI bit is not set to $"--$, in most assemblers, means "the same address of the current instruction." Thus the 8051 will pause on

Page 46: Microcontrollers and their application

the JNB instruction until the TI bit is set by the 8051 upon successful transmission of the character.

Reading the Serial Port

Reading data received by the serial port is equally easy. To read a byte from the serial port one just needs to read the value stored in the SBUF (99h) SFR after the 8051 has automatically set the RI flag in SCON.

For example, if your program wants to wait for a character to be received and subsequently read it into the Accumulator, the following code segment may be used:

JNB RI,$ ;Wait for the 8051 to set the RI flagMOV A,SBUF ;Read the character from the serial port

The first line of the above code segment waits for the 8051 to set the RI flag; again, the 8051 sets the RI flag automatically when it receives a character via the serial port. So as long as the bit is not set the program repeats the "JNB" instruction continuously.

Once the RI bit is set upon character reception the above condition automatically fails and program flow falls through to the "MOV" instruction which reads the value.

PC Controlled Robot

Introduction

The advent of new high-speed technology and the growing computer capacity provided realistic opportunity for new robot controls and realization of new methods of control theory. This technical improvement together with the need for high performance robots created faster, more accurate and more intelligent robots using new robots control devices, new drives and advanced control algorithms.This project describes a new economical solution of robot control systems. The presented robot control system can be used for different sophisticated robot applications. The control system consists of a PC, a microcontroller that collects data from the PC and control the robot.The intelligent control software, which has been developed using high-level graphical programming language (visual basic). A complete solution of a robot control solution is presented in this project. The robot was fully controlled by the PC and the commands from the PC were received by the microcontroller.The robot can be used in military applications.

MAX232 IC

Page 47: Microcontrollers and their application

max232 is primary used for people building electronics with an rs232 interface. Serial RS-232 (V.24) communication works with voltages (between -15V ... -3V are used to transmit a binary '1' and +3V ... +15V to transmit a binary '0') which are not compatible with today's computer logic voltages. On the other hand, classic TTL computer logic operates between 0V ... +5V (roughly 0V ... +0.8V referred to as low for binary '0', +2V ... +5V for high binary '1' ). Modern low-power logic operates in the range of 0V ... +3.3V or even lower.

So, the maximum RS-232 signal levels are far too high for today's computer logic electronics, and the negative RS-232 voltage can't be grokked at all by the computer logic. Therefore, to receive serial data from an RS-232 interface the voltage has to be reduced, and the 0 and 1 voltage levels inverted. In the other direction (sending data from some logic over RS-232) the low logic voltage has to be "bumped up", and a negative voltage has to be generated, too.

RS-232 TTL Logic----------------------------------------------- -15V ... -3V <-> +2V ... +5V <-> 1 +3V ... +15V <-> 0V ... +0.8 <-> 0

MAX232 Driver/ReceiverThe MAX232 from Maxim was the first IC which in one package contains the necessary drivers (two) and receivers (also two), to adapt the RS-232 signal voltage levels to TTL logic. It became popular, because it just needs one voltage (+5V) and generates the necessary RS-232 voltage levels (approx. -10V and +10V) internally. This greatly simplified the design of circuitry. Circuitry designers no longer need to design and build a power supply with three voltages (e.g. -12V, +5V, and +12V), but could just provide one +5V power supply, e.g. with the help of a simple 78x05 voltage regulator.The MAX232 has a successor, the MAX232A. The ICs are almost identical, however, the MAX232A is much more often used (and easier to get) than the original MAX232, and the MAX232A only needs external capacitors 1/10th thecapacity of what the original MAX232 needs.

MAX232(A) is just a driver/receiver. It does not generate the necessary RS-232 sequence of marks and spaces with the right timing, it does not decode the RS-232 signal, it does not provide a serial/parallel conversion. All it does is to convert signal voltage levels. Generating serial data with the right timing and decoding serial data has to be done by additional circuitry, e.g. by a 16550 UART or one of these small micro controllers.

Page 48: Microcontrollers and their application

MAX232(A) DIP Package

MAX232(A) DIP Package Pin Layout

Nbr Name Purpose Signal Voltage Capacitor Value MAX232

Capacitor Value MAX232A

1 C1+ + connector for capacitor C1

capacitor should stand at least 16V

1µF 100nF

2 V+ output of voltage pump

+10V, capacitor should stand at least 16V

1µF to VCC 100nF to VCC

3 C1- - connector for capacitor C1

capacitor should stand at least 16V

1µF 100nF

4 C2+ + connector for capacitor C2

capacitor should stand at least 16V

1µF 100nF

5 C2- - connector for capacitor C2

capacitor should stand at least 16V

1µF 100nF

6 V- output of voltage pump / inverter

-10V, capacitor should stand at least 16V

1µF to GND 100nF to GND

Page 49: Microcontrollers and their application

7 T2out Driver 2 output RS-232

8 R2in Receiver 2 input RS-232

9 R2out Receiver 2 output TTL

10 T2in Driver 2 input TTL

11 T1in Driver 1 input TTL

12 R1out Receiver 1 output TTL

13 R1in Receiver 1 input RS-232

14 T1out Driver 1 output RS-232

15 GND Ground 0V 1µF to VCC 100nF to VCC

16 VCC Power supply +5V see above see above

V+(2) is also connected to VCC via a capacitor (C3). V-(6) is connected to GND via a capacitor (C4). And GND(15) and VCC(16) are also connected by a capacitor (C5), as close as possible to the pins.

A Typical Application

The MAX232(A) has two receivers (converts from RS-232 to TTL voltage levels) and two drivers (converts from TTL logic to RS-232 voltage levels). This means only two of the RS-232 signals can be converted in each direction.

Typically a pair of a driver/receiver of the MAX232 is used for

TX and RX

Maxim's data sheet explains the MAX232 family in great detail, including the pin configuration and how to connect such an IC to external circuitry. This information can be used as-is in own design to get a working RS-232 interface.

MAX232 to RS232 DB9 Connection as a DCE

MAX232 Pin Nbr. MAX232 Pin Name Signal Voltage DB9 Pin

7 T2out RTS RS-232 8

8 R2in CTS RS-232 7

Page 50: Microcontrollers and their application

9 R2out CTS TTL n/a

10 T2in RTS TTL n/a

11 T1in TX TTL n/a

12 R1out RX TTL n/a

13 R1in TX RS-232 3

14 T1out RX RS-232 2

15 GND GND 0 5

In addition one can directly wire DTR (DB9 pin 4) to DSR (DB9 pin 6) without going through any circuitry. This gives automatic (brain dead) DSR acknowledgment of an incoming DTR signal.

Sometimes pin 6 of the MAX232 is hard wired to DCD (DB9 pin 1). This is not recommended. Pin 6 is the raw output of the voltage pump and inverter for the -10V voltage. Drawing currents from the pin leads to a rapid breakdown of the voltage, and as a consequence to a breakdown of the output voltage of the two RS-232 drivers. It is better to use software which doesn't care about DCD, but does hardware-handshaking via CTS/RTS only.

The circuitry is completed by connecting five capacitors to the IC as it follows. The MAX232 needs 1.0µF capacitors, the MAX232A needs 0.1µF capacitors. MAX232 clones show similar differences. It is recommended to consult the corresponding data sheet. At least 16V capacitor types should be used. The first pin is always where the plus pole of the capacitor should be connected to.

Data Cables

With the rise of mobile phones so called data cables for these phones have also become popular. These are cables to connect the mobile phone to a serial interface of a computer. The interesting thing is that modern mobile phones work with 3.3V logic, and older phones with 5V logic on their data buses. So these data cables must and do convert the phone logic voltage levels to and from RS232 voltage levels.

No-name data cables have become rather cheap (as opposite to original phone-brand data cables). The cheap cables with their voltage converters can be used as an alternative to home-made MAX232-based circuitry. The advantage is that the cables occupy much less space (the converter is usually inside the RS232 plug). Such a cable also saves the effort to solder a circuitry board. Another advantage, which can also be a disadvantage of such a data cable is that they usually take their power from the RS232 connector. This saves an external power supply, but can also cause problems, because the RS232 interface is not designed to power

Page 51: Microcontrollers and their application

some logic and the DTE might not provide enough power. Another disadvantage is that many of these cables just support RX and TX (one receiver, one driver), and not two drivers/receivers as the MAX232. So there is no hardware handshake possible. Finally, when using such a cable it should be made sure that they convert to the desired voltage (3.3V or 5V).

USB <-> RS-232 Converter

USB to Serial interface cables often have two components: a USB transciever that outputs serial data; and a voltage shifter to produce standards-compliant RS-232 voltages. It is often possible to throw away (ignore, desolder, cut-out) the USB part of these cables, connect an external 5V power source (or abuse the RS-232 interface) to replace the power coming from the USB bus and to just use the RS-232 level-shifter. All this is probably as much work as using a MAX232A, although you get one RS-232 connector for free.

On considering a USB cable, it is also worthwhile to consider using USB directly, instead of RS-232. Many USB transceiver chips can be integrated directly into circuits, eliminating the need for voltage-shifting components. Parts such as the FTDI FT232BM even have an input allowing designers to select 5V or 3.3V output levels. Most of these USB transceiver chips are available as surface-mount components only. But some vendors offer DIP-sized preassembled modules, often at competitive prices, and often with free or cheap drivers or driver development environments.

The required parts:

1 x female serial port connector 1 x max 232 4 x 1uF capacitor 1 x 10uF capacitor Soldering iron, wires, breadboard etc.

Program for working of a PC controlled robot:-

Page 52: Microcontrollers and their application

#include<reg51.h>

#include<ctype.h>

#define motor P1

void ser_init();

unsigned char choice;

void ser_tx(unsigned char);

unsigned char ser_rx();

void ser_str(unsigned char *a);

void main()

{ l1:

ser_init();

ser_str("HI");

motor=0x00;

while(1)

{ choice=ser_rx();

if(islower(choice))

choice=toupper(choice);

if(choice=='F')

{ motor=0x06;}

else if(choice=='S')

{ motor=0x00;}

else if(choice=='B')

{ motor=0x09;}

Page 53: Microcontrollers and their application

else if(choice=='L')

{ motor=0x04; }

else if(choice=='R')

{ motor=0x01; }

else

{ ser_str("Wrong Entry!!Please Enter between(R,L,S,B,F)");

break; }

}

goto l1; }

void ser_init()

{ SCON=0x50;

TMOD=0x20;

TH1=0xFD;

TR1=1; }

void ser_tx(unsigned char ch)

{ SBUF=ch;

while(TI==0);

TI=0; }

unsigned char ser_rx()

{ unsigned char ch;

while(RI==0);

ch=SBUF;

RI=0;

Page 54: Microcontrollers and their application

return ch; }

void ser_str(unsigned char * a)

{ unsigned int i=0;

while(a[i]!='\0')

{ ser_tx(a[i]);

i++; }}