8051

24
Intel 8051 microcontroller David Wilson 8051 Architecture & basic programming model S TUDENT VERSION Department of Electrical Engineering University of Karlstad March 1998 David Wilson 1/48 Intel 8051 microcontroller UNIVERSITY OF KARLSTAD 1 Microprocessors & microcontrollers This course is really about microcontrollers (8051), not about micro- processors such as the PC 8086. microprocessors IBM PC, general purpose, multi-chips required for all the functions. microcontrollers true computer on a chip, logic functions, bit ad- dressing, small cheap & fast. True “computer on a single chip”. Block diagram of a microprocessor & controller ALU Accumulator Working registers prog counter clock stack ptr interrupt circuits I/O port I/O port interrupt clock timer internal ROM ALU ACC W.Reg. internal RAM stack ptr PC micro-controller microprocessor David Wilson 2/48 Intel 8051 microcontroller 1 Microprocessors & microcontrollers UNIVERSITY OF KARLSTAD

Upload: api-3776064

Post on 14-Nov-2014

12 views

Category:

Documents


0 download

DESCRIPTION

its a 8051 pdf file. its really gud one

TRANSCRIPT

Page 1: 8051

Intel 8051 microcontroller

David Wilson

8051 Architecture & basic programming model

STUDENT VERSION

Department of Electrical EngineeringUniversity of Karlstad

March 1998

David Wilson1/48

Intel 8051 microcontrollerUNIVERSITY OF

KARLSTAD

1 Microprocessors & microcontrollers

This course is really about microcontrollers (8051), not about micro-processors such as the PC 8086.

microprocessors IBM PC, general purpose, multi-chips requiredfor all the functions.

microcontrollers true computer on a chip, logic functions, bit ad-dressing, small cheap & fast. True “computer on a single chip”.

Block diagram of a microprocessor & controller

ALU

AccumulatorWorking registers

prog counter

clock

stack ptr

interrupt circuits

I/O port

I/O port

interrupt

clock

timer

internalROM

ALU

ACCW.Reg.

internalRAM

stack ptr PC

micro-controller

microprocessor

David Wilson2/48

Intel 8051 microcontroller1 Microprocessors & microcontrollers

UNIVERSITY OF

KARLSTAD

Page 2: 8051

Microcomputers & microcontrollers

Essential elements of any computer are:

CPU or central processing unit

memory for both data and program

I/O or input/output system

Various different architectures exist depending on the application.

Mini-computer all 3 systems mounted on a board

Micro-computer 2 systems on a single chip.

Micro-controller All systems on a single chip.

The Intel 8051 is an example of a micro-controller.

David Wilson3/48

Intel 8051 microcontroller1 Microcomputers & microcontrollers /2

UNIVERSITY OF

KARLSTAD

2 An micro-controller application

DIW

Measuring house heating

Motivation I have just moved into a villa, and my electricity bill ismuch higher than it was in Australia! So I would like to monitor thetemperature inside and outside of my house in different rooms overat least 48 hours.

Requirement Use one 8051 as a data logger and local storage de-vice. It should measure around 5 temperatures say every minute,and store them so I can load them up from the 8051 via a serial ca-ble to my PC every couple of days.

Heat distribution in my oven & fridge

Motivation I have an old oven without a fan, and I discover thatwhen baking, you must be very careful as to where you place thefood (near the top, or near the bottom etc.) I would like a timevarying 3D temperature map of my oven.

David Wilson4/48

Intel 8051 microcontroller2 An micro-controller application

UNIVERSITY OF

KARLSTAD

Page 3: 8051

3 Intel 8051 microcontroller

The 8051 is a Single Chip Computer or microcontroller made byIntel. It is one of the most widely used microcontroller chips in theworld.

� A stand alone, high performance, single chip computer for con-troller applications

� Small, cheap & 40 pins. (# of pins increases size & cost.)

� 64k program memory

� 64k data memory

Our 8031 version is very similar to the generic 8051, but it has somefeatures attractive for proto-typing:

��

��

David Wilson5/48

Intel 8051 microcontroller3 Intel 8051 microcontroller

UNIVERSITY OF

KARLSTAD

4 8051 pin layout

The 40 pin package has a pin DIP (dual in-line package) layout asfollows:

But a 44 pin square layout exists and the more advanced membersof the 8051 family have slightly different layouts.

For what is inside this ‘black-box’, see following overheads.

David Wilson6/48

Intel 8051 microcontroller4 8051 pin layout

UNIVERSITY OF

KARLSTAD

Page 4: 8051

5 8051 Controller

A minimal 8051-based controller needs only the following compo-nents:

1.

2.

3.

Basic SBC51

Memory8051 CPU

--�

A[0..15]D[0..7]D[0..7]

A[0..15]

- Read#

- WR#

Address bus

-

��

-

input/output

P3.[0..7]P1.[0..7]

� Buses (groups of 8) are wide lines, single lines are bits

� Address (2 buses) give 16 bits (0x0000 – 0xFFFF)

� Data is bidirectional, address unidirectional from CPU to mem-ory

� Read & write strobes one way.

David Wilson7/48

Intel 8051 microcontroller5 8051 Controller

UNIVERSITY OF

KARLSTAD

6 8051 CPU architecture

Compare what crosses the dashed line with the pin-out diagramgiven previously.

David Wilson8/48

Intel 8051 microcontroller6 8051 CPU architecture

UNIVERSITY OF

KARLSTAD

Page 5: 8051

Ref Ayala, p56–57

8051 architecture given previously contains the following:

Registers � 8bit CPU registers (called the ‘A’ register or accumu-lator & B register)

� 16bit program counter & data pointer

� 8bit program status word

� Control registers

Internal ROM of zero (8031) to 4K (8051)

Internal RAM of 128 bytes

� 4 register banks

� 16 bytes (bit addressable)

� 80 bytes of general purpose scratch pad.

Timers & counters (16 bits)

David Wilson9/48

Intel 8051 microcontroller6 8051 architecture /2

UNIVERSITY OF

KARLSTAD

7 The Single-Board-Computer SBC51

We have a laboratory proto-type single board computer based onthe Intel 8051 called a SBC51. However we will use a PC for editing,storage of source programs and assembling. We will “dump” thecompiled code from the PC to SBC51 using a serial cable.

SBC51 board components

DisplayPort #1

Serial to PC

80C32

EPROM

8255

switches Digital outAnalogue in/out

Singlestep

reset

switch

See the component layout on p58, and the circuit diagram follow-ing. Also read chapter 9 of Ayala.

David Wilson10/48

Intel 8051 microcontroller7 The Single-Board-Computer SBC51

UNIVERSITY OF

KARLSTAD

Page 6: 8051

A picture of an equivalent single board computer proto-type kit.(Not exactly the same as what we have in the lab)

This configuration has

� 80C32 (square package) with BASIC & external ROM

� liquid crystal display (LCD) screen, 2 by 16

� Serial connection (to dump programs & data)

� hexadecimal keypad (4� 5) buttons

David Wilson11/48

Intel 8051 microcontroller7 A single board computer /2

UNIVERSITY OF

KARLSTAD

Getting started with the SBC51 Read this before the first laboratory.

1. Connect the PC port COM1to the SBC port P1 with the serialcable, 9600, no parity & 1 stop bit. Use MSD.EXEto check &mode to check your settings.

2. Turn on the SBC51 & reboot the PC under DOS. (It will givestrange results under Windows or NT, possibly not communi-cating)

3. Choose the SBC51or andra program in the boot menu, andthen start the program:

c:> cd sbc51\work

c:> sbc51\work\sbc.exe

4. Load your program using the LOAD FILE menu.

5. Edit your file if necessary, use ALT-h for help.

6. Assemble your program to a relocatable object file, a R03, thenlink to an Intel hexadecimal HEX file.

7. Choose TERMINALand

(a) press ALT-C to set up the serial communication to theSBC51.

(b) Press the RESET button on the SBC51

(c) Press ALT-L to download the hexcode.

8. Start with the laboratories, p3 1.1

David Wilson12/48

Intel 8051 microcontroller7 Getting started with the SBC51 /3

UNIVERSITY OF

KARLSTAD

Page 7: 8051

8 8051 Memory types

The 8051 has two separate memory blocks, for data and program.Since both blocks have the same address, this is called a Harvardarchitecture.

Separating the program memory from the data memory improvesreliablility since we cannot inadventently overwrite the programcode, and allows us to use program ROM, or read only memory.

Program memory normally we will have 4K on the chip (but not inthe case of the 8031)

4K internal

60K externalor 64K external

80318051(our proto-type version)

Program memory

Data memory all 64K is off the chip except for (a miniscule 128bytes).

David Wilson13/48

Intel 8051 microcontroller8 8051 Memory types

UNIVERSITY OF

KARLSTAD

Data memory internal 256 bytes is divided into two parts: generalscratch and the special function registers SFRs. (See description fol-lowing).

00

and7F80

128 bytesinternal

Data memory

128 bytesinternal

SFR64K

external

FF

00

FFFF

8><>:

8><>:direct addressing only

direct & indirect addressing

The 128 bytes in lower internal RAM have the following structure:

.................................

.................................

.................................

9>=>;

bank #0bank #1bank #2bank #3

7 6 5 4 3 2 1 0

register banks

.................................

................................. �

bit addressable area

scratch pad

0007

� � � 201F

7F

� Only one of the 4 register banks can be active at any particulartime

� Which one is active is given by flags in the PSW

David Wilson14/48

Intel 8051 microcontroller8 Data memory /2

UNIVERSITY OF

KARLSTAD

Page 8: 8051

9 Special Function Registers

The Special Function Registers (SFRs) contain memory locationsthat are used for special tasks. (They should not be used for gen-eral purpose tasks.)

Each SFR occupies internal RAM from 0x80 to 0xFF, (but some areasare empty!) They are 8 bits wide. Some examples are:

A register or accumulator is used for most ALU operations & exter-nal moves

B used for mltiplication & division and can also be used for generalpurpose storage

PSW Program Status Word is a bit addressable register. Refer to themanual for the description of the bit fields.

See p48

Two special 16-bit registers (double registers):

PC or program counter. This is not directly addressable, nor does ithave a memory location

DPTR or data pointer. Is accessible two 8-bit registers: DPTRLowand DPThigh.

David Wilson15/48

Intel 8051 microcontroller9 Special Function Registers

UNIVERSITY OF

KARLSTAD

Program Status word (PSW)

Ayala, p62

The PSW is the most important of the SFRs. It is a byte registerwhich holds 8 bits that can addressed indivdually. Each bit is re-ferred to as a flag.

Flags can be either set (1) or cleared (0). This is more efficient thanusing an entire byte memory location for a binary variable.

The PSW is divided up as follows:7 6 5 4 3 2 1 0

CY AC F0 RS1 RS0 OV – PNote:

� We start numbering from zero and go right to left (MSB, or mostsignificant bit first)

� Flags are zero and one (not 1 & 2)� One flag should not be used, but is reversed for future use. Use

at your own peril

� Address as PSW.3 for RS0 for example.

Each of the flags has a special function, consult the manual.

Question What flags are set when the PSW holds 0x7C ?

David Wilson16/48

Intel 8051 microcontroller9 PSW /2

UNIVERSITY OF

KARLSTAD

Page 9: 8051

Bit addressable SFRsSome special function registers are bit addressable. (This makes iteasier to program.)

The byte addresses are always multiples of 8, or they all lie in column0 of the SFR register block. The bit addresses are just appended ontothe byte address.

So the fouth bit of the accumulator is Acc.3 .byte address of the accumulator is 0E0h

so, the bit address is:

Acc.3 = 0E0h

+ 5

= 0E5h

Question: How does this explains the (incorrect) command CLR

B?

David Wilson17/48

Intel 8051 microcontroller9 Bit addressable SFRs /3

UNIVERSITY OF

KARLSTAD

10 8051 flags

Flags are stored in the PSW, so will be affected if you change it (ex-cept the parity flag).

Arithmetic flags:

� C, AC & OV, (Carry, auxiliary carry & overflow)

� Increment/decrement do not effect the math flags.

� I.e. no OV if we INC A from FFh to 00h .

� inc DPTR , note no DECversion.

Addition

C if carry out of bit #7

AC is set if carry from bit 3 to bit 4. (Used in BCD addition)

OV is set if carry out of bit 7 but not bit 6oris set if carry out of bit 6 but not bit 7.In other words:

OV = C7XORC6

Signed addition & subtraction is complicated, and you will need tostudy the flags carefully.

Use pre-tested subroutines for your arithmetic routines if possible.(See text books, or libraries on the internet.)

David Wilson18/48

Intel 8051 microcontroller10 8051 flags

UNIVERSITY OF

KARLSTAD

Page 10: 8051

11 Accessing external memory

Storage problems? What happens if our program is larger than4096 bytes of code?We have the ‘ROMless’ 8031 version, so we must

In assembler we use the movx (move external) to access the datablock, and movc to fetch from code memory.

We have two separate read signals, RD, (read) and PSEN , (pro-gram send enable). The bar means that it is active low, (when zero,will do something).

David Wilson19/48

Intel 8051 microcontroller11 Accessing external memory

UNIVERSITY OF

KARLSTAD

12 Prototyping 8051 design

Ayala, Chapter 9

For many small applications where we might want to change theROM code, we would like to use external EPROM, which means:

� We have lost the use of ports 0 and ports 2 since they must beused to interface with external ROM and not available for I/O.

� We may need external RAM (since the 128 bytes may not beenough for our application), which means that we have lostport 3.6, WR, and 3.7, RD.

� Any serial communication requires 3.0 (RXD) and 3.1 (TXD)

Loss of ports leaves us with:

1. All of port #1, and

2. Port P3.2 – P3.5

for general purpose I/O and external interrupts and timing inputs.

Question How do we recover the use of the lost ports?

David Wilson20/48

Intel 8051 microcontroller12 Prototyping 8051 design

UNIVERSITY OF

KARLSTAD

Page 11: 8051

Programmable Logic DevicesThe PROM chip is an example of a Programmable Logic DevicePLD. Once programmed, it will retain the program even when thepower is turned off.

� One-time programmable devices uses tiny fuses which areburnt or blown (or we can use antifuses which have the sameend function. Circuit size is 10� that for EPROMS.

� Eraseable Programmable read Only memory (EPROMS) can bere-programmed. This uses a modified MOS transistor with afloating gate that when uncharged does not effect the normaloperation. However if it is subjected to (high) +12V, then acharge will move into the 2nd transistor which is stable (willlast a decade).

Reprogram by subjecting the cells to UV light (via an expensiveceramic window on top of the package). Wiping time takesabout 20 minutes.

� EEPROM or Electrically erasable proms are about 2.5 timeslarger than eproms, and are quicker to clear.

� FLASH proms are much quicker to erase (hence the name), andcan be reprogrammed while still on the circuit board. Suitable foreasy upgrading by the public of ROM chips in Modems andPCs.

On the SBC51 board we have a 32k EPROM that is reprogrammedby UV light. This holds the monitor program. (We don’t have thesource to this, but we could reverse assemble it.)

David Wilson21/48

Intel 8051 microcontroller12 Programmable Logic Devices /2

UNIVERSITY OF

KARLSTAD

13 Reading to Ports

1. Store the address of the memory mapped port into the DPTR

register, and

2. indirectly address this through Acc.

; Reading & writing from a PORT

MOV DPTR, #0F012h; address to read digi-

tal input

MOVX A, @DPTR ; read the val-

ues into Acc

MOV DPTR, #0F011h; address of LED outputs

MOVX @DPTR, A ; write this value back out agai

The actual values of the address are decided by the designed of theparticular circuit board, (SBC in our case).

David Wilson22/48

Intel 8051 microcontroller13 Reading to Ports

UNIVERSITY OF

KARLSTAD

Page 12: 8051

14 Subroutines

Question Subroutine overheads slow a program down so why use them?

Subroutines do exist in assembler programming using the CALLop-code, but you must take care of the “housekeeping” yourself.

� All variables are global, so they may get altered or destroyed.This includes the PSW, register banks etc.

� You will need to save all variables before calling, and restorethem after returning from the subroutine.

� The stack is a special memory location (stack of registers) thatyou can use. (see OHs following)

� The processor uses the stack to remember the address where toreturn to after the subroutine has finished.

� The stack is pointed to by the stack pointer, SP.

� Near, Long (or far) and absolute calls are possible.

David Wilson23/48

Intel 8051 microcontroller14 Subroutines

UNIVERSITY OF

KARLSTAD

Ayala, p64, p129–130

Stack & the stack pointer makes housekeeping easier for certaintasks like storing & retrieving numbers quickly. The name comesfrom a ‘stack’ of dishes in a cafeteria or a stack of cigarettes at thesupermarket checkout.

To store data on the stack you PUSHit on.To retreive data, you POPit off

The Stack is a small amount of internal ram. The start of the stackis held in the stack pointer, SP. As you push data, the stack growsupwards (to higher locations) in ram memory.

The following occurs when you store some data on the stack & thenpop it off again.

David Wilson24/48

Intel 8051 microcontroller14 stack /2

UNIVERSITY OF

KARLSTAD

Page 13: 8051

Ayala, p130

Stack Note the cautions regarding usage!

� The stack is reset to 07h, but since this will overwrite the reg-ister banks, and bit area, we normally move it ‘out of harmsway’, to say 3Fh. (Done by the monitor program)

� If you push too many times, you will run off the end of internalRAM adress 07h which will result in errors.

� SP “rolls over” from FFh to 00.

� Use direct address, not register names R1, R2 etc since the stackhas no way of knowing which register bank is in use at thetime.

� Use PUSH Accnot PUSH A.

David Wilson25/48

Intel 8051 microcontroller14 Pushes & pops /3

UNIVERSITY OF

KARLSTAD

15 The stack & subroutine calls

Ayala, p177

What happens when a subroutine is called (including a hardware inter-rupt) ?

1. The PC is incremented and this becomes the return address,i.e. the spot the CPU will return to after it has completed thesubroutine.

2. The 16bit return address is pushed onto the stack, low bytefirst,

3. during which the stack pointer SP is incremented twice.

4. The subrouine address is placed in the PC and the subroutineis executed, until . . .

5. a RETreturn instruction is encounted, then

6. The CPU POPs the stack twice to recover the return address,and places it in the PC. (Sp is decremented twice)

7. CPU starts from the return address . . .

David Wilson26/48

Intel 8051 microcontroller15 The stack & subroutine calls

UNIVERSITY OF

KARLSTAD

Page 14: 8051

Question What is the maximum number of nested subroutine callswe can make?Question What are the advantages/disadvantages of long calls as

opposed to short calls?

David Wilson27/48

Intel 8051 microcontroller15 Subroutine review questions /2

UNIVERSITY OF

KARLSTAD

16 Interrupts

Interrupts are just special subroutines that may (or may not) becalled explicity.

Why have them?

1.

2.

3.

If conditions are “right”, when an interrupt occurs, then the proces-sor will stop what it is doing, and jump to a specific place in mem-ory (decided by the Intel 8051 designers) hooked that that particularinterrupt. (See following OH.)

It is up to the programmer to make sure that you supply a sensiblefurther course of action. This is called the interrupt handler routineor interrupt service routine, ISR.

Types of interruptsOn the 8051 we have 2 timers or counters and 2 external interrupts.

David Wilson28/48

Intel 8051 microcontroller16 Interrupts

UNIVERSITY OF

KARLSTAD

Page 15: 8051

Interrupt programming

� Signals or conditions generated external to the main program

– External events such as a change in a logic value

– Overflow of a counter

– Arrival of data at the serial port.

� Interrupts can be enabled or disabled by the programmer. (Al-though some interrupts are non-maskable.)

Interrupts on the 8051

� IE0 - external interrupt #0. Provided by an input pin on thechip.

� IE1 - external interrupt #1. Provided by an input pin on thechip.

� TF0, TF1 - Timer/Counter Interrupts. Generated by internaltimer/counters

� RI,TI Communication port interrupts. Indicates that a charac-ter has been received or the buffer is empty and a character cnabe transmitted.

Each interrupt forces the processor to jump to a different place inmemory.

David Wilson29/48

Intel 8051 microcontroller16 8051 interrupts /2

UNIVERSITY OF

KARLSTAD

Note that the computer does not explicitly call the ISR, this is de-termined by outside events, & we cannot predict exactly where &when it will call.

This splits out program into 2 parts, foreground & backgroundtasks.

Foreground tasks are under program control & are called explicitly

Background tasks are called via interrupts.

This makes the writing of complex real-time controller applicationsmuch easier.

Relocating the ISRs Normally ROM (or EPROM) occupies lowmemory, so the ISR is relocated to a higher address. (Otherwisewe would need to re-program the ROM everytime we wanted tochange the ISR in our prototype.)The Interrupt vector tableThe interrupt table has been moved (by the monitor program).

Name 8051 relocated on the SBC51INT 0 0003 single-step functionTIMER 0 000B 200BINT 1 0013 2013TIMER 1 001B 201Bserial port 0023 2023

Usage is by the LCALL op-code. However you must supply a RETI ,a return from interrupt op-code at the end of your interrupt handlersubroutine.

In our case we do a Long jump to +2000h.

David Wilson30/48

Intel 8051 microcontroller16 ISRs /3

UNIVERSITY OF

KARLSTAD

Page 16: 8051

17 Timers & counters

Timers (clocks) and counters are a good example for the advantagesof interrupts. Many applications require the counting of externalevents;

� Calculate the frequency of an external pulse train, or

� generate a precise delay between other computer actions (sayfor digital control)

Could use software techniques, but this keeps the processor occu-pied. Better to use interrupts & the two 16-bit count-up timers. Caneither be programmed to:

1. count internal : : :

2. count external : : :

All counter action is controlled by the TMOD(timer mode register)and the TCON(timer/counter control register).

David Wilson31/48

Intel 8051 microcontroller17 Timers & counters

UNIVERSITY OF

KARLSTAD

TCON Timer control SFR contains timer 1&2 overflow flags, exter-nal interrupt flags, timer control bits, falling edge/Low level selec-tor bit etc. (refer documentation)

TMOD timer mode SFR is two four-bit registers (timer #1, timer #0).Select timer/counter & various modes.)

Applications Say we want to count a specified number of events(clock pulses or external events), then

1. Store the start number in the counter. (Value = max count- de-sired count+1)

2. Counter automatically increments (in the background)

3. When it rolls over to zero, it will ste the timer flag.

4. Test the flag in the program, or generate an interrupt.

Timing configures the counter to count the internal clock fre-quency/12. (E.g. if fc = 6:0Mhz, then the timer clock will havea frequency of 500kHz.)Configure as a timer:

1. Clear C= �T bit in TMOD(Count internal frequency)

2. Set TRx in the TCON(timer run) and the gate bit in the TMOD

must be 0, or the external pin �INTx must be 1.

3. Select one of 4 modes.

David Wilson32/48

Intel 8051 microcontroller17 Counters /2

UNIVERSITY OF

KARLSTAD

Page 17: 8051

Ref: Ayala, pp205–212

Timing subroutinesIn microcontroller applications we need to wait a specified time,and so we need to have programmable time delays.

In all cases your application will be written for a specific clock fre-quency, say 12MHz, 16MHz, 11.0592 MHz etc.)

If you subsequently change the clock frequency, you will need toupdate your code, & possibly do some timing tests.

The timing options are:

1. Pure software time delays (wastefull)

2. Software polled timer (still wastefull, but OK in non-criticalapps)

3. Pure hardware using interrupts (accurate & preferred method)

Question We are mostly interested in the hardware timing version,why?

You should read carefully the Pure Hardware Delay code exampleon pp210–212 in Ayala.

David Wilson33/48

Intel 8051 microcontroller17 Timing subroutines /3

UNIVERSITY OF

KARLSTAD

Ref: Ayala, p210

Using a timer interrupt allows a timer to run and generate a timerinterrupt while the main program is running.

1. Setup the timer for a delay of 1000 �s. Enable the interrupts,and place the interrupt vector at 001Bh .

2.

3.

David Wilson34/48

Intel 8051 microcontroller17 Hardware timing /4

UNIVERSITY OF

KARLSTAD

Page 18: 8051

18 Computer communications

Phil Melore, http://www.plcs.net/comhistory29.htm

Computer communication systems have their roots in the old telegraph. Early attempts

to communicate electronically over long distances began as early as the late 1700’s. In

1810 a German man (von Soemmering) was using a device with 26 wires (1 for each letter

of the alphabet) attached to the bottom of an aquarium. When current passed through

the wires, electrolytic action produced small bubbles. By choosing the appropriate wires

to energize, he was able to send encoded messages “via bubbles”. This then caught the

attention of the military and the race to find a system was on.

In 1839, 2 Englishmen, Cooke andWheatstone, had a 13 mile telegraph inuse by a British railroad. Their devicehad 5 wires powering small electromag-nets which deflected low-mass needles.By applying current to different combi-nations of 2 wires at a time the needleswere deflected so that they pointed toletters of the alphabet arranged in a ma-trix. This “2 of 5” code only allowed20 combinations so the letters “z,v,u,q,jand c” were omitted (forget about a, a,and o). This telegraph was a big step forthe time, but the code was not binary(on/off) but rather it was trinary (theneedle moved left,right,or not at all).

The biggest problems with these devices was the fact that they were parallel (required

multiple wires) so it was S.F.B. Morse who created the fully serial binary system; Morse

code.

David Wilson35/48

Intel 8051 microcontroller18 Computer communications

UNIVERSITY OF

KARLSTAD

19 Interfacing

Usually means connecting your PC to periperals such as printers,plotters, modems, data acquisition hardware etc.

My portable PC

serialparallel????

????????

8-bit

| {z }

My PC LP1:

COM1:

1 bit + control

For interfacing we have two options

Parallel all 8 (or more) bits used together to send an entire byteat a time. (Requires about 20 pins practically) Speed is about150kbits/second for a maximum distance of 2–3 meters. (Nostandard, although CENTRONIX PARALLEL, or ECP, or EPP (ex-tended parallel port) are common. Writes one byte at a time,reads one nybble at a time.

Serial Send just one bit at a time. (Requires 5–8 pins practically.)Follows RS-232 standard and extensions. Typical speed is 9600bits/second (although faster versions are more common nowwith compression etc.)

Easy to program:Use the IN and OUTop-codes on the 8086 PC. or use the Port[]

command in Pascal.

David Wilson36/48

Intel 8051 microcontroller19 Interfacing

UNIVERSITY OF

KARLSTAD

Page 19: 8051

20 Serial communications: RS232

The serial RS232 standard is a serial asynchronous communicationsprotocol. (RS is for ‘recommended standard’)

Serial The infomation travels down a single line

Asynchronous means that it is not necessary to exactly synchronisethe clocks between the transmitter and receiver. Data is trans-mitted from 1 computer to another, not necessarily running atexactly at the same clock speed.

Standard An Electronics Industry Standard (EIS) #232. Defineshow the connectors should physically look, specifies voltagelevels, and defines what signals should do.

There are 2 types of RS-232 devices.

DTE Data Terminal Equipment and a common example is a com-puter. (Originally PCs used to be thought of as terminals to realcomputers such as IBM mainframes)

DCE Data Communications Equipment and a common example isa mainframe or modem. The 8051 may be either a DTE or DCEdevice.

and there are now two types of connectors:

1. The older 25 pin D-shell (DB–25)

2. The newer 9pin (DB–9), since most of the connections on the 25pin version were never used.

David Wilson37/48

Intel 8051 microcontroller20 Serial communications: RS232

UNIVERSITY OF

KARLSTAD

Serial port hardware comes in 2 flavors– a 25-pin type and a 9-pintype (shown below).

9-PIN 25-PIN PURPOSE1 1 frame ground (internally connected to the chassis)2 3 receive data (RD) (pin where the data from the external device enters)3 2 transmit data (TD) (pin where the data leaves)4 20 data terminal ready (DTR)5 7 signal ground6 6 data set ready (DSR)7 4 request to send (RTS)8 5 clear to send (CTS)9 22 ring indicator (RI) *only for modems*

Details of the pins follows:

DTS data terminal ready– This pin is a master control for the ex-ternal device. When this pin is 1 the external device will nottransmit or receive data.

DSR data set ready– Usually external devices have this pin as apermanent 0 and the plc basically uses it to determine that theexternal device is powered up and ready.

RTS request to send– This is part of hardware handshaking. Whenthe 8051 wants to send data to the external device it sets thispin to a 0. In other words, it sets the pin to a 0 and basicallysays “I want to send you data. Is it ok?” The external devicesays it’s OK to send data by setting its clear to send pin to 0.The 8051 then sends the data.

CTS clear to send- This is the other half of hardware handshaking.As noted above, the external device sets this pin to 0 when it isready to receive data from the 8051.

David Wilson38/48

Intel 8051 microcontroller20 RS232 /2

UNIVERSITY OF

KARLSTAD

Page 20: 8051

Ref: Sargent & Shoemaker, p655

The DB 9pin male conector as seen looking at the computer’s serialport. This is smaller & has less pins than the 25pin version, but stillcarries all the necessary infomation.

1

2

3

4

5

7

6

9

8

request to send (RTS)

Data set ready

clear to send (CTS)

Ring indicator (RI)

Data carrier detect (DCD)

Receive data (RxD)

Transmit Data (TxD)

Data terminal ready (DTR)

Signal ground

DB-9 male connector & pin assignments

DB–25 pin connections for RS232 lines.

RS232 signal Direction DTE DCESignal ground 1 1Transmit Data (TxD) Out 2 3Receive Data (RxD) In 3 2Request to Send (RTS) Out 4 5Clear to Send (CTS) In 5 4Data Terminal Ready (DTR) Out 20 6Data Set Ready (DSR) In 6 20Ring Indicator (RI) 22 22

David Wilson39/48

Intel 8051 microcontroller20 RS232 protocol /3

UNIVERSITY OF

KARLSTAD

Connecting two DCE devices (such as say two computers) will notwork very well, (since they are both DCEs, rather than one DCE andone DTE) so we must reverse two of the pins.

2 receive data

3 transmit data

2 receive data

DTE device DTE device

3 transmit data

2 receive data

3 transmit data

2 receive data

DTE device DTE device

3 transmit data

Null modem cable

Will not work !

computer #2computer #1

It is easy to swap over 2 of the lines of the cable to make a NullModem Cable.

David Wilson40/48

Intel 8051 microcontroller20 Serial RS232 protocol /4

UNIVERSITY OF

KARLSTAD

Page 21: 8051

Serial RS232 protocolSo to transmit the letter ‘A’, ASCII code (41h), we must send

‘A’ � 01000001

where:1 = high voltage, ( > +5V), but less than +15V0 = low voltage, ( < �5V ), but greater than �15V

So the serial transmission of ‘A’ is

Serial

1 0 0 0 0 0 01

�direction of time

z }| {‘A’

Without any transmission is kept at a high voltage.

David Wilson41/48

Intel 8051 microcontroller20 Serial RS232 protocol /5

UNIVERSITY OF

KARLSTAD

But this brings in a ambiguity regarding the start of the transmis-sion. (We could tune in half-way through.)

What happens if the transmission starts with a 1?

Start bit Add a zero to the front of each character transmitted. (Thisis obviously not part of the information content of the signal.) Sonow ‘A’ is sent as: 0 01000001| {z }

A

.

Noise in telephone lines is very common.

� Data can get corrupted by random signals

� Need a redundancy check. (Will not be fool proof, but reducesthe probability of a mistaken signal)

� This will further lengthen the code, and reduce the ‘informa-tion concentration’

Odd Parity. A cheap redundancy check. Count how many 1s wehave in our character, and if the number of ones is:

Even, then add a one to the codeOdd, then add a zero to the code

This ensures that each transmission segement (character) has an oddnumber of ones. Even parity is possible, and in this case all charac-ters have an even # of ones.

David Wilson42/48

Intel 8051 microcontroller20 Serial RS232 protocol /6

UNIVERSITY OF

KARLSTAD

Page 22: 8051

Using Odd parity, to transmit the character B

01000010| {z }

2ones

which has an even number of ones, we must append after the lastbit a single 1 to get:

parityz}|{1 01000010| {z }

B

Now to transmit C=

David Wilson43/48

Intel 8051 microcontroller20 Parity checks /7

UNIVERSITY OF

KARLSTAD

21 Interfacing with the outside world

For the computer to measure ‘real-world’ signals such as tempera-ture, pressure, humidity, and for it to write out voltages to controlthe speed on motors, brightness of lights etc, it must have both a

� D/A (Digital to analogue converter)

� A/D (Analogue to digital converter)

-voltage in

9=; 8 bit (1 byte) to computerA/D

-

8-bit Analogue to Digital conversion

--------

8<:8 bit binary value D/A - voltage out

8-bit Digital to Analogue conversion

-------

More expensive 12 & 16 bit converters are also possible.

David Wilson44/48

Intel 8051 microcontroller21 Interfacing with the outside world

UNIVERSITY OF

KARLSTAD

Page 23: 8051

D/A converters are easier to fabricate and cheaper than A/Ds. TheD/A takes a binary stream, and converts this to a single continuousvoltage.

D/A converter

R2R4R8R

b0 b1 b2 b3

�Vref

Vout

R0

�+

The D/A converter outputs a voltage, Vout given a binary number

b3b2b1b0, where each of the bs can be either 1 or 0,

Vout =R0

R

b3 +

b22

+

b14

+

b08

!Vref

As we increase the # of bits, the range of matched resistors becomeslarge, and the accuracy becomes poor.

David Wilson45/48

Intel 8051 microcontroller21 D/A converters /2

UNIVERSITY OF

KARLSTAD

Ref: Ogata, DCE, p32

An alternative scheme for a D/A converter that uses resistors ofonly size R and 2R is a ladder scheme.

Ladder D/A converter

2RRR

2R2R

b1 b2 b3

�Vref

R2R

2R2R

b0

Vout

3R

�+

In this scheme, all the resistors (except for the feedback resistor)are either R or 2R which means a high level of accuracy can beachieved.

A/D converters are more complicated and use internally a D/Aconverter coupled with a successive approximation register (SAR).Details given in electronic handbooks.

David Wilson46/48

Intel 8051 microcontroller21 D/A ladder scheme /3

UNIVERSITY OF

KARLSTAD

Page 24: 8051

22 8052: Extending the 8051 family

The 8051 is just the first member of a series of micro-controllers. Themost common “big brother” is the 8052.

� adds another 128 bytes of internal RAM (indirectly addressable)

� increases the onboard ROM from 4K to 8K.

� Adds another timer, T2, (to make three; T0,T1 and T2), andassociated new SFRs.

� T2 is a capture timer.

� No new op-codes, but does have new SFRs

Since the INTEL designers of the original 8051 left ample room inthe SFR space for future functions, Philips Semiconductor designerscan add another timer with special functions, without adding new op-codes.SFR AddressT2H 0xCD

T2L 0xCC

RCAP2H 0xCB

RCAP2L 0xCA

T2CON 0xC8

You should consult the relevant manufacturer’s documentation forthese extra functions, (such as Phillips Semiconductor).

David Wilson47/48

Intel 8051 microcontroller22 8052: Extending the 8051 family

UNIVERSITY OF

KARLSTAD

23 8051 conclusions

David Wilson48/48

Intel 8051 microcontroller23 8051 conclusions

UNIVERSITY OF

KARLSTAD