Você está na página 1de 54

Basic Circuit for 8051

8051 PIN
Power Reset Crystal External EA, I/O Port P3 is external interrupts INT0, INT1 Counter control T0, T1 P0 and P2 are multiplexed with Address and Data bus

OUT
Vcc, Vss RST XTAL[1,2] device interfacing ALE, PSEN, WR, RD

P0[7;0], P1[7:0], P2[7:0], P3 shared with control lines Serial I/O RxD, TxD,

BASIC CIRCUIT -THAT MAKES 8051 WORKS.

EA/VP Pin

The EA on

pin 31 is tied high to make the 8051 executes program from Internal ROM

Reset
RESET is state. The 8051 is low. Power-On - Initially - When Manual -closing

Circuit
an active High input When RESET is set to High, 8051 goes back to the power on reset by holding the RST high for at least two machine cycles and then returning it

Reset charging of capacitor makes RST High capacitor charges fully it blocks DC. reset the switch momentarily will make RST High.

After a reset, the program counter is loaded with 0000H but the content of on-chip RAM is not affected.

Register Program counter Accumulator B register PSW SP DPTR All ports

Content 0000h 00h 00h 00h 07h 0000h FFh

Register IP IEv All timer registers SCON SBUF PCON (HMOS) PCON (CMOS)v

Content XXX00000b 0XX00000b 00h 00h 00h 0XXXXXXXbv 0XXX0000b Note: content of on-chip RAM is not affected by Reset.

Oscillator
The 8051 Effectively, machine instruction

Circuit
uses the crystal for precisely that: to synchronize its operation. the 8051 operates using what are called "machine cycles." A single cycle is the minimum amount of time in which a single 8051 can be executed. although many instructions take multiple cycles.

8051 has operating frequency of the 8051. This can be achieved in two ways,,

an on-chip oscillator. It needs an external crystal thats decides the

The crystal is connected to pins 18 and 19 with stabilizing capacitors. 12 MHz (11.059MHz) crystal is often used and the capacitance ranges from 20pF to 40pF. The oscillator can also be a TTL clock source connected with a NOT gate as shown

How fast 8051 works ? A cycle is, in reality, 12 pulses of the crystal. That is to say, if an instruction takes one machine cycle to execute, it will take 12 pulses of the crystal to execute. Since we know the crystal is pulsing 11,059,000 times per second and that one machine cycle is 12 pulses, we can calculate how many instruction cycles the 8051 can execute per second: 11,059,000 / 12 = 921,583 Why is such an oddball crystal frequency? 11.0592 MHz crystals are often used because it can be divided to give you exact clock rates for most of the common baud rates for the UART, especially for

the higher these

speeds (9600, 19200). Despite the "oddball" value, crystals are readily available and commonly used.

Power

Supply

C1-1000 The 78L05 is a 5V regulator. The input voltage ranges from 7V to 35V and the output voltage is about 5V.

mf ,C2-100 mf

Using Ports for I/O Operation


8051 is TTL logic device. TTL logic has two levels: Logic "High" (1) and logic "Low" (0). The voltage and current involved for the two levels are as follows:

Level High

Voltage Above 2.4V

Current Virtually no current flow 1.6mA Sinking current from TTL input to ground (Depends on logic family)

Low

Below 0.9V

Port functions Ports Port 0 (Pin 32-39) Port 1 (Pin 1-8) Dedicated I/O port Used solely for interfacing to external devices Internal pull-ups Function Dual-purpose port- 1. general purpose I/O Port. 2. multiplexed address & data bus Open drain outputs

Port 2 (Pin 21-28) Dual-purpose port- 1. general purpose I/O port. 2. a multiplexed address & data bus. Internal pull-ups Dual-purpose port- 1. general purpose I/O port. 2. pins have alternate purpose related to special features of the 8051 Internal pull-ups

Port 3 (Pin 10-17)

The 8051 internal ports are partly bi-directional (Quasi-bi-directional). The following is the internal circuitry for the 8051 port pins:

1.Configuring for output P0 is open drain. Has to be pulled high by external 10K resistors. Not needed if P0 is used for address lines Writing to a port pin loads data into a port latch that drives a FET connected to the port pin. P0: Note that the pull-up is absent on Port 0 except when functioning as the external address/data bus. When a "0" is written to a bit in port 0, the pin is pulled low. But when a "1" is written to it, it is in high impedance (disconnected) state. So when using port 0 for output, an external pull-up resistor is needed, depending on the input characteristics of the device driven by the port pin P1, P2, P3 have internal pull-ups: When a "0" is written to a bit in these port , the pin is pulled low ( FET-ON) ,also when 1 is written to a bit in these port pin becomes high (FET-OFF) thus using port P1,P2,P3 is simple.

2. Configuring for input At power-on all are output ports by default To configure any port for input, write all 1s (0xFF) to the port Latch bit=1, FET=OFF, Read Pin asserted by read instruction You can used a port for output any time. But for input, the FET must be off. Otherwise, you will be reading your own latch rather than the signal coming from the outside. Therefore, a "1" should be written to the pin if you want to use it as input, especially when you have used it for output before. If you don't do this input high voltage will get grounded through FET so you will read pin as low and not as high. An external device cannot easily drive it high so, you should not tide a port high directly without any resistor. Otherwise, the FET would burn. Be Careful : Some port pins serve multiple functions. Be careful writing to such ports. For example, P3.0 is the UART RXD (serial input), and P3.1 is the UART TXD (serial output). If you set P3.0 to a '0', an external buffer (such as an RS232 level translator) cannot drive it high. Therefore you have prevented receiving any serial input. If an external interrupt such as EX1 on P3.3 is enabled, and set to be level sensitive, and you clear this pin's output latch to a zero, guess what? You've just caused a perpetual interrupt 1. The pin's input buffer will read the output of it's latch as always low. Your controller will spend all of its time in the interrupt handler code and will appear to have crashed, since it will have very little time for other tasks. In fact, it will get to execute a single instruction before reentering the interrupt handler, so the rest of your program will execute very, very slowly.

Interfacing to 8051 I/O ports.

SWITCH ON I/O PORTS

Good Circuit
It is the The 10k and always best connecting the switch to ground with a pull-up resistor as shown in "Good" circuit. When the switch is open, the 10k resistor supplies very small current needed for logic 1. When it is closed, the port pin is short to ground. voltage is 0V and all the sinking current requirement is met, so it is logic 0. The resistor will pass 0.5 mA (5 Volt/10k ohm). Thus the circuits waste very little current in either state. The drawback is that the closure of switch gives logic 0 people like to think of a switch closure gives logic 1. But this is not a matter because it is easy to handle in software.

Fair circuit
The "Fair" circuit requires that the pull-down resistor be very small. Otherwise, the pin will rise above 0.9V when the resistor passes the 1.6mA sinking current. When the switch is closed, the circuit waste a large current since virtually no current flows into the pin. The only advantage is that a switch closure gives logic 1.

Poor circuit
In the "Poor" circuit, the logic 1 is stable when the switch is closed. But when the switch is open, the input floats to a noise-sensitive high rather than a low. An open TTL pin is usually read as logic 1 but the pin may picks up noise like an antenna. To conclude, driving a TTL input should always consider current sinking (pulling input to 0V).

LED ON I/O PORTS

Since TTL outputs is designed to feed multiple TTL inputs, they are good at current sinking but poor at current sourcing. The Standard TTL can sink up to 16mA and source 250uA. The LS logic family can sink 8mA and source 100uA. The 8051 port pin can sink 1.6mA (3.2mA for port 0) and source 60uA. Therefore, if you drive significant current, try to arrange your circuits to use current sinking. Unlike diodes, Light-emitting diodes have a forward voltage drop from 1.7 to 2.5 volts and most of them flow a forward current 20mA.

Poor circuit
since the TTL output can't source above 1mA so the LED will be very dim.

Fair circuit
The LED will conduct heavily at about 2V and the extra 3V has to be dropped in the TTL circuitry. This causes high power dissipation in the TTL or the LED fails.

Good circuit
The resistor limits the current. The resistance can be calculated by assuming its voltage is about 2.5V and the TTL output is 0.9V. For 2.2V LED, 1.9V is across the resistor so the 220ohm would limit the current to 8.6mA (1.9/220). For 1.7V LED, 2.4V is across the resistor so it would limit the current to 10.9mA (2.4/220). The resistor should not less than 100ohm or the LED would fail.

CODE EXAMPLE

Connection -Switch -P1.0 , LED - P2.0 Condition - Turn on LED when switch is pressed. ASSEMBLY LANGUAGE SETB P1.0 ; input pin. LOOP: JB P2.0, LOOP ; not grounded then stay in loop CLR P0.0 ;To clear pin P0.0 when P1.0 is at 0 v C LANGUAGE (SPJ )

BIT button p1.0 / * Using BIT keyword for p1.0 definition*/ BIT LED p2.0 void main ( ) { while (1) { LED = button ; /* Note LED=button is wrong */ } }

RELAY ON I/O PORT (2CO Relay)

In A, NPN transistor (say a BC337 or BC338) is being used to control a relay with a 5 V coil. Series base resistor R1 is used to set the base current for Q1, so that the transistor is driven into saturation (fully turned on) when the relay is to be energized. That way, the transistor will have minimal voltage drop, and hence dissipate very little power as well as delivering most of the 5V to the relay coil. How do work out the value of R1?. Let us say RLY1 needs 50mA of coil current to pull in and hold reliably, and has a resistance of 24 Ohms so it draws this current from 5V. Our BC337/338 transistor will need enough base current to make sure it remains saturated at this collector current level. To work this out, we simply make sure that the base current is greater than this collector current divided by the transistors minimum DC current gain hFE. So as the BC337/338 has a minimum hFE of 100 (at 100mA), we'll need to provide it with at least 50mA/100 = 0.5mA of base current. In practice, you give it roughly double this value, say 1mA of base current, just to make sure it does saturate. So if your resistance will be TTL Logic High Voltage (Min) /1ma ( 1K approx)

EXAMPLE

Connection -Port 0 is connected to eight LEDs, each of them is connected to 5V through a 330ohm resistor. Port 1 is connected to a DIP switch and a 10Kohm resistor

Condition - Corresponding led should light up when switch pressed , i.e. if Switch at 1.0 is pressed -> LED at P0.0 should light up.

CODE EXAMPLE
ASSEMBLY LANGUAGE LOOP: mov p1,#0ffh ; To configure port for input. mov a,p1 mov p0 ,a sjmp LOOP ; Stay in infinite loop . 1. void main() { while (1) { P0 = P1; /* Note P1=P0 will not work } } 2. voided main() { char port_value; while (1) { port_value = P1; P0 = port_value; } } C LANGUAGE (SPJ SIDE51)

USING ULN
Another option for driving relays would be to use a high-voltage, high-current, Darlington array driver IC such as the ULN2803. The ULN2803 can directly interface to the data outputs of the 8051 pins, and provides much higher drive-current. The ULN2803 also has internal diode

protection that eliminates the need for the fly-back diode as shown in the above relay driver schematics. You can connect 8 relay using this IC. So I think ULN is better choice if you have more than 3 relay. ( Simple design of circuit & PCB as well ! )

Serial Communication
RS-232 WAVEFORM

TTL/CMOS Serial Logic Waveform The diagram above, shows the expected waveform from the UART when using the common 8N1 format. 8N1 signifies 8 Data bits, No Parity and 1 Stop Bit. The RS-232 line, when idle is in the Mark State (Logic 1). A transmission starts with a start bit which is (Logic 0). Then each bit is sent down the line, one at a time. The LSB (Least Significant Bit) is sent first. A Stop Bit (Logic 1) is then appended to the signal to make up the transmission. The data sent using this method, is said to be framed. That is the data is framed between a Start and Stop Bit . RS-232 Voltage levels 1. +3 to +25 volts to signify a "Space" (Logic 0) 2. -3 to -25 volts for a "Mark" (logic 1). 3. Any voltage in between these regions (i.e. between +3 and -3 Volts) is undefined. The data byte is always transmitted least-significant-bit first. The bits are transmitted at specific time intervals determined by the baud rate of the serial signal.

This is the signal present on the RS-232 Port of your computer, shown below.

RS-232 Logic Waveform

RS-232 LEVEL CONVERTER

Standard serial interfacing of microcontroller (TTL) with PC or any RS232C Standard device , requires TTL to RS232 Level converter . A MAX232 is used for this purpose. It provides 2-channel RS232C port and requires external 10uF capacitors. The driver requires a single supply of +5V .

MAX-232 includes a Charge Pump, which generates +10V and -10V from a single 5v supply.

MICROCONTROLLER INTERFACING WITH RS-232 STANDARD DEVICES



MAX232 (+5V -> +-12V converter) Serial port male 9 pin connector (SER)

SETTING SERIAL PORT.


SCON 8 bit UART ,RN enabled , TI & RI operated by program. - 50hex Timer 1 Count TH1 = 256 - ((Crystal / 384) / Baud) -PCON.7 is clear. TH1 = 256 - ((Crystal / 192) / Baud)-PCON.7 is set.

so with PCON.7 is clear we get timer value = FDhex

CODE EXAMPLE
1. TRANSMITTING 'A' CONTINUOUSLY ON SERIAL PORT. ASSEMBLY LANGUAGE START mov TMOD, #20H ;T1 is mode2 mov TH1, #0fd ;9600 baud mov SCON, #50H ;8b, 1stop, 1start, REN enabled anl PCON, #07fh ;To make SMOD =0 setb TR1 ;start T1 AGAIN mov SBUF, #A ;letter A is transmitted HERE jnb TI, HERE ;poll TI until all the bits are transmitted clr TI ;clear TI for the next character sjmp AGAIN ;while(1) C LANGUAGE #include <Intel\8052.h> #include <standard.h> #include<stdio.h> (SPJ SIDE51)

void main () { TMOD = 0x20; TH1 = 0xfd; PCON &= 0x7f; SCON = 0x50; TCON =0x40; while (1) /*continues loop */ { printf("a"); /* transmit a along with CR & LF. }

2.TO RECEIVE DATA FROM SERIAL PORT AND SENT IT TO PORT 1.

ASSEMBLY LANGUAGE START: mov TMOD, #20H ;T1 in mode 2 mov TH1, #-3 ;9600 baud mov SCON, #50H ;8b, 1start, 1stop anl PCON, #07fh ;To make SMOD =0 setb TR1 ;start T1 AGAIN: clr RI ;ready to receive a byte HERE: jnb RI, HERE ;wait until one byte is Rx-ed mov A, SBUF ;read the received byte from SBUF mov P1, A ;display on P1 sjmp AGAIN ;while (1)

C LANGUAGE #include <Intel\8052.h> #include <standard.h> #include<stdio.h> unsigned char a; void main () { TMOD = 0x20; TH1 = 0xfd; PCON &= 0x7f; SCON = 0x50; TCON =0x40; while (1) /*continues loop */ { a= getchar () ; P1=a; } }

(SPJ SIDE51)

3. SENDING DATA IN STRING TO SERIAL PORT In Assembly Lan. prog. : Data is stored in string at pointer DATA. 0 is appended at end of string. In transmit subroutine data in string is transmitted till 0 is detected. ASSEMBLY LANGUAGE (A51) C LANGUAGE .org 0000h ljmp START DATA: .db "HI,I AM MAHESH",0dh,0ah,0 ;0 at end to detect end of string(0d carrage return ,0a -line feed) #include <Intel\8052.h> #include <standard.h> #include<stdio.h> void main () { (SPJ SIDE51)

;********************TRANSMIT****************** TRANSMIT: clr A ; clear A to get data movc A,@A+DPTR ; get data from string at data pointer jz EXITSTR ; if data zero, eos lcall OUTCHAR ; else send character inc dptr ; increment data pointer sjmp TRANSMIT ; continue, zero condition will terminate EXITSTR: ret OUTCHAR: mov sbuf,a ; place A into Serial Port 1 Buffer WAITCHAR: jnb ti,WAITCHAR ; wait buffer empty flag is set clr ti ; clear buffer empty flag ret START: ;******************INITIALISATION**************** * mov TMOD, #20H ;T1 in mode 2 mov TH1, #-3 ;9600 baud mov SCON, #50H ;8b, 1start, 1stop anl PCON, #07fh ;To make SMOD =0 setb TR1 ;start T1 ;*****************To SEND DATA******************* mov dptr,#DATA lcall TRANSMIT sjmp START

TMOD = 0x20; TH1 = 0xfd; PCON &= 0x7f; SCON = 0x50; TCON =0x40; while (1) /*continues loop */ { printf("HI I AM MAHESH\n"); /* transmit a along with CR & LF*/ } }

EXAMPLE - MOBILE PHONE AND GPS RECEIVER.

You can use same circuit for communicating with Mobile phones/GSM Module or GPS. Communicating with both of these require a Multiplexer ,which can be implemented using NAND gates. GPS serial output Most GPS are capable of sending information through a simple serial link. Only the TXD and GROUND pins need to be connected . The GPS must be set at 9600 bps (or 4800) , 8 bits, No Parity, and 1 stop bit.

NAND gate as 2:1 Mux. which connects Rx of GSM modem or GPS receiver according to select bit logic level (pin P1.0 of uC)

7 Segment Display
INTRODUCTION
For the seven segment display you can use the LT-541 or LSD5061-11 chip. Each of the segments of the display is connected to a pin on the 8051 (the schematic shows how to do this). In order to light up a segment on the the pin must be set to 0V. To turn a segment off the corresponding pin must be set to 5V. This is simply done by setting the pins on the 8051 to '1' or '0'.

LED displays are

Power-hungry (10ma per LED) Pin-hungry (8 pins per 7-seg display)

But they are cheaper than LCD display 7-SEG Display are available in two types -1. Common anode & 2. common cathode , but command anode display are most suitable for

interfacing with 8051 since 8051 port pins can sink current better than sourcing it.

CREATING DIGIT PATTERN


For displaying Digit say 7 we need to light segments -a ,b, c. Since we are using Common anode display , to do so we have to to provide Logic -0 (0 v) at anode of these segments. so need to clear pins- P1.0 ,P1.1,P1.2. that is 1 1 1 1 1 0 0 0 -->F8h .

Connection Segment number a b c d e f g h(dp) 8051 pin number P1.0 P1.1 P1.2 P1.3 P1.4 P1.5 p1.6 P1.7 Digit 0 Seg. h 1 Seg. g 1 Seg. f 0

Hex Code

Seg. e 0

Seg. d 0

Seg. c 0

Seg. b 0

Seg. a 0

HEX C0

1 2 3 4

0 1 1 1

0 0 0 0

0 1 1 0

0 0 1 1

0 0 0 1

1 1 0 0

1 0 0 0

0 0 0 1

06 A4 B0 99

You can also do this for some characters like A ,E .. but not for D or B because it will be same as that of 0 & 8 . So this is one of limitation of 7-seg display. Since we can Enable only one 7-seg display at a time ,we need to scan these display at fast rate .The scanning frequency should be high enough to be flicker-free. At least 30HZ .Therefore time one digit is ON is 1/30 seconds

INTERFACING
Note that I am using Common Anode display. so the common Anode pin is tied to 5v .The cathode pins are connected to port 1 through 330 Ohm resistance (current limiting).

Common Anode display

CODE EXAMPLE
Connection - a:h to port p1.0:p1.7 , D0:D1 to p3.0:p3.1. To Display - Consider example of vending machine where we want to display number of soft drink bottles on display entered by customer. Suppose he enter 3 (03) bottles then we will use lookup table to see DIGIT PATTERN of these keys. So DIGI[1]=c0 (hex code for '0') & DIGI[2]=bo(hex code for '3'). Note: I have taken values for DIGI[1] & DIGI[2] directly in code.

Algorithm start : disable [D0:D1] again : enable D0 [a:h] - pattern for Digit1 delay disable D0. Enable D1 void main( ){ [a:h] - pattern for Digit2

C LANGUAGE #include <Intel\8052.h> #include <standard.h> #include<stdio.h> #include<etc.h>

(SPJ SIDE51)

unsigned char DIGI[2];

delay Goto again

unsigned char right,cnt; P1 = 0; /* initialize all P1 outputs to be zero*/ P3 = 0; DIGI[1]=0xc0;/*(hex code for '0')*/ DIGI[2]=0xb0;/*(hex code for '3')*/

while(1) { for (cnt=1;cnt<3;cnt++) { P3 = cnt; /*Enable D0 and then D1*/ P1=DIGI[cnt];/*P1=c0 when D0 is enabled & P1=b0 when d1 is enabled*/ delay_ms(20); } } }

Interfacing to LCD Display

Most projects you create with the 8051 CPU require some form of display. The most common way to accomplish this is with the LCD (Liquid Crystal Display). LCDs have become a cheap and easy way to get text display for an embedded system Common displays are set up as 16 to 20 characters by 1 to 4 lines.

UNDERSTANDING LCD

Pinout
8 data pins D7:D0 Bi-directional data/command pins. Alphanumeric characters are sent in ASCII format. RS: Register Select RS = 0 -> Command Register is selected RS = 1 -> Data Register is selected R/W: Read or Write 0 -> Write, 1 -> Read E: Enable (Latch data) Used to latch the data present on the data pins. A high-to-low edge is needed to latch the data.

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

Display Data RAM (DDRAM)


Display data RAM (DDRAM) is where you send the characters (ASCII code) you want to see on the LCD screen. It stores display data represented in 8-bit character codes. Its capacity is 80 characters (bytes). Below you see DD RAM address layout of a 2*16 LCD.

In the above memory map, the area shaded in black is the visible display (For 16x2 display) . For first line addresses for first 15 characters is from 00h to 0Fh. But for second line address of first character is 40h and so on up to 4Fh for the 16th character. So if you want to display the text at specific positions of LCD , we require to manipulate address and then to set cursor position accordingly .

Character Generator RAM (CGRAM)-User defined character RAM


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

Registers
The HD44780 has two 8-bit registers, an instruction register (IR) and a data register (DR). The IR stores instruction codes. The DR temporarily stores data to be

written into DDRAM or CGRAM and temporarily stores data to be read from DDRAM or CGRAM. Data written into the DR is automatically written into DDRAM or CGRAM by an internal operation. . These two registers can be selected by the register selector (RS) signal. See the table below: Register Selection RS 0 0 1 1 R/W Operation 0 1 0 1 IR write as an internal operation (display clear, etc.) Read busy flag (DB7) and address counter (DB0 to DB6) DR write as an internal operation (DR to DDRAM or CGRAM) DR read as an internal operation (DDRAM or CGRAM to DR)

Busy Flag (BF)


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

LCD Commands
The LCDs internal controller accept several commands and modify the display accordingly. These commands would be things like: Clear screen Return home Shift display right/left

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

Decimal 56 48 40 32 See Below 28 24 2 16 20 14 15 12 8 12 1 128 + addr 64 + addr

HEX 38 30 28 20 See Below 1E 18 2 10 14 0E 0F 0C 08 0C 01 80+ addr 40+ addr

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

Set cursor position (DDRAM address)

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

INTERFACING LCD TO 8051

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

Checking the Busy Flag


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

1. 2. 3. 4.

Set R/W Pin of the LCD HIGH(read from the LCD) Select the instruction register by setting RS pin LOW Enable the LCD by Setting the enable pin HIGH The most significant bit of the LCD data bus is the state of the busy flag(1=Busy,0=ready to accept instructions/data). The other bits hold the current value of the address counter.

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

CODE EXAMPLE
It is easy (and clean tech. ) to make different subroutines and then call them as we need.

Busy flag checking ready: setb P1.7 ;D7 as input clr P3.6 ;RS=0 cmd setb P3.5 ;RW=1 for read again: setb P3.7 ;H->L pulse on E clr P3.7 jb P1.7, again ret

Data write Routine data: mov P1, A ;move acc. data to port setb P3.6 ;RS=1 data clr P3.5 ;RW=0 for write setb P3.7 ;H->L pulse on E clr P3.7 lcall ready ret

Command write Routine command: mov P1, A ;move acc. data to port clr P3.6 ;RS=0 for cmd clr P3.5 ;RW=0 for write setb P3.7 ;H->L pulse on E clr P3.7 lcall ready ret

Initialization initialization: mov A, #38H ; Initialize, 2-lines, 5X7 matrix. lcall Command mov A, #0EH ; LCD on, cursor on lcall Command mov A, #01H ; Clear LCD Screen lcall Command mov A, #06H ; Shift cursor right lcall Command

Display clear clear: setb p3.7 ;enable EN clr 3.6 ;RS=0 for cmd. mov DATA,#01h clr p3.7 ;disable EN lcall ready RET Note- As we need to clear the LCD frequently and not the whole initialisation , it is better to use this routine separately.

Displaying "HI"

lcall initialization lcall clear mov A,#'H' acall data mov A,#'I' lcall data

Let's now try code for displaying text at specific positions. I want to display "MAHESH" in message "Hi MAHESH" at the right corner of first line then I should start from 10th character.

So referring to table 80h+0Ah= 8Ah. So below is code and I don's think that you will need explanation comments. ASSEMBLY LANGUAGE

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

ADC-DAC Interfacing
Analog signals are very common inputs to embedded systems .Most transducers and sensors such as temperature ,pressure ,velocity ,humidity are analog. Therefore we need to convert these analog signals in to digital so that 8051 can read it.

ANALOG DIGITAL TO CONVERTER - ADC


Commonly used ADC device ADC804

ABOUT IC PinOut
CS Chip Select , active low RD Read Digital data from ADC, H-L edge triggered WR -- Start conversion, L-H pulse edge triggered INTR -- end of conversion, Goes low to indicate conversion done Data bits -- D0-D7 CLK IN & CLK R CLK IN is an input pin connected to an external clock source when an external clock is used for timing. However, ADC804 has an internal clock

generator. To use the internal clock generator of the ADC804, the CLK IN and CLK R pins are connected to a capacitor and a resistor. In that case, the clock frequency is determined by the equation. f = 1/1.1RC R=10K and C=150pF f=606Hz the conversion time is 110us.

Input Voltage range


Default 0-5V. Can be changed by setting different value for Vref/2 pin. Vin=Vin(+) Vin (-) Range = 0 to 2x Vref/2. for Vin = 2x Vref/2. we get 256 as a digital output on D0-D7. (Refer Table) Step Size a Smallest change (2 x Vref/2)/ 256 for ADC804

Vref/2 (Volts) Open (2.5) 2.56 1.28 0.5

Vin (Volts) 0 to 5 0 to 5.12 0 to 2.56 0 to 1

Step size (mV) 5/256 = 19.53 5.12/256 =20 2.56/256 = 10 1/256=3.90

for eg for step size 10mv ,digital output on D0-D7 changes by one count for every 10mv change of the input analog voltage.

Data Out
Dout = Vin / Step Size
for input vtg. of 2.56 volts (Vref=1.28 volts) and stepsize of 10mv Dout =2560/10 =256 or FF that is full scale output.

Conversion Time
Greater than 110us for ADC804

Resolution
8 bits for ADC804

INTERFACING ADC804 TO 8051

Signals to be interfaced (on the ADC804) D0-D7, RD, WR, INTR, CS Can do both Memory mapping and IO mapping

Memory Mapping (timing is critical) Connect D0-D7 of ADC804 to the data bus of the 8051 system Connect RD, WR of the ADC804 to the 8051 system (ensure polarity) Connect CS of ADC804 to an appropriate address decoder output Connect INTR of ADC804 to an external interrupt Pin on the 8051 (INT0 or INT1) IO Mapping (easiest - I prefer ) Connect D0-D7, RD, WR, CS, INTR to some port bits on the 8051 (12 in all).

Algorithm
Make CS=0 and send a low-to-high to pin WR to start the conversion. Keep monitoring INTR If INTR =0, the conversion is finished and we can go to the next step. If INTR=1, keep polling until it goes low. After INTR=0, we make CS=0 and send a high-to-low pulse to RD to get the data out of the ADC804 chip.

ASSEMBLY LANGUEGE

(A51)

ADC_IO: mov P1, #0xff ; To configure as input AGAIN clr p3.7 ;Chip select setb P3.6 ;RD=1 clr P3.5 ;WR=0 setb P3.5 ;WR=1- low to high transition WAIT: jb P3.4, WAIT ;wait for INTR clr p3.7 ;generate cs to ADC

clr P3.6 ;RD=0 -High to low transition mov A, P1 ;read digital o/p sjmp AGAIN

INTERFACING ADC804 TO 8051


ADC808/809 Chip with 8 analog channel. This means this kind of chip allows to monitor 8 different transducers. ADC804 has only ONE analog input: Vin(+). ALE: Latch in the address Start : Start of conversion (same as WR in 804) OE: output enable (same as RD in 804) EOC: End of Conversion (same as INTR in 804)

Channel IN0 IN1 IN2 IN3 IN4 IN5 IN6 IN7

CBA 000 001 010 011 100 101 110 111

Algorithm
Notice that the ADC808/809 that there is no self-clocking and the clock must be provided from an external source to the CLK pin. (you can use programmable clock oscillator to enable or disable clock by programmable bit. )

Select an analog channel by provide bits to A, B, C. Enable clock Activate ALE with a low-to-high pulse. Activate SC with a high-to-low pulse (start conversion) The conversion is begun on the falling edge of the start conversion pulse. you can use circuit like Monitor EOC Pin .After conversion this pin goes high. Activate OE with a high-to-low pulse to read data out of the ADC chip.

DIGITAL TO ANALOG CONVERTER - DAC


Commonly used DAC808 (MC1408) R/2R ladder Iout = Iref (D7/2 + D6/4 + D5/8 + + D0/256) Iout converted to voltage by a resistive load or op-amp based isolator (Rf from Vout to V- and V+ to GND) PinOut D0-D7 Connected to the Processors IO port Vref+, Vref-, Vee Usage: Just write a byte to the IO port and the DAC converts it to an analog value

Sensors Interfacing
Transducer is a device capable of being actuated by an an energizing input from one or more transmission media and in turn generating a related signal to one or more transmission systems. It provides a usable output in response to specified input measurand , which may be in the form physical, chemical, Mechanical or optical.... For eg. temperature transducer transduces temp. changes to equivalent resistance changes which can further converted into electrical signal (voltage) for measurements.

TEMPERATURE 1. LM35 Precision temperature sensor


LM34 series are precision integration-circuit temperature sensors whose output voltage is linearly proportional to the Fahrenheit temperature. LM35 series are precision integration-circuit temperature sensors whose output voltage is linearly proportional to the Celsius temperature.

P/N LM35A LM35 LM35CA LM35C LM35D

Temperature Range (oC) -55 to 150 -55to 150 -40 to 110 -40 to 110 0 to 100

Accuracy (oC) 1.0 1.5 1.0 1.5 2.0

Output (mv/oC) 10 10 10 10 10

I am using LM35DT package to operate over a 0 to +100C temperature range

R5 and C3 are used for capacitive load compensation.

INTERFACING TO MICROCONTROLLER USING ADC804

The ADC804 has 8-bit resolution with a maximum of 256 steps and the LM35 produces 10mV for every degree of temperature change. We will do calibration such that , for temperature range of 0 to 100C , voltage in at the input of ADC will be 0 to 2.56 v.

we need to set Vref/2 = 1.28V so step size will be 2560mv/256 = 10mv also for every degree change in temp. LM35 output changes by 10mv ,so every degree change in temp. will produce 1 unit change in digital out of ADC

Thus resolution of our system will be 1deg C , which is Smallest temp. that we can measure with this system.

CALIBRATION For Temperature range 0 to 100C Output voltage 0V to 1V

Required gain of amplifier

Required Max. voltage input for ADC / Vout at LM35 = 2560mv /100mv =2.56

Use preset for R2 --> 5.12KOhms

so gain =R3/R2 =2.56

Although our theoretical design is correct , operational amplifiers are often needed to to be calibrated practically , what i mean to say is that you need to adjust gain of amp. (Adjusting pot -R2) so that we get designed output at various temperature. That is if current temp. is 25C , LM35 output will be 250mv and amp. output should be 250x2.56 =0.64v . if it is not, adjust R2. LM35 has a limited ability to drive heavy capacitive loads. The LM35 by itself is able to drive 50 pf without special precautions. you can improve the tolerance of capacitance with a series R-C damper from output to ground.

2. P100 Platinum resistance temp. detector .


PT 1 00 - platinum resistance temp. detector (PRTD) . PT 1 00 has a resistance of 100 W at zero deg. Celsius . Linear Sensitivity-a0 =0.00385W/ deg. Celsius Response time - 0.5 to 5 s or more. DESIGN (0 to 85 deg. cel.) 1) R1*R4 = R2*R3 -----BRIDGE

BALANCE CONDITION

2) 3)

Rt = Ro [ 1 + a T] ----- RESISTANCE VARIATION FOR RTD Vab = V*R3 / ( R1 + R3 ) - VR4 /( R2 + R4 ) --- BRIDGE OUTPUT (V=5v)

4) Vo = R2 / R1 ( Va Vb )---- GAIN OF INSTRUMENTATION AMPLIFIER 1. At 0oC R1=R2=R3 =R4(100 W RTD )=100 ohms. so bridge is balance -o/p vtg 0v 2.At 85 oC R85 = 100 ( 1 + 0.00385 [ 85 ] ) = 132.72 ohms Bridge output Vab = 0.35V. (FOR R1=R2=R3=100ohms)

3.Gain of Amplifier Vo = R2 / R1 ( Va Vb ) For Vab = 0.351 & A = R2 / R1 = 14.62 For R1 = 1 k ohm ; We let R2 = 14.62 K ohm approx. R2 = 15 k ohm(use preset). Vo = 0.351 V at 85 deg. Cel.

Since the change in resistance of RTD w.r.t. temp.is linear , the change in bridge output is also linear w.r.t. temp. i.e. change in temp. from 0

to 85 deg. Cel. causes bridge output to change from 0 to 0.351 V. I have given Ref voltage of 5.12 v to ADC chip so step size will be ,5120mV/256 (8 bit ADC) =20 mV. So bridge output voltage in the range 0 to 0.351 V corresponding to 0 to 85oC change in temperature is converted in to 0 to 5.12V using Amplifier having gain of 14.62 . Interfacing is same as that I have shown in ADC-DAC page .

PROGRAM LOGIC: Output of an ADC is from 00 TO FFH for an input voltage variation of 0 to 5.12V. I used lookup table method to display the proper temperature. For this,I prepare a lookup table of 256 values(00 to FF)i.e output of ADC.. An small example of a lookup table has been shown below. Values corresponding to output of ADC are selected from lookup table and displayed. CONCEPT FOR LOOK- UP TABLE:

ADC OUTPUT 0000 0001 0002 0003 0004 0005 Cntd 00FE 00FF 00 00 00 01 01 01

TEMPERATURE IN DEG.CEL

85 85

SONAR MODULE
Sonar's are basically a device that puts out an inaudible pulse, and counts the time it takes to get an echo. The Polaroid 6500 series sonar ranging module has a range of 6" to 35 feet. INTERFACING TO 8051

Polaroid makes the 6500 series sonar ranging module. Basically the init line is brought high and a timer is started, when the echo line goes high the time counted is run through a simple formula of 0.9 ms per foot to calculate the distance traveled to an object detected. An additional line may be brought to the MCU if object detection of distances less than 18 inches is desired.

+5v +---------+ init echo | sonar | | +---| | gnd to MCU -------| -------| | / \ |===| transducer | | | |---+ module |

+---------+

Stepper Motor

BASICS OF STEPPER MOTOR


Of all motors, step motor is the easiest to control. It's handling simplicity is really hard to deny - all there is to do is to bring the sequence of rectangle impulses to one input of step controller and direction information to another input. Direction information is very simple and comes down to "left" for logical one on that pin and "right" for logical zero. Motor control is also very simple - every impulse makes the motor operating for one step and if there is no impulse the motor won't start. Pause between impulses can be shorter or longer and it defines revolution rate. This rate cannot be infinite because the motor won't be able to "catch up" with all the impulses (documentation on specific motor should contain such information). The picture below represents the scheme for connecting the step motor to microcontroller and appropriate program code follows. The key to driving a stepper is realizing how the motor is constructed. A diagram shows the representation of a 4 coil motor, so named because 4 coils are used to cause the revolution of the drive shaft. Each coil must be energized in the correct order for the motor to spin.

In Figure 3.3, as in Figure 3.1, boxes are used to represent switches; a control unit, not shown, is responsible for providing the control signals to open and close the switches at the appropriate times in order to spin the motors. The control unit is commonly a computer or programmable interface controller, with software directly generating the outputs needed to control the switches.

As with drive circuitry for variable reluctance motors, we must deal with the inductive kick produced when each of these switches is turned off. Again, we may shunt the inductive kick using diodes, but now, 4 diodes are required, as shown in Figure 3.4:

Step angle
It is angle through which motor shaft rotates in one step. step angle is different for different motor . selection of motor according to step angle depends on the application , simply if you require small increments in rottion choose motor having smaller step angle. No of steps require to rotate one complete rotation = 360 deg. / step angle in deg.

Steps/second
The relation between RPM and steps per sec. is given by , steps or impulses /sec. =(RPM X Steps /revolution ) /60 Pause between impulses can be shorter or longer and it defines revolution rate. This rate cannot be infinite because the motor won't be able to "catch up" with all the impulses (documentation on specific motor should contain such information). So referring to RPM value in datasheet you can calculate steps/sec and from it delay or pause between impulses

INTERFACING TO 8051.

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

Coil A 0 0 1 1

Coil B 1 0 0 1

Coil C 1 1 0 0

Coil D 0 1 1 0

Step 1 2 3 4

CODE EXAMPLE
To move motor in forward direction continuously

Connection -P1.0 -P1.3 connected to Coils A -D.

ASSEMBLY LANGUAGE mov a,#66h ;Load step sequence AGAIN mov p2,a ;issue sequence to motor rr a ;rotate step sequence right clockwise=Next sequence acall DELAY ;~ 20 msec. sjmp AGAIN ;Repete again

C LANGUAGE void main () { TMOD = 0x20 ; TCON = 0x40 ; TH1 = 0xf9 ; TL1 = 0xf9 ; PCON = 0x80 ; SCON = 0x50 ;

(SPJ)

while (1) /*continues loop */ { printf("a"); /* transmit a along with CR & LF. }

CONTROLLING STEPPER MOTOR WITH TWO PORT PINS ONLY


For Forward

D0 0 0 1 1

D0 0 1 0 1

Coil energized AB BC CD DA

To reverse the motor just reverse the above sequence viz. 11,10,01,00.

Você também pode gostar