62
Basic Circuit for 8051 8051 PIN OUT Power - Vcc, Vss Reset - RST Crystal - XTAL[1,2] Externa l device interfacing EA, ALE, PSEN, WR, RD I/O Port – P0[7;0], P1[7:0], P2[7:0], P3 P3 is shared with control lines – Serial I/O RxD, TxD, – external interrupts INT0, INT1 – Counter control T0, T1

Basic Circuit for 8051

Embed Size (px)

DESCRIPTION

8051

Citation preview

Page 1: Basic Circuit for 8051

Basic Circuit for 8051 

                                                                                                     

           

8051 PIN OUT 

  Power - Vcc, Vss

 Reset - RST

 Crystal - XTAL[1,2]

 Externa l device interfacing      – EA, ALE, PSEN, WR, RD

  I/O Port      – P0[7;0], P1[7:0], P2[7:0], P3

    P3 is shared with control lines        – Serial I/O RxD, TxD,         – external interrupts INT0,  INT1         – Counter control T0, T1

    P0 and P2 are multiplexed with Address and Data bus

  

 

BASIC CIRCUIT -THAT MAKES 8051 WORKS.

Page 2: Basic Circuit for 8051

 

                                                   

EA/VP PinThe EA on pin 31 is tied high to make the 8051 executes program from Internal ROM

Page 3: Basic Circuit for 8051

 

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

  Power- On Reset

    - Initially charging of capacitor makes RST High    - When capacitor charges fully it blocks DC.

  Manual reset

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

 

 

 

 

 

 

Note: content of on-chip RAM is not affected by Reset.

 

Register Content Register Content

Program counter 0000h IP XXX00000b

Accumulator 00h IEv 0XX00000b

B register 00h All timer registers 00h

PSW 00h SCON 00h

SP 07h SBUF 00h

DPTR 0000h PCON (HMOS) 0XXXXXXXbv

All ports FFh PCON (CMOS)v 0XXX0000b

Page 4: Basic Circuit for 8051

Oscillator Circuit

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

8051 has an on-chip oscillator. It needs an external crystal thats decides the operating frequency of the 8051.

 This can be achieved in two ways,,

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 speeds (9600, 19200). Despite the "oddball" value, these crystals are readily available and commonly used.

 

Page 5: Basic Circuit for 8051

Power Supply

 

C1-1000 mf ,C2-100 mf

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

 

 

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   Voltage Current

High Above 2.4V Virtually no current flow

Low Below 0.9V1.6mA Sinking current from TTL input to ground(Depends on logic family)

 

 Port functions

Ports   Function

Port 0 Dual-purpose port- 1. general purpose I/O Port.

Page 6: Basic Circuit for 8051

(Pin 32-39)                                 2. multiplexed address & data bus                                                           Open drain outputs

Port 1

(Pin 1-8)

 

 Dedicated I/O port – Used solely  for interfacing to external devices                                               Internal pull-ups

Port 2

(Pin 21-28)

 

Dual-purpose port-  1. general purpose I/O port.                                   2. a multiplexed address & data bus.                                  Internal pull-ups

Port 3

(Pin 10-17)

 

Dual-purpose port-  1. general purpose I/O port.                                  2. pins have alternate purpose related to special features of the 8051                                                Internal pull-ups

 

 

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

Page 7: Basic Circuit for 8051

                                       

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.

Page 8: Basic Circuit for 8051

2. Configuring for input

At power-on all are output ports by defaultTo configure any port for input, write all 1’s (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 re-entering the interrupt handler, so the rest of your program will execute very, very slowly.

Page 9: Basic Circuit for 8051

Interfacing to 8051 I/O ports. 

 

SWITCH ON I/O PORTS 

 Good Circuit

It is always best connecting the switch to ground with a pull-up resistor as shown in

the "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. The

voltage is 0V and all the sinking current requirement is met, so it is logic 0. The

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

and 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 circuitThe "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 circuitIn 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).

 

Page 10: Basic Circuit for 8051

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 circuitsince  the TTL output can't source above 1mA so the LED will be very dim. Fair circuitThe 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 circuitThe 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. 

Page 11: Basic Circuit for 8051

ASSEMBLY LANGUAGE   C LANGUAGE             (SPJ )

       

SETB P1.0       ;  input pin.LOOP: JB P2.0, LOOP  ; not grounded  then stay in loopCLR P0.0 ;To clear pin P0.0 when P1.0 is at 0 v   

 

 

 

 

 

 

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

 

RELAY ON I/O PORT (2CO Relay)

                                               

Page 12: Basic Circuit for 8051

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  

Page 13: Basic Circuit for 8051

                                                               

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.

Page 14: Basic Circuit for 8051

 

CODE EXAMPLE

ASSEMBLY LANGUAGE   C LANGUAGE             (SPJ SIDE51)

       

LOOP:mov p1,#0ffh ; To configure port for input.mov a,p1mov p0 ,asjmp 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;    }}

 

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 ! )

Page 15: Basic Circuit for 8051

 

                                                              

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.

Page 16: Basic Circuit for 8051

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 .

Page 17: Basic Circuit for 8051

 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)

 

Page 18: Basic Circuit for 8051

                                                                   

SETTING SERIAL PORT.

SCON8 bit UART ,RN enabled , TI & RI operated by program. - 50hex Timer 1 CountTH1 = 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 

Page 19: Basic Circuit for 8051

   CODE EXAMPLE

1. TRANSMITTING 'A' CONTINUOUSLY ON SERIAL PORT.

ASSEMBLY LANGUAGE   C LANGUAGE             (SPJ SIDE51)

       

 STARTmov TMOD, #20H ;T1 is mode2mov TH1, #0fd ;9600 baudmov SCON, #50H ;8b, 1stop, 1start, REN enabledanl 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)

   

#include <Intel\8052.h>#include <standard.h>#include<stdio.h>  

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.

 

Page 20: Basic Circuit for 8051

ASSEMBLY LANGUAGE   C LANGUAGE             (SPJ SIDE51)

 

START: mov TMOD, #20H ;T1 in mode 2mov TH1, #-3 ;9600 baudmov SCON, #50H ;8b, 1start, 1stopanl 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-edmov A, SBUF ;read the received byte from SBUFmov P1, A ;display on P1sjmp AGAIN ;while (1)

 

 

   

#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; } }  

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             (SPJ SIDE51)

  .org 0000hljmp 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 ()

Page 21: Basic Circuit for 8051

;********************TRANSMIT******************TRANSMIT:clr A ; clear A to get datamovc A,@A+DPTR ; get data from string at data pointerjz EXITSTR ; if data zero, eoslcall OUTCHAR ; else send characterinc dptr ; increment data pointersjmp 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 setclr ti ; clear buffer empty flagret

START:;******************INITIALISATION*****************mov TMOD, #20H ;T1 in mode 2mov TH1, #-3 ;9600 baudmov SCON, #50H ;8b, 1start, 1stopanl PCON, #07fh ;To make SMOD =0 setb TR1 ;start T1

;*****************To SEND DATA*******************mov dptr,#DATAlcall TRANSMITsjmp 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.

Page 22: Basic Circuit for 8051

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 outputMost 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 

Page 23: Basic Circuit for 8051

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.

 

 

 

Page 24: Basic Circuit for 8051

 

                                                                                                                                                                                                                                         

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                                                                                                               Hex Code

Digit Seg. h Seg. g Seg. f Seg. e Seg. d Seg. c Seg. b Seg. a HEX

0 1 1 0 0 0 0 0 0 C0

Segment number 8051 pin number

a P1.0

b P1.1

c P1.2

d P1.3

e P1.4

f P1.5

g p1.6

h(dp) P1.7

Page 25: Basic Circuit for 8051

1 0 0 0 0 0 1 1 0 06

2 1 0 1 0 0 1 0 0 A4

3 1 0 1 1 0 0 0 0 B0

4 1 0 0 1 1 0 0 1 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

Page 26: Basic Circuit for 8051

                                                                                                                                                           

                                                                                                                                                                                          

                   

 

   

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   C LANGUAGE             (SPJ SIDE51)

 

 

 

 

 

 

start : disable [D0:D1]

again : enable D0

[a:h] - pattern for Digit1

delay

disable D0. Enable D1

[a:h] - pattern for Digit2

    #include <Intel\8052.h>

#include <standard.h>

#include<stdio.h>

#include<etc.h>

void main( ){

unsigned char DIGI[2];

Page 27: Basic Circuit for 8051

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 

Page 28: Basic Circuit for 8051

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

 

Page 29: Basic Circuit for 8051

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:

Page 30: Basic Circuit for 8051

    Register Selection

RS R/W Operation

0 0 IR write as an internal operation (display clear, etc.)

0 1 Read busy flag (DB7) and address counter (DB0 to DB6)

1 0 DR write as an internal operation (DR to DDRAM or CGRAM)

1 1 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 LCD’s internal controller accept several commands and modify the display accordingly. These commands would be things like:

– Clear screen

– Return home

– Shift display right/left

 

Instruction Decimal HEX

Function set (8-bit interface, 2 lines, 5*7 Pixels) 56 38

Function set (8-bit interface, 1 line, 5*7 Pixels) 48 30

Function set (4-bit interface, 2 lines, 5*7 Pixels) 40 28

Page 31: Basic Circuit for 8051

Function set (4-bit interface, 1 line, 5*7 Pixels) 32 20

Entry mode set See Below See Below

Scroll display one character right (all lines) 28 1E

Scroll display one character left (all lines) 24 18

Home (move cursor to top/left character position) 2 2

Move cursor one character left 16 10

Move cursor one character right 20 14

Turn on visible underline cursor 14 0E

Turn on visible blinking-block cursor 15 0F

Make cursor invisible 12 0C

Blank the display (without clearing) 8 08

Restore the display (with cursor hidden) 12 0C

Clear Screen 1 01

Set cursor position (DDRAM address) 128 + addr 80+ addr

Set pointer in character-generator RAM (CG RAM address) 64 + addr 40+ addr

Entry mode set

This command sets cursor move direction and display shift ON/OFF. There are 4 possible function set commands;04, 05, 06, and 07. This command changes the

direction the cursor moves by setting the address counter to increment or decrement. This command is very important. If you do not understand it you may not

see anything or what you actually wanted to see on LCD screen. I have created 4 animated gifs to demonstrate what the function set command is all about.

 

Set cursor position (DDRAM address)

As said earlier if we want to display the text at specific positions of LCD , we require to manipulate address and then to set cursor position accordingly.

I want to display "MAHESH" in message "Hi MAHESH" at the right corner of first line then I should start from 10th character.

So referring to table 80h+0Ah= 8Ah.

Page 32: Basic Circuit for 8051

 

 

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. Set R/W Pin of the LCD HIGH(read from the LCD) 2. Select the instruction register by setting RS pin LOW 3. Enable the LCD by Setting the enable pin HIGH 4. The most significant bit of the LCD data bus is the state of the busy flag(1=Busy,0=ready to accept instructions/data). The other bits hold the current

value of the address counter.

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

Page 33: Basic Circuit for 8051

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   Data write Routine   Command write Routine

ready: setb P1.7 ;D7 as inputclr P3.6 ;RS=0 cmdsetb P3.5 ;RW=1 for read again: setb P3.7 ;H->L pulse on Eclr P3.7jb P1.7, againret

  data: mov P1, A ;move acc. data to portsetb P3.6 ;RS=1 dataclr P3.5 ;RW=0 for writesetb P3.7 ;H->L pulse on Eclr P3.7lcall readyret 

   

command:mov P1, A ;move acc. data to portclr P3.6 ;RS=0 for cmdclr P3.5 ;RW=0 for writesetb P3.7 ;H->L pulse on Eclr P3.7lcall readyret

   

Initialization    Display clear   Displaying "HI"

initialization:mov A, #38H ; Initialize, 2-lines, 5X7 matrix.lcall  Commandmov A, #0EH ; LCD on, cursor onlcall  Commandmov A, #01H ; Clear LCD Screenlcall  Command

  clear:setb p3.7 ;enable ENclr 3.6 ;RS=0 for cmd.mov DATA,#01hclr p3.7 ;disable  ENlcall  readyRET

   lcall initializationlcall clearmov A,#'H'acall datamov A,#'I'lcall data

Page 34: Basic Circuit for 8051

mov A, #06H ; Shift cursor rightlcall  Command 

Note- As we need to clear the LCD frequently and not the whole initialisation , it is better to use this routine separately.

 

 

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 Initializationlcall clearmov a,#'H'lcall datamov a,#'I'lcall data

mov a,#8ahlcall command

 

Page 35: Basic Circuit for 8051

mov a,#'M'lcall datamov a,#'A'lcall datamov a,#'H'lcall datamov a,#'E'lcall datamov a,#'S'lcall datamov a,#'H'lcall data

 

ADC-DAC InterfacingAnalog 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.

Page 36: Basic Circuit for 8051

 

 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

Page 37: Basic Circuit for 8051

• 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

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

Vref/2

(Volts)

Vin

(Volts)

Step size (mV)

Open (2.5) 0 to 5 5/256 = 19.53

2.56 0 to 5.12 5.12/256 =20

1.28 0 to 2.56 2.56/256 = 10

0.5 0 to 1 1/256=3.90

Page 38: Basic Circuit for 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.

 

Page 39: Basic Circuit for 8051

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(+).

Page 40: Basic Circuit for 8051

• 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)

 

   

   

   

   

   

 

 

 

 

 

 

 

 

Algorithm

Channel C B A

IN0 000

IN1 001

IN2 010

IN3 011

IN4 100

IN5 101

IN6 110

IN7 111

Page 41: Basic Circuit for 8051

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 Processor’s IO port

– Vref+, Vref-, Vee

 

Page 42: Basic Circuit for 8051

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/NTemperature

Range (oC)Accuracy (oC) Output (mv/oC)

LM35A  -55 to 150  1.0  10

Page 43: Basic Circuit for 8051

LM35  -55to 150 1.5 10

LM35CA -40 to 110 1.0 10

LM35C -40 to 110 1.5 10

LM35D  0 to 100 2.0 10

 

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

 

    R5 and C3 are used for capacitive load compensation.

     

 

Page 44: Basic Circuit for 8051

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 100°C , 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.

 

Page 45: Basic Circuit for 8051

 

CALIBRATION

For Temperature range 0 to 100°C  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 25°C ,

LM35 output will be 250mv and amp. output should be 250x2.56 =0.64v . if it is not,  adjust R2.

Page 46: Basic Circuit for 8051

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)    Rt = Ro [ 1 + a T]  ----- RESISTANCE VARIATION FOR RTD

3)    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                          

Page 47: Basic Circuit for 8051

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  &        Vo  = 0.351 V at 85 deg. Cel.

         A = R2 / R1  = 14.62

           For R1 = 1 k ohm ;     We let R2 = 14.62 K ohm  approx. R2 = 15 k ohm(use preset).

 

 

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

Page 48: Basic Circuit for 8051

below. Values corresponding to output of ADC are selected  from lookup table and displayed. 

CONCEPT FOR LOOK- UP  TABLE:

ADC OUTPUT TEMPERATURE IN DEG.CEL

0000 00

0001 00

0002 00

0003 01

0004 01

0005 01

Cntd  

   

00FE 85

00FF 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

Page 49: Basic Circuit for 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 | |---+

to MCU -------| sonar |

echo | module | /

-------| |===| transducer

| | \

+---| |

| +---------+

gnd

Stepper Motor

 

 

BASICS OF STEPPER MOTOR

Page 50: Basic Circuit for 8051

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.

Page 51: Basic Circuit for 8051

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.

Page 52: Basic Circuit for 8051

 

Coil A Coil B Coil C Coil D Step

0 1 1 0 1

0 0 1 1 2

1 0 0 1 3

1 1 0 0 4

 

 

CODE EXAMPLE

To move motor in forward direction continuously

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

ASSEMBLY LANGUAGE    C LANGUAGE             (SPJ)

Page 53: Basic Circuit for 8051

 

 

 

 

 

 

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   

void main ()

{

TMOD = 0x20 ;

TCON = 0x40 ;

TH1 = 0xf9 ;

TL1 = 0xf9 ;

PCON = 0x80 ;

SCON = 0x50 ;

while (1) /*continues loop */

{

printf("a"); /* transmit a along with CR & LF.

}

 

 

  CONTROLLING STEPPER MOTOR WITH TWO PORT PINS ONLY

 For Forward

Page 54: Basic Circuit for 8051

 

 

 

 

 

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

D0 D0 Coil energized

0 0 AB

0 1 BC

1 0 CD

1 1 DA