You are on page 1of 56

INTERNATIONAL ISLAMIC UNIVERSITY

FACULTY OF ENGINEERING & TECHNOLOGY


DEPARTMRNT OF ELECTRONIC ENGINEERING

THE 8051
MICROCONTROLLER
INTERFACING
LABORATORY MANUAL
First Edition

ENGR. RASHID FARID CHISHTI


INTERNATIONAL ISLAMIC UNIVERSITY ISLAMABAD
http://www.iiu.edu.pk
LIST OF EXPERIMENTS

LAB01: LEDS INTERFACING AND PROGRAMMING ................................................................ 1


LAB02: 7-SEGMENT INTERFACING AND PROGRAMMING ................................................... 7
LAB03: LCD INTERFACING AND PROGRAMMING ................................................................ 11
LAB04: TIMER MODE PROGRAMMING .................................................................................... 19
LAB05: COUNTER MODE PROGRAMMING .............................................................................. 22
LAB06: INTERRUPTS PROGRAMMING ON PC ........................................................................ 23
LAB07: PC TO PC SERIAL COMMUNICATION......................................................................... 26
LAB08: SERIAL COMMUNICATION BETWEEN COMPUTER & 8051 MC .......................... 35
LAB09: PARALLEL PORT PROGRAMMING IN PC .................................................................. 43
LAB10: ADC INTERFACING AND PROGRAMMING................................................................ 45
LAB11: CONTROLLING A STEPPER MOTOR ........................................................................... 50
Microcontroller Interfacing Lab LAB01: LEDs Interfacing and Programming

LAB01: LEDs Interfacing and Programming


Objective:

1. Make basic circuitry to run a microcontroller


2. Interfacing LEDs with 89C51 microcontroller
3. Microcontroller programming in C
4. Writing hex code to the microcontroller.
5. Running a simple program to blink set of LEDs

Hardware List:

S.No. Type Symbol Rating Quantity


01 Resistor R1 512 watt 01
02 Resistor R2 10 K watt 01
03 LED L1~L8 8 Green LEDs 08
04 Capacitor C1 10 f 01
05 Crystal CR1 11 MHz 01
06 Capacitor C2, C3 33 pf 02
07 Breadboard 1 01
08 Power Supply 5V 01
Basic Circuit Diagram:

Faculty of Engineering & Technology, International Islamic University Islamabad Page 1


Microcontroller Interfacing Lab LAB01: LEDs Interfacing and Programming

Pin Functions
18 Port 1. The bi-directional pins on this
port may be used for input and output:
each pin may be individually controlled
and for example some may be used
for input while others on the same port
are used for output.
9 The Reset pin. When this pin is held
at Logic 0, the chip will run normally.
If, while the oscillator is running, this
pin is held at Logic 1 for two (or more)
machine cycles, the microcontroller will
be reset.
1017 Port 3. Another bi-directional input port
(same operation as Port 1). Each pin on
this port also serves an additional
function. Pin 10 and Pin 11 are used to
receive and transmit (respectively)
serial data using the RS-232 protocol.
Pin 12 and Pin 13 are used to process
interrupt inputs. Pin 14 and Pin 15 have
alternative functions associated with
Timer 0 and Timer 1. Pin 16 and Pin 17
are used when working with external
memory
1819 These pins are used to connect an
external crystal, ceramic resonator or
oscillator module to the
microcontroller.
20 Vss. This is the ground pin.
2128 Port 2. Another bi-directional input port (same operation as Port 1). These pins are also used when
working with external memory
29 Program Store Enable (PSEN) is used to control access to external CODE memory (if used).
30 Address Latch Enable (ALE) is used when working with external memory. Note that some devices
allow ALE activity to be disabled (if external memory is not used): this can help reduce the level of
electromagnetic interference (EMI) generated by your product. This pin is also used (on some devices)
as the program pulse input (PROG) during Flash programming.
31 External Access (EA). To execute code from internal memory (e.g. on-chip Flash, where available)
this pin must be connected to Vcc. To execute code from external memory, this pin must be connected
to ground. Forgetting to connect this pin to Vcc is a common error when people first begin
working with the 8051.
3239 Port 0. Another bi-directional input port (same operation as Port 1). Note that unlike Port 1, Port 2
and Port 3 this port does NOT have internal pull-up resistors. These pins are also used when working
with external memory
40 Vcc. This is the 5V pin (on 5V devices; 3V on 3V devices, etc).

Faculty of Engineering & Technology, International Islamic University Islamabad Page 2


Microcontroller Interfacing Lab LAB01: LEDs Interfacing and Programming

Power Supply Schematic:

Implementation on Breadboard:

C Programming Code:

Write down the following code in a notepad and save it as lab01.C

#include <c:\c51\inc\AT89C51.H>
void wait (void){ /* wait function */
unsigned int x;
for(x=0;x<10000;x++); /* one second delay for LEDs */
}
void main (void)
{
unsigned int i; /* Delay variable */
unsigned char j; /* LED variable */

while (1) /* Loop forever */


{
for (j=0x01; j< 0x80; j<<=1)
{ /* Blink LEDs 0, 1, 2, 3, 4, 5, 6 */
P1 = j; /* send Output to Port 1 */
P0 = j; /* Output to LED Port */
wait (); /* call wait function */

Faculty of Engineering & Technology, International Islamic University Islamabad Page 3


Microcontroller Interfacing Lab LAB01: LEDs Interfacing and Programming

for (j=0x80; j> 0x01; j>>=1)


{ /* Blink LED 6, 5, 4, 3, 2, 1 */
P1 = j; /* Output to LED Port */
P0 = j; /* Output to LED Port */
wait (); /* call wait function */

}
}
}

Circuit Diagram for Interfacing Eight LEDs:

Faculty of Engineering & Technology, International Islamic University Islamabad Page 4


Microcontroller Interfacing Lab LAB01: LEDs Interfacing and Programming

Keil C51 Compiler Command Summery:


----------------------------------------------------------------------------------------
Generating Hex File
----------------------------------------------------------------------------------------
Step 1) Compile Command c51 lab01.c
Step 2) Link Command l51 lab01.obj
Step 3) Hex File Command ohs51 lab01

----------------------------------------------------------------------------------------
Invoking DScope
----------------------------------------------------------------------------------------

Compile Command c51 lab01.c db oe // debug object executed

Link Command l51 lab01.obj

DScope Command ds51 lab01

----------------------------------------------------------------------------------------
Using DScope
----------------------------------------------------------------------------------------
Decrease Command Window Size Alt+D
Increase Command Window Size Alt+U
Reset Command reset
Go To Main Function g,main
Execute One Instruction Alt+t
Watch Set Instruction ws variablename
Watch Kill Instruction wk watchnumber
Serial Data In Instruction sin = hexdata

Exercise:

Change the above code So that the LEDs should blink like a progress bar e.g

Faculty of Engineering & Technology, International Islamic University Islamabad Page 5


Microcontroller Interfacing Lab LAB01: LEDs Interfacing and Programming

Answer:

Faculty of Engineering & Technology, International Islamic University Islamabad Page 6


Microcontroller Interfacing Lab LAB02: 7-Segment Interfacing and Programming

LAB02: 7-Segment Interfacing and Programming

Objective:

6. Interface Seven Segment Display with microcontroller


7. Program a driver, that can show numbers from 0 to 9 on Seven Segment Display

Circuit Diagram:

Faculty of Engineering & Technology, International Islamic University Islamabad Page 7


Microcontroller Interfacing Lab LAB02: 7-Segment Interfacing and Programming

Hardware List:

S.No. Type Symbol Rating Quantity


01 Resistor R1 512 watt 01
02 Resistor R2 10 K watt 01
03 7-Segment 01
04 Capacitor C1 10 f 01
05 Crystal CR1 11.0592 MHz 01
06 Capacitor C2, C3 22 or 33 pf 02
07 Breadboard 01
08 Power Supply +5V 01

C Programming Code:

Write down the following code in a notepad and save it as lab02.C

sfr P0 = 0x80;
sbit a=P0^0; sbit b=P0^1; sbit c=P0^2;
sbit d=P0^3; sbit e=P0^4; sbit f=P0^5;
sbit g=P0^6; sbit dot=P0^7;

void delay(int sec)


{
int i,j;
for ( i = 0 ; i<sec ; i++)
{
for ( j = 0 ; j<1000 ; j++) {
;
}
}
}

void number(int n)
{
switch(n)
{
case 0:
dot=0; g=0; f=1; e=1; d=1; c=1; b=1; a=1; break;
// OR you can also use P0=0x3F;
case 1:
dot=0; g=0; f=0; e=0; d=0; c=1; b=1; a=0; break; // P0 = 0x06;
case 2:
dot=0; g=1; f=0; e=1; d=1; c=0; b=1; a=1; break; // P0 = 0x5B;
case 3:
dot=0; g=1; f=0; e=0; d=1; c=1; b=1; a=1; break; // P0 = 0x4B;
case 4:
dot=0; g=1; f=1; e=0; d=0; c=1; b=1; a=0; break; // P0 = 0x66;
case 5:
dot=0; g=1; f=1; e=0; d=1; c=1; b=0; a=1; break; // P0 = 0x6D;
case 6:
dot=0; g=1; f=1; e=1; d=1; c=1; b=0; a=1; break; // P0 = 0x7D;
case 7:
dot=0; g=0; f=0; e=0; d=0; c=1; b=1; a=1; break; // P0 = 0x07;
case 8:
dot=0; g=1; f=1; e=1; d=1; c=1; b=1; a=1; break; // P0 = 0x7F;

Faculty of Engineering & Technology, International Islamic University Islamabad Page 8


Microcontroller Interfacing Lab LAB02: 7-Segment Interfacing and Programming

case 9:
dot=0; g=1; f=1; e=0; d=0; c=1; b=1; a=1; break; // P0 = 0x67;
}

}
void main()
{
int i=0;
while(1){
number(i);
delay(50);
i++;
if(i>=10)
i=0;
}
}

Exercise:

Change the above code to Show remaining hexadecimal values on Seven Segment like

Answer:

Faculty of Engineering & Technology, International Islamic University Islamabad Page 9


Microcontroller Interfacing Lab LAB02: 7-Segment Interfacing and Programming

Faculty of Engineering & Technology, International Islamic University Islamabad Page 10


Microcontroller Interfacing Lab Lab03: LCD Interfacing and Programming

Lab03: LCD Interfacing and Programming


Objective:

1. Interface Liquid Crystal Display with microcontroller


2. Write a program to show some text messages on LCD

Hardware List:

S.No. Type Symbol Rating Quantity


01 Resistor R1 512 watt 01
02 Resistor R2 10 K watt 01
03 LCD 16 x 2 Characters 01
04 Capacitor C1 10 f 01
05 Crystal CR1 11 MHz 01
06 Capacitor C2, C3 33 pf 02
07 Breadboard 01
08 Power Supply +5V 01

Circuit Diagram:

Faculty of Engineering & Technology, International Islamic University Islamabad Page 11


Microcontroller Interfacing Lab Lab03: LCD Interfacing and Programming

Pin Assignment:

TABLE-1 Hitachi 44780 Based LCD Pin out


PIN SYMBOL I/O DESCRIPTION
1 Vss - Power supply (GND)
2 Vcc - Power supply (+5V)
3 Vdd - Contrast Settings (0~2V)
4 RS I 0 = Select command reg.
1 = Select data reg. of LCD
5 R/W I 0 = Write to LCD
1 = Read from LCD
6 E I The Enable (E) line allows access to the display through R/W and RS lines.
0 = Access to LCD disabled, 1 = Access to LCD enabled
7 DB0 I/O Data bit line 0 (LSB)
8 DB1 I/O Data bit line 1
9 DB2 I/O Data bit line 2
10 DB3 I/O Data bit line 3
11 DB4 I/O Data bit line 4
12 DB5 I/O Data bit line 5
13 DB6 I/O Data bit line 6
14 DB7 I/O Data bit line 7 (MSB)

Instruction Set:

Table-2 HD44780 instruction set


Instruc- Code Exec-
RS R/ DB DB DB DB DB DB DB DB Description ution
tion W 7 6 5 4 3 2 1 0 time**
Clear 0 0 0 0 0 0 0 0 0 1 Clears display and returns cursor 1.64
display to the home position (address 0). mS
Cursor 0 0 0 0 0 0 0 0 1 * Returns cursor to home position
home (address 0). Also returns display
1.64
being shifted to the original
mS
position. DDRAM contents
remain unchanged.
Entry 0 0 0 0 0 0 0 1 I/D S Sets cursor move direction (I/D),
mode set ID=1/0:right(incr)/left(decr), also specifies to shift the display
S=1/0:without/with text (S) or not. These operations are 40uS
performed during data read/write.

Display 0 0 0 0 0 0 1 D C B Sets On/Off of all display (D),


On/Off D,C,B=1/0:Display,Cursor,Blink cursor On/Off (C) and blink of 40uS
control on/off cursor position character (B).
Cursor/di 0 0 0 0 0 1 S/ R/ * * Sets cursor-move or display-shift
splay C L (S/C), shift direction (R/L).
40uS
shift SC=1/0:text/Cursor to DDRAM contents remain
RL=1/0:right/left) unchanged.
Function 0 0 0 0 1 DL N F * * Sets interface data length (DL),
40uS
set DL=1/0:8/4-bit bus, N=1/0:both number of display line (N) and

Faculty of Engineering & Technology, International Islamic University Islamabad Page 12


Microcontroller Interfacing Lab Lab03: LCD Interfacing and Programming

lines/one line character font(F).


Set 0 0 0 1 Character Generator RAM Sets the CGRAM address.
CGRAM address CGRAM data is sent and 40uS
address received after this setting.
Set 0 0 1 Display Data RAM address Sets the DDRAM address.
DDRAM DDRAM data is sent and 40uS
address received after this setting.
Read 0 1 BF CGRAM / DDRAM address Reads Busy-flag (BF) indicating
busy-flag BF=1/0:busy/not busy internal operation is being
and performed and reads CGRAM or
0uS
address DDRAM address counter
counter contents (depending on previous
instruction).
Write to 1 0 Character Byte Writes a character to last (CG or
CGRAM DD) RAM address chosen.
40uS
or
DDRAM
Read 1 1 Character Byte Read data from last (CG or DD)
from RAM address chosen.
CGRAM 40uS
or
DDRAM
Remarks:
- DDRAM = Display Data RAM. CGRAM = Character Generator RAM.
- DDRAM address corresponds to cursor position. * = Don't care.
- ** = Based on Fosc = 250kHz.

TABLE-4 Hitachi 44780 Based LCD Types Character Locations


LCD Character Positions DDRAM Address
16x2 00 01 02 03 04 05 06 07 80 81 82 83 84 85 86 87
08 09 10 11 12 13 14 15 88 89 8A 8B 8C 8D 8E 8F
00 01 02 03 04 05 06 07 C0 C1 C2 C3 C4 C5 C6 C7
08 09 10 11 12 13 14 15 C8 C9 CA CB CC CD CE CF
20x1 00 to 19 80 to 93
20X2 00 to 19 80 to 93
00 to 19 C0 to D3
20X4 00 to 19 80 to 93
00 to 19 C0 to D3
00 to 19 94 to A7
00 to 19 D4 to E7
40X2 00 to 39 80 to A7
00 to 39 C0 to E7

Faculty of Engineering & Technology, International Islamic University Islamabad Page 13


Microcontroller Interfacing Lab Lab03: LCD Interfacing and Programming

Interfacing:

8-bit Interface (Example of busy flag testing using an 8-bit interface.)

Writing data to the LCD is done in several steps:

Step 1: Set R/W bit to low


Step 2: Set RS bit to logic 0 or 1 (instruction or character)
Step 3: Set data to data lines (if it is writing)
Step 4: Set E line to high
Step 5: Set E line to low
Step 6: Read data from data lines (if it is reading)

Example of data transfer using a 4-bit interface.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 14


Microcontroller Interfacing Lab Lab03: LCD Interfacing and Programming

Character Set:

Characters that can be shown on the display are stored in data


display (DD) RAM. The size of DDRAM is 80 bytes.
The LCD display also possesses 64 bytes of Character-
Generator (CG) RAM. This memory is used for characters
defined by the user. Data in CG RAM is represented as an 8-
bit character bit-map.
Each character takes up 8 bytes of CG RAM, so the total
number of characters, which the user can define, is eight. In
order to read in the character bit-map to the LCD display, we
must first set the CG RAM address to starting point (usually
0), and then write data to the display. The definition of a
'special' character is given in the picture.
Before we access DD RAM after defining a special
character, the program must set the DD RAM address. Writing
and reading data from any LCD memory is done from the last
address which was set up using set-address instruction. Once
the address of DD RAM is set, a new written character will be
displayed at the appropriate place on the screen.
Until now we discussed the operation of writing and
reading to an LCD as if it were an ordinary memory. But this is
not so. The LCD controller needs 40 to 120 microseconds (uS)
for writing and reading. Other operations can take up to 5 mS.
During that time, the microcontroller can not access the LCD,
so a program needs to know when the LCD is busy. We can
solve this in two ways.

One way is to check the BUSY bit found on data line D7. This
is not the best method because LCD's can get stuck, and program will then stay forever in a loop
checking the BUSY bit. The other way is to introduce a delay in the program. The delay has to be long
enough for the LCD to finish the operation in process. Instructions for writing to and reading from an
LCD memory are shown in the previous table.

At the beginning we mentioned that we needed 11 I/O lines to communicate with an LCD. However, we
can communicate with an LCD through a 4-bit data bus. Thus we can reduce the total number of
communication lines to seven. The wiring for connection via a 4-bit data bus is shown in the diagram

Faculty of Engineering & Technology, International Islamic University Islamabad Page 15


Microcontroller Interfacing Lab Lab03: LCD Interfacing and Programming

below. In this example we use an LCD display with 2x16 characters. The message 'Microcon' is written in
the first row: and In the second row we have produced the word 'www.iiu.edu.pk'.

C Programming Code:

Write down the following code in a notepad and save it as lab03.C

#include<C:\c51\inc\REG51F.h>

sbit RS=P1^0;
sbit RW=P1^1;
sbit E=P1^2;
sbit BF=P0^7;
sfr DATA_BUS = 0x80; //Port 0
char data1;

int ready() //For checking that the LCD is ready or not?


{
BF=1;
RS=0;
RW=1;
while(BF==1)
{
E=0;
E=1;
}

return 1;
} //Ready Function Ends

void delay(unsigned int z) //For delay (Starts)


{
int x,y;
for(x=0;x<z;x++){
for(y=0;y<=1000;y++){
y=y+0;
}
}
} //Delay Function Ends

static void LCD_Pulse_E(int t) {

unsigned char i;
E = 1; for(i=0; i<t; i++) i = i;
E = 0; for(i=0; i<t; i++) i = i;
}
int LCD_Run_Command(unsigned char COMMAND){
if(ready()){
DATA_BUS=COMMAND;
RS=0; delay(1);
RW=0; delay(1);
LCD_Pulse_E(255);
}
return 1;
}
int LCD_Show(unsigned char CHARACTER){
if(ready()){
DATA_BUS=CHARACTER;

Faculty of Engineering & Technology, International Islamic University Islamabad Page 16


Microcontroller Interfacing Lab Lab03: LCD Interfacing and Programming

RS=1; delay(1);
RW=0; delay(1);
LCD_Pulse_E(255);
delay(1);
}
return 1;
}
int LCD_Initialize(){
LCD_Run_Command(0x38); // 8 data lines, two lines, Font 5x7.
LCD_Run_Command(0x0E); // Display=ON, Curson=ON, Cursor Blonking=ON
LCD_Run_Command(0x01); // Clear display and return cursor to the home position
LCD_Run_Command(0x06); // During read/write operation only cursor (not text)
// should move right.
LCD_Run_Command(0x80); // Cursor at Line 1, Position 0
return 1;
}

void main()
{

for(;;)
{
delay(50);
LCD_Initialize();
for(data1='A' ; data1 <'T' ; data1++){
LCD_Show(data1);
}
LCD_Run_Command(0xC0); // Cursor at Line 2, Position 0

for(data1='T' ; data1 <'Z' ; data1++){


LCD_Show(data1);

}
delay(50);
}
}

Exercise:

Show the following messages repeatedly on LCD


1ST screen 2ND SCREEN 3RD SCREEN 4TH SCREEN 5TH SCREEN
Count Down Count Down Count Down Count Down Y O U R
3 2 1 0 N A M E

Faculty of Engineering & Technology, International Islamic University Islamabad Page 17


Microcontroller Interfacing Lab Lab03: LCD Interfacing and Programming

Faculty of Engineering & Technology, International Islamic University Islamabad Page 18


Microcontroller Interfacing Lab Lab04: Timer Mode Programming

Lab04: Timer Mode Programming

Objective:

Timer Mode Programming

Registers Functionality:

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

TMOD (89h) SFR


Bit Name Explanation of Function Timer

7 GATE1 When this bit is set the timer will only run when INT1 (P3.3) is high. When this 1
bit is clear the timer will run regardless of the state
of INT1.
6 C/T1 When this bit is set the timer will count events on T1 (P3.5). When this bit is 1
clear the timer will be incremented every machine cycle.
5 T1M1 Timer mode bit (see table below) 1
4 T1M0 Timer mode bit (see table below) 1
3 GATE0 When this bit is set the timer will only run when INT0 (P3.2) is high. When this 0
bit is clear the timer will run regardless of the state of INT0.
2 C/T0 When this bit is set the timer will count events on T0 (P3.4). When this bit is 0
clear the timer will be incremented every machine cycle.
1 T0M1 Timer mode bit (see table below) 0
0 T0M0 Timer mode bit (see table below) 0

As you can see in the above chart, four bits (two for each timer) are used to specify a mode of operation. The
modes of operation are:
TxM1 TxM0 Timer Mode Description of Mode
0 0 0 13-bit Timer.
0 1 1 16-bit Timer
1 0 2 8-bit auto-reload
1 1 3 Split timer mode

The TCON SFR: The TCON is a bit addressable special function register controls the two timers and provides
valuable information about them. The TCON SFR has the following structure:
TCON (88h) SFR
Bit Name Bit Explanation of Function Timer
Address
7 TF1 8Fh Timer 1 Overflow. This bit is set by the microcontroller when 1
Timer 1 overflows (timer rolls from all ones to zero).
6 TR1 8Eh Timer 1 Run. When this bit is set to 1 by program, Timer 1 is 1

Faculty of Engineering & Technology, International Islamic University Islamabad Page 19


Microcontroller Interfacing Lab Lab04: Timer Mode Programming

turned on. When this bit is set to 0, Timer 1 is off.


5 TF0 8Dh Timer 0 Overflow. This bit is set by the microcontroller when 0
Timer 0 overflows.
4 TR0 8Ch Timer 0 Run. When this bit is set Timer 0 is turned on. When this 0
bit is clear Timer 0 is off.
3 IE1 8Bh External Interrupt 1. This bit is set to 1 by the microcontroller
when a high to low signal is received on INT1 (P3.3). Cleared when
processor vectors to interrupt service routine located at program
address 0013h.
2 IT1 8Ah External Interrupt 1 Signal Type: When this bit is set to 1 by the
program, the external interrupt will be triggered by a falling edge
signal. When this bit is set to 0, a LOW level signal on INT1 (P3.3)
will generate an interrupt.
1 IE0 89h External Interrupt 0. This bit is set to 1 by the microcontroller
when a high to low signal is received on INT0 (P3.2). Cleared when
processor vectors to interrupt service routine located at program
address 0003h.
0 IT0 88h External Interrupt 0 Signal Type: When this bit is set to 1 by the
program, the external interrupt will be triggered by a falling edge
signal. When this bit is set to 0, a LOW level signal on INT0 (P3.2)
will generate an interrupt.

Please Note: the lower 4 bits (bit0 to bit3) of the TCON register dont have anything to do with timers. These
are related to Interrupts.

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

Your program may enable and disable interrupts by modifying the IE SFR (A8h):
Bit Name Bit Address Explanation of Function
7 EA AFh Global Interrupt Enable/Disable
6 - AEh Undefined
5 - ADh Undefined
4 ES ACh Enable Serial Interrupt
3 ET1 ABh Enable Timer 1 Interrupt
2 EX1 AAh Enable External 1 Interrupt
1 ET0 A9h Enable Timer 0 Interrupt
0 EX0 A8h Enable External 0 Interrupt

As you can see, each of the 8051s interrupts has its own bit in the IE SFR. You enable a given
interrupt by setting the corresponding bit.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 20


Microcontroller Interfacing Lab Lab04: Timer Mode Programming

C Programming Code:

Write down the following code in a notepad and save it as lab04.C

// The following program geterates a clock of frequency about 2 KHz at its port P1^7
// Please read Ali Mazidis book for reference

#include <c:\c51\inc\reg51f.h>

sbit SPEAKER = P1^7;

void main(void)
{

TMOD = 0x10; /* Timer 1, mode 1 (16 BIT )counter */


/* GATE1=0; C/T1 =0; M10=0; M00=1; */
/* TMOD.7 = GATE1 = When this bit is set the timer will only run
when INT1 (P3.3) is high. When this bit is
clear the timer will run regardless of the state of INT1.

TMOD.6 C/T1 = When this bit is set the timer will count events
on T1 (P3.5). When this bit is clear the timer
will be incremented every machine cycle.
*/
while(1){
TL1 = 0x1A; /* initial values */
// TL1 = 0x00; /* initial values */

TH1 = 0xFF;
TR1 = 1; // Start Timer 1
// ET1 = 1; // Enable Timer 1 overflow interrupt
while(!TF1){
;
}

TR1 = 0; // Stop Timer 1;


SPEAKER = ~SPEAKER; // Complement Speaker Pin
TF1 = 0; // TF1 = Timer 1 Overflow. This bit is set by the
// microcontroller when Timer 1 overflows.
}
}

Faculty of Engineering & Technology, International Islamic University Islamabad Page 21


Microcontroller Interfacing Lab Lab05: Counter Mode Programming

Lab05: Counter Mode Programming


Objective:

Programming Timer in Counter Mode

C Programming Code:

Write down the following code in a notepad and save it as lab05.C

// The following program counts the events at port P3^5, whenever this pin is connacted
to ground, an event occures and the total no of events are shown on port P0.
// Please read Ali Mazidis book for reference

#include <c:\c51\inc\reg51f.h>

void main(void)
{

TMOD = 0x50; /* Timer 1, mode 1 (16 BIT )counter */


/* GATE1=0; C/T1 =1; M10=0; M00=1; */
/* TMOD.7 = GATE1 = When this bit is set the timer will only run
when INT1 (P3.3) is high. When this bit is
clear the timer will run regardless of the state of INT1.

TMOD.6 C/T1 = When this bit is set the timer will count events
on T1 (P3.5). When this bit is clear the timer
will be incremented every machine cycle.
So An Event Occures when we connect P3.5 to ground
*/
// P3^5=1;

TL1 = 0x00; /* initial values */


TH1 = 0x00;

while(1){
TR1 = 1; // Start Timer 1;
while(!TF1){
P0=TL1; // 0XDF = 1101 1111

TR1 = 0; // Stop Timer 1;


TF1 = 0; // TF1 = Timer 1 Overflow. This bit is set by the
// microcontroller when Timer 1 overflows.
}
}

Faculty of Engineering & Technology, International Islamic University Islamabad Page 22


Microprocessor Interfacing Lab Lab06: Interrupts Programming on PC

Lab06: Interrupts Programming on PC


BIOS Interrupt Vector Table

The various functions the BIOS carries out are termed interrupt service routines (ISR). The design of the
PC BIOS allows the system to put these interrupt handlers (ISR) at any convenient address. So that a calling
program can find the proper routine.

The BIOS reserves part of your PCs memory for a map called a BIOS interrupt vector table. This map
consists of a long list of 32-bit addresses with one address corresponding to each interrupt handler. These
addresses point to the first byte of the program code for carrying out the interrupt and are called interrupt
vectors. The microprocessor reads the value of the vector, and starts executing the code located at the value
stored in the vector.

The table of interrupt vectors begins at the very start of the microprocessor's memory, address 00000(Hex).
Each vector comprises four bytes and all vectors are stored in increasing order. Table given below
summarizes list of selected BIOS interrupt vectors and the associated functions

Absolute address (hex) Interrupt value Function Hardware interrupt


0000:0000 00H Divide by Zero Interrupt Header
0000:0004 01H Single Step Interrupt Handler
0000:0014 05H Print Screen
0000:002C 0BH Serial Port 2 IRQ3
0000:0030 0CH Serial Port 1 IRQ4
0000:0034 0DH Hard Disk IRQ5
0000:0038 0EH Floppy disk IRQ6
0000:003C 0FH Parallel Port IRQ7
0000:0040 10H Video Services
0000:0044 11H Equipment Check
0000:0048 12H Memory Size Check
0000:004C 13H Floppy and Hard Disk I/O
0000:0050 14H RS-232 Service
0000:0054 15H System Services
0000:0058 16H Keyboard
0000:005C 17H Printer I/O
0000:0060 18H Basic ROM Entry point (startup)
0000:0064 19H Initial Program Load (IPL)
0000:0084 21H DOS Function Calls
0000:0068 1AH Time of Day
0000:01C0 70H Real Time Clock IRQ8
0000:01C4 71H LAN Adapter (IRQ2 replacement) IRQ9
0000:01C8 72H Reserved IRQ10
0000:01CC 73H Reserved IRQ11
0000:01D0 74H Mouse IRQ12
0000:01D4 75H 80287 NMI Error IRQ13
0000:01D8 76H Hard disk controller IRQ14

Faculty of Engineering & Technology, International Islamic University Islamabad Page 23


Microprocessor Interfacing Lab Lab06: Interrupts Programming on PC

0000:01DC 77H Reserved IRQ15


0000:01E0 78H-7FH Unused
0000:0200 80H-85H BASIC
0000:0218 86H NetBIOS
0000:021C 87H-F0H BASIC
0000:03C4 F1H-FFH Reserved for Program Interrupts

Calling 8068 Software Interrupts

#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <conio.h>

#define VIDEO 0x10

void movetoxy(int x, int y)


{
union REGS regs;

regs.h.ah = 2; /* set cursor position */


regs.h.dh = y;
regs.h.dl = x;
regs.h.bh = 0; /* video page 0 */
int86(VIDEO, &regs, &regs);
}

int main(void)
{
clrscr();
movetoxy(35, 10);
printf("Hello\n");
getch();
return 0;
}

Here is another way of Calling Software Interrupts

#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <conio.h>

void movetoxy(int x, int y)


{
_AH = 2; /* set cursor position */
_DH = y; _DL = x;
_BH = 0; /* video page 0 */
geninterrupt(0x10); /* Move Cursor to that position */
}
int main(void)
{
clrscr();
movetoxy(35, 10);
printf("Hello\n");
getch();
return 0;

Faculty of Engineering & Technology, International Islamic University Islamabad Page 24


Microprocessor Interfacing Lab Lab06: Interrupts Programming on PC

Faculty of Engineering & Technology, International Islamic University Islamabad Page 25


Microprocessor Interfacing Lab Lab07: PC to PC Serial Communication

Lab07: PC to PC Serial Communication


Introduction
In PC serial port is used for sending or receiving data serially to/from another
device/PC. For this purpose serial port uses a device called UART (Universal
Asynchronous Receiver Transmitter). UART is used for asynchronous communications. UART
encapsulates data (7 or 8 bits) in start and stop bits. We can also use extra parity
bit with the data for error detection. The width of stop bits may also vary

Figure 1: A serial data frame with eight data bits and one stop bit.

In most of our PCs, BIOS supports 4 UARTS as COM Ports COM1, COM2, COM3, COM4. The following
table shows the address at which we can find the Communications (COM) Ports Addresses in the BIOS
Data Area. Each address will take up 2 bytes.

The Following Table Summarizes the Standard Port Addresses and this information is correct for most of
PCs

Port Memory Port Hardware


Name Address Base Interrupt
COM1 0040:0000 03F8H IRQ4
COM2 0040:0002 02F8H IRQ3
COM3 0040:0004 03E8H IRQ4
COM4 0040:0006 02E8H IRQ3

The following debug command shows that the address of COM1 is 03F8 , the address of COM2 is 02F8 and
the address of COM3 is 03E8.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 26


Microprocessor Interfacing Lab Lab07: PC to PC Serial Communication

Fig: Each byte in output of debug is a byte in memory

Fig: Calculating the Absolute Address

The following sample program in C, It shows how you can read these locations to obtain
the addresses of your communications ports. Save this code as port.address.cpp
Compile it using Turbo C compiler
#include <stdio.h>

Faculty of Engineering & Technology, International Islamic University Islamabad Page 27


Microprocessor Interfacing Lab Lab07: PC to PC Serial Communication

#include <conio.h>
#include <dos.h>
void main(void)
{
unsigned int far *ptraddr; /* ointer to location of Port
addresses */
unsigned int address; /* ddress of Port */
int a;

clrscr();
ptraddr=(unsigned int far *)0x00000400;
for (a = 0; a < 4; a++)
{
address = *ptraddr;
if (address == 0)
printf("No port found for COM%d \n",a+1);
else
printf("Address assigned to COM%d is
%Xh\n",a+1,address);
*ptraddr++;
}
getch();

// on my PC executing this code showed the following output


Address assigned to COM1 is 3F8h
Address assigned to COM2 is 2F8h
No port found for COM3
No port found for COM3

If you want to see these information in Windows 2000/XP


1- Go to Device Manager
2- See the properties of Communications Port (COM1)

Faculty of Engineering & Technology, International Islamic University Islamabad Page 28


Microprocessor Interfacing Lab Lab07: PC to PC Serial Communication

Figure 2 the male DB-9 plug used by AT-class serial devices.

Table 3: 9-Pin Serial Connector and its functions

Null Modems

Connecting two PCs together using RS232, without handshaking

Faculty of Engineering & Technology, International Islamic University Islamabad Page 29


Microprocessor Interfacing Lab Lab07: PC to PC Serial Communication

Connecting two PCs together using RS232, with handshaking

Programming PCs Serial Port:

// To run this program place a loop back plug at first serial port of your PC

#include <stdio.h>
#include <bios.h>
#include <conio.h>

#define COM1 0
#define DATA_READY 0x100
#define TRUE 1
#define FALSE 0

#define SETTINGS (_COM_1200 | _COM_CHR8 | _COM_STOP1 | _COM_NOPARITY)

int main(void)
{
clrscr();
int send, receive, status, DONE = FALSE;

printf("Initalizing serial port at\n");


printf("Baud Rate = 1200 \t Data Size = 8-bit\n");
printf("Stop Bits = 1 \t Parity Bits= No Parity\n");

bioscom(0, SETTINGS, COM1);


printf("\nPress [ESC] key to exit ...\n");

Faculty of Engineering & Technology, International Islamic University Islamabad Page 30


Microprocessor Interfacing Lab Lab07: PC to PC Serial Communication

while (!DONE)
{
status = bioscom(3, 0, COM1);
if (status & DATA_READY)
{
receive = bioscom(2, 0, COM1);
printf("Data Received = %c",receive);
}

if (kbhit())
{
if ((send = getch()) == '\x1B')
DONE = TRUE;
printf("\nSending Data = %c",send);
bioscom(1, send, COM1);
}
}
return 0;
}

Programming PCs Serial Port Using BIOS Interrupt 14h:

#include <stdio.h>
#include <bios.h>
#include <process.h>
#include <conio.h>
#include <iostream.h>

#define COM1 0 // First Serial Port, 1=2nd Serial Port


#define DATA_READY 0x1
#define TRUE 1
#define FALSE 0

#define SETTINGS ( _COM_1200| _COM_NOPARITY | _COM_STOP1 | _COM_CHR8)


// Bits 0-1: Word length
// 10 -> 7 bits, 11 -> 8 bits
// Bit 2: Number of stop bits
// 0 -> 1 stop bit, 1 -> 2 stop bits
// Bits 3-4: Parity
// 00 -> none, 01 -> odd, 11 -> even
// Bits 5-7: Baud rate
// 000 -> 110 baud, 001 -> 150 baud
// 010 -> 300 baud, 011 -> 600 baud
// 100 -> 1200 baud, 101 -> 2400 baud
// 110 -> 4800 baud, 111 -> 9600 baud
// As I want 1200 Baud Rate, No Parity, 1 Stop bit, Word Length = 8 bits
// 1 0 0 0 0 0 11
= 0x83

int port_initialize()
{
union REGS regs;
regs.h.ah = 0; // Call Function 0 to initialize Port
regs.h.dl = COM1; // Which Port?
regs.h.al = SETTINGS; // Configuration parameters
cout<<"Initalizing serial port at\n";
cout<<"Date Size = 8-Bit \t Stop Bits = One \n";
cout<<"Parity Bits = No \t Baud Rate = 1200 \n";
cout<<"Settings = "<<hex<<SETTINGS<<endl;

Faculty of Engineering & Technology, International Islamic University Islamabad Page 31


Microprocessor Interfacing Lab Lab07: PC to PC Serial Communication

int86(0x14, &regs, &regs);


return 0;

int port_status()
{
union REGS regs;
regs.h.ah = 3; // Function 3h: Read Status
regs.h.dl = COM1; // first serial port
int86(0x14, &regs, &regs);
if (regs.h.ah & 1) // is DATA_READY
return TRUE;
else
return FALSE;
}

int port_send(char ch)


{
union REGS regs;
regs.h.ah = 1; // Function 1h: Send Character
regs.h.dl = COM1; // first serial port
regs.h.al = ch; // Character to send
int86(0x14, &regs, &regs);
return TRUE;
}

char port_receive()
{
if(port_status()){
union REGS regs;
regs.h.ah = 2; // Function 2h: Receive Character
regs.h.dl = COM1; // first serial port
int86(0x14, &regs, &regs);
return(regs.h.al); // Character Received
}
else
cout<<"\nData is Not Ready"<<endl;
return FALSE;
}

int main(void)
{
clrscr();
char option;
printf("\nPress [ESC] key to exit ...\n");

port_initialize();
while(1)
{
cout<<"\n[S]-> Send Data \t [R]->Receive Data \t [ESC]->Exit\n";
option = getch();
if(option =='s'){
cout<<"Send What? ";
port_send(getche());
}
if(option =='r')
cout<<port_receive()<<endl;
if(option =='\x1B')
exit(0);
}

Faculty of Engineering & Technology, International Islamic University Islamabad Page 32


Microprocessor Interfacing Lab Lab07: PC to PC Serial Communication

}
Here is out put
Press [ESC] key to exit ...
Initalizing serial port at
Date Size = 8-Bit Stop Bits = One
Parity Bits = No Baud Rate = 1200
Settings = 83

[S]-> Send Data [R]->Receive Data [ESC]->Exit


Send What? X
[S]-> Send Data [R]->Receive Data [ESC]->Exit
X // Press r to receive Data

[S]-> Send Data [R]->Receive Data [ESC]->Exit

Using outportb() function for serial communication

#include <dos.h>
#include <stdio.h>
#include <conio.h>
#define PORT1 0x3F8
/* Defines Serial Ports Base Address */
/* COM1 0x3F8 */ /* COM2 0x2F8 */ /* COM3 0x3E8 */ /* COM4 0x2E8 */

void main(void)
{ int c;
int ch;
outportb(PORT1 + 1 , 0); /* Turn off interrupts - Port1 */
/* PORT 1 - Communication Settings */
outportb(PORT1 + 3 , 0x80); /* SET DLAB ON */
outportb(PORT1 + 0 , 0x03); /* Set Baud rate - Divisor Latch Low Byte */
/* Default 0x03 = 38,400 BPS */
/* 0x01 = 115,200 BPS */ /* 0x02 = 56,700 BPS */ /* 0x06 = 19,200 BPS */
/* 0x0C = 9,600 BPS */ /* 0x18 = 4,800 BPS */ /* 0x30 = 2,400 BPS */

outportb(PORT1 + 1 , 0x00); /* Set Baud rate - Divisor Latch High Byte */


outportb(PORT1 + 3 , 0x03); /* 8 Bits, No Parity, 1 Stop Bit */
outportb(PORT1 + 2 , 0xC7); /* FIFO Control Register */
outportb(PORT1 + 4 , 0x0B); /* Turn on DTR, RTS, and OUT2 */

printf("\nSample Comm's Program. Press ESC to quit \n");


do {
c = inportb(PORT1 + 5); /* Check to see if char has been */
/* received. */
if (c & 1) {ch = inportb(PORT1); /* If so, then get Char */
printf("%c",ch);} /* Print Char to Screen */
if (kbhit()){ch = getch(); /* If key pressed, get Char */
outportb(PORT1, ch);} /* Send Char to Serial Port */
}
while (ch !=27); /* Quit when ESC (ASC 27) is pressed */

} Table of Registers

Base Address DLAB Read/Write Abr. Register Name


+0 =0 Write - Transmitter Holding Buffer
=0 Read - Receiver Buffer
=1 Read/Write - Divisor Latch Low Byte

Faculty of Engineering & Technology, International Islamic University Islamabad Page 33


Microprocessor Interfacing Lab Lab07: PC to PC Serial Communication

+1 =0 Read/Write IER Interrupt Enable Register


=1 Read/Write - Divisor Latch High Byte
+2 - Read IIR Interrupt Identification Register
- Write FCR FIFO Control Register
+3 - Read/Write LCR Line Control Register
+4 - Read/Write MCR Modem Control Register
+5 - Read LSR Line Status Register
+6 - Read MSR Modem Status Register
+7 - Read/Write - Scratch Register

Faculty of Engineering & Technology, International Islamic University Islamabad Page 34


Microprocessor Interfacing Lab Lab08: Serial Communication between Computer & 8051 MC

Lab08: Serial Communication between Computer & 8051 MC


Objective:

Send a character from Computer to Microcontroller through serial port. Microcontroller increments that
character and send it back to Computer.

RS-232 Level Converters

The serial port of computer sends/receives data serially at logic levels between -12 to +12V. But the
microcontroller works at logic levels between 0 to 5V. So we need a RS-232 to TTL and TTL to RS-232
converter and this is done by RS-232 Level Converter called MAX-232.

MAX-232 includes a Charge Pump, which generates +10V


and -10V from a single 5v supply. This I.C. also includes
two receivers and two transmitters in the same package.

Null Modem Cable

A Null Modem Cable is needed to connect MAX-232 to PC.

Circuit Diagram for Connecting MAX-232 to Computer and Microcontroller

Faculty of Engineering & Technology, International Islamic University Islamabad Page 35


Microprocessor Interfacing Lab Lab08: Serial Communication between Computer & 8051 MC

Program for Computer:

// computer.cpp

#include <stdio.h>
#include <bios.h>
#include <conio.h>

#define COM1 0
#define DATA_READY 0x100
#define TRUE 1
#define FALSE 0

#define SETTINGS (_COM_1200 | _COM_CHR8 | _COM_STOP1 | _COM_NOPARITY)

int main(void)
{
clrscr();
int send, receive, status, DONE = FALSE;

printf("Initalizing serial port at\n");


printf("Baud Rate = 1200 \t Data Size = 8-bit\n");
printf("Stop Bits = 1 \t Parity Bits= No Parity\n");

bioscom(0, SETTINGS, COM1);


printf("\nPress [ESC] key to exit ...\n");

while (!DONE)
{
status = bioscom(3, 0, COM1);
if (status & DATA_READY)
{
receive = bioscom(2, 0, COM1);
printf("\nData Received = %c",receive);

Faculty of Engineering & Technology, International Islamic University Islamabad Page 36


Microprocessor Interfacing Lab Lab08: Serial Communication between Computer & 8051 MC

if (kbhit())
{
if ((send = getch()) == '\x1B')
DONE = TRUE;
printf("\nSending Data = %c",send);
bioscom(1, send, COM1);
}
}
return 0;
}

Microcontroller Registers related to Serial Communication:

There are some special registers in 8051 microcontrollers that are used for serial communication

SCON (Serial Control) SFR

Bit Name Bit Explanation of Function


Address
7 SM0 9Fh Serial port mode bit 0
6 SM1 9Eh Serial port mode bit 1.
5 SM2 9Dh Mutliprocessor Communications Enable
4 REN 9Ch Receiver Enable. This bit must be set in order to
receive characters
3 TB8 9Bh Transmit bit 8. The 9th bit to transmit in mode 2
and 3.
2 RB8 9Ah Receive bit 8. The 9th bit received in mode 2 and 3.
1 TI 99h Transmit Flag. Set when a byte has been completely
transmitted
0 RI 98h Receive Flag. Set when a byte has been completely
received.

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

SM0 SM1 Serial Mode Explanation Baud Rate


0 0 0 8-bit Shift register Oscillator / 12
0 1 1 8-bit UART Set by Timer 1 (*)
1 0 2 9-bit UART Oscillator / 32 (*)
1 1 3 9-bit UART Set by Timer 1 (*)

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

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

Bit Name Explanation of Function Timer


7 GATE1 When this bit is set the timer will only run when 1
INT1 (P3.3) is high. When this bit is clear the

Faculty of Engineering & Technology, International Islamic University Islamabad Page 37


Microprocessor Interfacing Lab Lab08: Serial Communication between Computer & 8051 MC

timer will run regardless of the state of INT1.


6 C/T1 When this bit is set the timer will count events on 1
T1 (P3.5). When this bit is clear the timer will be
incremented every machine cycle.
5 T1M1 Timer mode bit (see below) 1
4 T1M0 Timer mode bit (see below) 1
3 GATE0 When this bit is set the timer will only run when 0
INT0 (P3.2) is high. When this bit is clear the
timer will run regardless of the state of INT0.
2 C/T0 When this bit is set the timer will count events on 0
T0 (P3.4). When this bit is clear the timer will be
incremented every machine cycle.
1 T0M1 Timer mode bit (see below) 0
0 T0M0 Timer mode bit (see below) 0

As you can see in the above chart, four bits (two for each timer) are used to specify a mode of
operation. The modes of operation are:
TxM1 TxM0 Timer Mode Description of Mode
0 0 0 13-bit Timer
0 1 1 16-bit Timer
1 0 2 8-bit auto-reload
1 1 3 Split timer mode

Data Rate is the bit rate, the number of bits per second available on a particular line
Baud Rate is the number of signaling elements on a particular line, or it can also be said as the
modulation rate
D = R / L = R / log2M
D = Data Rate
R = Modulation Rate
L = Number of bits per signaling element
M = Number of signaling elements

Crystal
TH 1 = 256
384 BaudRate

e.g. for Crystal = 11.0592 MHz, Baud Rate = 1200

11059200
TH 1 = 256 = 256 24 = 232 = E8 = 24
384 1200

Faculty of Engineering & Technology, International Islamic University Islamabad Page 38


Microprocessor Interfacing Lab Lab08: Serial Communication between Computer & 8051 MC

The TCON SFR


Finally, theres one more SFR that controls the two timers and provides
valuable information about them. The TCON SFR has the following
structure:
Bit Name Bit Address Explanation of Function Timer
7 TF1 8Fh Timer 1 Overflow. This bit is set by 1
the microcontroller when Timer 1
overflows.
6 TR1 8Eh Timer 1 Run. When this bit is set Timer 1
1 is turned on. When this bit is clear
Timer 1 is off.
5 TF0 8Dh Timer 0 Overflow. This bit is set by 0
the microcontroller when Timer 0
overflows.
4 TR0 8Ch Timer 0 Run. When this bit is set Timer 0
0 is turned on. When this bit is clear
Timer 0 is off.

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

Microcontroller Programming:

When writing a communications program in for Microcontroller you have two methods available to you.
1- Poll the T I flag to see if any new data is available.
2- Set up an interrupt handler to remove the data from the SBUF.
//poll.c
# include <c:\c51\inc\reg51.h>

void sendChar(unsigned char dataByte)


{
while(!TI); /* Wait until the serial port signals the previous character has
* been sent. It does so by setting the Transmit interrupt flag, TI,
* which this routine loops on until it is set to 1. */

TI = 0 ; /* Clear the Transmit Interrupt flag to prepare the serial port

Faculty of Engineering & Technology, International Islamic University Islamabad Page 39


Microprocessor Interfacing Lab Lab08: Serial Communication between Computer & 8051 MC

* to send a new character. */

SBUF = dataByte; /* Write the character into the serial port buffer register */
}

unsigned char recieveChar()


{
unsigned char dataByte;
while(!RI); /* Wait until the serial port signals a new character has arrived.
* It does so by setting the Received interrupt flag, RI, which
* this routine loops on until it is set to 1. This is known
* as polling. */

dataByte = SBUF; /* copy the the value in SBUF into the local variable */
RI = 0; /* Once the character is read, the serial port must be told
* that it is free to receive a new character. This is done
* by clearing the Received Interrupt flag. */

return dataByte; /* the character is then returned to the calling function. */


}

void main()
{
unsigned char dataByte;
SCON = 0x50; /* mode 1, 8-bit uart, enable receiver (RI=1) */
TMOD = 0x20; /* timer 1, mode 2, 8-bit reload */
TH1 = -24; /* Reload value of the timer for baud rate 1200 bps */
/* TH1 = 256 - clock frequency (in Hz) / (384 * baud rate)
* For 1200bps and a 11.02Mhz clock:
* TH1 = 256 - 11,020,000 / (384 * 1200) = 232 = 0xE8 = -24 */
TR1 = 1; /* Setting TR1 will start the timer, and serial communications */
TI=1; /* Set the Transmit Interrupt flag to send the the character in
* the serial buffer, clearing will be done by the program. */
while(1)
{
dataByte=recieveChar(); /* read the next character from the serial port */
dataByte= dataByte+1; /* Increment the received character */
sendChar(dataByte); /* send it back to the original sender */
}

Faculty of Engineering & Technology, International Islamic University Islamabad Page 40


Microprocessor Interfacing Lab Lab08: Serial Communication between Computer & 8051 MC

//interr.c

# include <c:\c51\inc\reg51.h>

void sendChar(unsigned char dataByte){


}

unsigned char recieveChar(){


}

void serial_int (void) interrupt 4 /* serial interrupt is interrupt 4. A single


* interrupt is generated for both transmit and receive interrupts. To write an
* interrupt handler in Keil, the function must be declared void, with no
* parameters, write interrupt keyword and then interrupt Number. */
{
static char chr = '\0'; /* character buffer */

/* The interrupt was generated, but it is still unknown why. First, check
* the RI flag to see if it was because a new character was received. */

if (RI == 1) /* it was a receive interrupt */


{
chr = SBUF; /* read the character into our local buffer */
RI = 0; /* clear the received interrupt flag */
TI = 1; /* signal that there's a new character to send */
}
else if (TI == 1) /* otherwise, assume it was a transmit interrupt */
{
TI = 0; /* clear the transmit interrupt flag */
if (chr != '\0') /* if there's something in the local buffer... */
{
chr = chr + 1; /* increment character */
SBUF = chr; /* put the character into the transmit buffer */
chr = '\0';
}
}
}

main()
{
/* Before the serial port may be used, it must be configured. */
/* Set up Timer 0 for the serial port */
SCON = 0x50; /* mode 1, 8-bit uart, enable receiver */
TMOD = 0x20; /* timer 1, mode 2, 8-bit reload */
TH1 = -24; /* reload value for 1200 baud */
ET0 = 0; /* we don't want this timer to make interrupts */
TR1 = 1; /* start the timer */
TI = 1; /* clear the buffer */

/* The compiler automatically installs the interrupt handler, so all that needs
* to be done to use it is enable interrupts. First, speficially enable the
* serial interrupt, then enable interrupts. */

ES = 1; /* allow serial interrupts */


EA = 1; /* enable interrupts */
P0 = 0; /* initialize Port 0 to 0 */

/* Loop forever, increasing Port 0. Again, note nothing is done with the serial
* port in this loop. Yet simulations will show that the software is perfectly
* capable of maintaining serial communications while this counting proceeds. */

Faculty of Engineering & Technology, International Islamic University Islamabad Page 41


Microprocessor Interfacing Lab Lab08: Serial Communication between Computer & 8051 MC

while (1)
{
unsigned int i;
for (i = 0; i < 60000; i++) {;} /* delay */
P0 = P0 + 1; /* increment Port 0 */
}
}

Faculty of Engineering & Technology, International Islamic University Islamabad Page 42


Microprocessor Interfacing Lab Lab09: Parallel Port Programming in PC

Lab09: Parallel Port Programming in PC

Following are the pinouts:

8 Output pins [D0 to D7]


5 Status pins [S4 to S7 and S3]
4 Control pins [C0 to C3]
8 ground pins [18 to 25]

The Pins having a bar over them ,means that the signal is inverted by the parallel port's hardware.If a 1 were to appear on
the 11 pin [S7], the PC would see a 0. The Status pins are mainly used by the PC to know the status of the printer ,like if
there is paper in the printer, end of paper etc.

Only the Data Port will be covered in this segment.

Parallel Port Female Connector

The Data Port

Sending commands involves only the data pins [D0 to D7].Though it is possible to use the some other pins as input, we'll
stick to the basics.

Please remember that the Data pins are from pin 2 to pin 9 and not from pin 1.

Sending Commands to the Port:

This part is easy.Just a single line of code does the trick.

Open up your C compiler.


Type the following program:

Faculty of Engineering & Technology, International Islamic University Islamabad Page 43


Microprocessor Interfacing Lab Lab09: Parallel Port Programming in PC

#include <stdio.h>
#include <dos.h>

void main(void)
{
outportb(0x378,0xFF); //da line
}

That's it ,you just set all your data pins to 1.

If you take an LED and put one terminal at pin2 and the other to pin 18,it would glow.[Use a 2K resistor in series with the
LED, otherwise you will end up ruining your LED, or source too much current from the port pin]

WARNING Please do not feed your port more than 5V.You'll blow it up. Check all the voltages with a Multimeter before
proceeding

if you wish to switch it off. Type this:

outportb(0x378,0x00);

0x378 is the parallel port address . Usually this is the default address. Sometimes it is 0x278 too

0x00 is the command appearing at the output pins. The Format is in Hexadecimal

So if u want to make pin no2 high, that's the first pin you type

0x01 which would mean 0000 0001 for the data port.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 44


Microprocessor Interfacing Lab Lab10: ADC Interfacing and Programming

Lab10: ADC Interfacing and Programming


OBJECTIVE: To convert analog signal into Digital and send it to PC through serial port

ADC 0804: The easiest way to do analog to digital conversion is to use ADC0804 IC. This IC converts
analog signal to 8-bit digital format.
The analog voltage is applied to pin 6 (Vin + ) and the result is available
at pins 11 through 18 (D7 to D0).
We will connect pin 1 (Chip Select) to ground so that the chip is always
enabled.
Connect pin 7 (Vin - ) to ground.
The ADC0804 includes an internal oscillator which requires an external
capacitor and resistor to operate.
o Therefore connect the 150 pF capacitor from pin 4 to ground
o Also connect a 10k ohm resistor from pin 4 to pin 19.
Connect pin 20 to 5 volts for Vcc and pin 10 to ground.
Connect pin 10 to ground.

Interfacing the ADC0804 to the 8051:


The AT89C2051 is a general purpose 20 pin microcontroller. To control the ADC0804, we will use 3 lines
from the AT89C51.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 45


Microprocessor Interfacing Lab Lab10: ADC Interfacing and Programming

Connect pin 2 (Read) from the ADC0804 to pin 7 (P3.3) of the 2051.
Connect pin 3 (Write) to pin 8 (P3.4).
Connect pin 5 (Interrupt) to pin 9 (P3.5).
The 8 bit Output Data from the ADC0804 will be connected to Port 1 of the 2051.
o Connect pin 18 (D0) of the ADC0804 to pin 12 of the 2051 (P1.0).
o Connect pin 17 (D1) to pin 13 (P1.1).
o Connect pin 16 (D2) to pin 14 (P1.2).
o Connect pin 15 (D3) to pin 15 (P1.3).
o Connect pin 14 (D4) to pin 16 (P1.4).
o Connect pin 13 (D5) to pin 17 (P1.5).
o Connect pin 12 (D6) to pin 18 (P1.6).
o Connect pin 11 (D7) to pin 19 (P1.7).
The 2051 pins 12 and 13 do not have internal pull up resistors so external pull up resistors are
required.
o Connect a 2.2k ohm resistor from pin 12 of the 2051 to 5 volts.
o Connect a 2.2k ohm resistor from pin 13 of the 2051 to 5 volts.
To power the 2051, Connect pin 20 of the 2051 to 5 volts and pin 10 of the 2051 to ground.
For the 2051 oscillator, Connect the 11 MHz Crystal from pin 4 of the 2051 to pin 5 of the 2051.
o Connect one 33 pF capacitor from pin 4 of the 2051 to ground.
o Connect an other 33 pF capacitor from pin 5 of the 2051 to ground.
For the 2051 reset circuit,
o Connect the 8.2k ohm resistor from pin 1 of the 2051 to ground.
o Connect the 10 uF capacitor from pin 1 of the 2051 to 5 volts.

The 2051 controls the analog to digital conversion process. The conversion process has several stages.
o Stage 1) to trigger (start) a new conversion, we must make pin 3 (Write) low and then return it
to the high state. The A/D will remain in the reset state as long as the (CS) and (Write) inputs
remain low. The conversion process starts when Write goes high (rising edge triggered).
o Stage 2) When the conversion process is complete, pin 5 (Interrupt) will make a High-to-Low
transition.
o Stage 3) When we see pin 5 (Interrupt) go Low; we must make pin 2 (Read or output enable)
low to load the new value into the outputs D0 - D7. Pin 2 can be grounded to constantly have
the latest conversion present at the output.

o Stage 4) Next we read the values into the 2051 Port 1.


o Stage 5) finally, we return pin 2 (Read) to the high state. The next conversion can be started
immediately.
Communicating with the PC - The MAX232 IC
Now that we have the 8 bit value in the 2051, we want to send that value to the PC. The 2051 has a built in
serial port that makes it very easy to communicate with the PC's serial port but the 2051 outputs are 0 and
5 volts and we need +10 and -10 volts to meet the RS232 serial port standard. The easiest way to get these
values is to use the MAX232.
The MAX232 acts as a buffer driver for the processor. It accepts the standard digital logic values of 0 and
5 volts and converts them to the RS232 standard of +10 and -10 volts. It also helps protect the processor
from possible damage from static that may come from people handling the serial port connectors.
The MAX232 requires 5 external 1uF capacitors. These are used by the internal charge pump to create
+10 volts and -10 volts.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 46


Microprocessor Interfacing Lab Lab10: ADC Interfacing and Programming

o For the first capacitor, the negative leg goes to ground and the positive leg goes to pin 16.
o For the second capacitor, the negative leg goes to 5 volts and the positive leg goes to pin 2.
o For the third capacitor, the negative leg goes to pin 3 and the positive leg goes to pin 1.
o For the fourth capacitor, the negative leg goes to pin 5 and the positive leg goes to pin 4.
o For the fifth capacitor, the negative leg goes to pin 6 and the positive leg goes to ground.

The MAX232 includes 2 receivers and 2 transmitters so two serial ports can be used with a single
chip. We will only use one transmitter for lab. The only connection that must be made to the 2051 is
one jumper from pin 3 of the 2051 to pin 11 of the MAX232.
To power the MAX232, Connect pin 16 to 5 volts, Connect pin 15 to ground.
To connect to the serial port of PC use a 9 pin female connector. There should be 3 wires soldered to
the DB9 connector pins 2, 3 and 5.
o Connect the wire from pin 5 of the connector to ground on the breadboard.
o Connect the wire from pin 2 of the connector to pin 14 of the MAX232. (The other wire is for
receiving and is not used in this lab)

The Software
Use the following code to program the microcontroller.
A conversion is started by clearing and setting P1.0 (The ADC0804s WR input).
Then the program sits in a loop waiting for the ADC0804 to finish the conversion and assert INTR at
P1.1
the data is read and sent to PC using serial communication.

#include <reg51.h>
#include "io.h"

void delay(unsigned char loop){


unsigned char chr;
for(chr=0 ; chr<loop ; chr++){
loop = loop + 1;
}
}

sbit READ = P3^2; /* Define these according to how you have connected the */
sbit WRITE = P3^3; /* RD, WR, and INTR pins */
sbit INTR = P3^4;

void main( void ) {

unsigned char adVal;


unsigned long volts;
InitIO();

READ = 1;
WRITE = 1;
INTR = 1;

while(1) {

WRITE = 0; /* Make a low-to-high transition on the WR input */


Delay(10);
WRITE = 1;

while( INTR == 1 ); /* wait until the INTR signal makes */

Faculty of Engineering & Technology, International Islamic University Islamabad Page 47


Microprocessor Interfacing Lab Lab10: ADC Interfacing and Programming

/* high-to-low transition indicating */


/* completion of conversion */

READ = 0; /* Read the voltage value from the port */


adVal = P1;
READ = 1;

/* Compute the digital value of the volatge read */

P0 = adVal /* Print the value of the voltage in decimal form */


}
}

Make sure the power is off to the circuit you have built.
Connect the circuit to the PC's serial port, Comm1. Turn on the power to the breadboard. The circuit
should send a continuous stream of values to the PC. To see the values on the PC.
Try this sample program. This program takes the received value and divides it by 51 to find the
corresponding voltage level. (The minimum value is 0 which is 0 volts and the maximum value is 255,
which is 5 volts.)

Testing the Circuit


To test your circuit, connect various voltages to pin 6 of the ADC0804. If you connect a jumper from
pin 6 to 5 volts, the voltage on the sample program should say 5 volts.
Remove the jumper. Try connecting a 2.2k resistor from pin 6 to ground and another 2.2k resistor
from pin 6 to 5 volts. The result should be around 2.5 volts.
Remove the resistors. Try playing with the 220 uF capacitor and the 15k Ohm resistor. Connect the
negative leg of the capacitor to ground and the positive leg to pin 6 of the ADC0804. Connect the
resistor from pin 6 to 5 volts. The voltage should rise quickly and then slower as it approaches 5 volts.
Now remove the resistor. The voltage should stay at the same voltage and slowly decay as the
capacitor loses it's charge. Connect the resistor from pin 6 to ground to quickly discharge the
capacitor.

#include <lcd4bitx51.h>
#include <stdio.h> // Required for the function sprintf
void main()
{
unsigned char buffer[17], readValue=0,i;
float voltage;
P0 = 0xff; // Initialize port 0 to read external values
P0 = 0x00;

InitLCD_rimsDEV2763();
PrintLCD("Value read :");

while(1) {
for(i=0;i<100;i++) // Read 100 values and average them
readValue += P0;
readValue = readValue / 100;

// Convert unsigned char value to 5 Volt floating voltage value


voltage =( readValue*5 )/ 256;

Faculty of Engineering & Technology, International Islamic University Islamabad Page 48


Microprocessor Interfacing Lab Lab10: ADC Interfacing and Programming

sprintf(bu ffer,"%3.2f Volts\0");


LocateLCD(2,1);
PrintLCD(buffer);
}
}

In the above example, one thing to keep in mind is that the A to D converter is running in self-clocking and
free running mode. It automatically converts any analog signal applied to its input into 8-bit digital code at the
output. So you read 100 values and took their average, and then converted it back into the voltage format and
display it on the LCD.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 49


Microprocessor Interfacing Lab Lab11: Controlling a Stepper Motor

Lab11: Controlling a Stepper Motor


Introduction

Stepper motors are often used


in conjunction with
microcontrollers to provide
precisely controlled motor
power. Stepper motors are
devices that rotate a precise
number of degrees for each
"step" applied, as opposed to
regular motors, which simply
rotate continuously when
power is applied. Driving a
stepper motor involves
applying a series of voltages to
the four(typically) coils of the
stepper motor. The coils are
energized one or two at a time
to cause the motor to rotate one
step. Stepper motor taken from
old disk drive can be used for
the experiment. Following is
the internal diagram of
different types of stepper
motors.

When the center-taps of these


motors are connected to +12
and one end of either winding
is grounded, the winding will
draw a current from 170 mA to
250 mA, depending on the
motor. The ULN2003
darlington transistor arrays
from Allegro Microsystems is
probably the most widely
available of the applicable
chips, so it will be used in this
lab.

M1 is a stepper taken from an old disk drive. There are five pins, i.e., common, coil 1, 2, 3 and 4. Resistance
measured between common pin and each coil is about 75 Ohms. 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. Each output provides 500mA max at 50V. P1.4 to P1.7, four output pins are connected to the input
of the ULN2003 as shown in the circuit. Four 4.7k resistors help the 2051 to provide more sourcing current
from the +5V supply. The serial port is optional for your exercises.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 50


Microprocessor Interfacing Lab Lab11: Controlling a Stepper Motor

I have changed a 10ms time base with a simple TF0 polling instead of using interrupt. The program is just to
send the stepper's energizing pattern to the P1 every 10ms. Flag1 is used for intertask communication.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 51


Microprocessor Interfacing Lab Lab11: Controlling a Stepper Motor

/* STEPPER.C */

#include c:\mc51\8051io.h /* include i/o header file */


#include c:\mc51\8051reg.h

register unsigned char j,flag1,temp;


register unsigned int cw_n,ccw_n;

Faculty of Engineering & Technology, International Islamic University Islamabad Page 52


Microprocessor Interfacing Lab Lab11: Controlling a Stepper Motor

unsigned char step[8]={0x80,0xc0,0x40,0x60,0x20,0x30,0x10,0x90}

#define n 400
/* flag1 mask byte
0x01 run cw()
0x02 run ccw()
*/

main(){
flag1=0;
serinit(9600);
disable(); /* no need timer interrupt */
cw_n = n; /* initial step number for cw */
flag1 |=0x01; /* initial enable cw() */
while(1){
tick_wait(); /* wait for 10ms elapsed */
energize(); /* round-robin execution the following tasks every 10ms */
cw();
ccw();
}
}
cw(){
if((flag1&0x01)!=0){
cw_n--; /* decrement cw step number */
if (cw_n !=0)
j++; /* if not zero increment index j */
else {
flag1&=~0x01; /* disable cw() execution */
ccw_n = n; /* reload step number to ccw counter */
flag1 |=0x02; /* enable cww() execution */
}
}
}
ccw(){
if((flag1&0x02)!=0)
{
ccw_n--; /* decremnent ccw step number */
if (ccw_n !=0)
j--; /* if not zero decrement index j */
else
{flag1&=~0x02; /* disable ccw() execution */
cw_n = n; /* reload step number to cw counter */
flag1 |=0x01; /* enable cw() execution */
}
}
}
tick_wait(){ /* cputick was replaced by simpler ASM code 10ms wait */
asm" JNB TCON.5,*"; /* wait for TF0 set */
asm" CLR TCON.5"; /* clear TF0 for further set */
asm" ORL TH0,#$DC"; /* reload TH0 with $DC, TL0 = 0 */
}
energize(){
P1 = step[(j&0x07)]; /* only step 0-7 needed */
}

Exercises

1. change the speed showing the rotation becomes faster or slower than 10ms time delay.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 53


Microprocessor Interfacing Lab Lab11: Controlling a Stepper Motor

2. with an additional serial port, write an initializing function that receives ascii command from terminal
to set the number of step for cw and ccw.

Faculty of Engineering & Technology, International Islamic University Islamabad Page 54

You might also like