Mc & Mp Lab Complete Manual.pdf

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Mc & Mp Lab Complete Manual.pdf as PDF for free.

More details

  • Words: 12,487
  • Pages: 68
Laboratory Manual for Microprocessor and Microcontroller Lab

Name of Student: Roll No.: Section:

Department of Electronic Engineering Faculty of Engineering & Technology

International Islamic University Islamabad

List of Experiments Introduction to SAP-1 and Implementation of Program Counter, Accumulator, AdderSubtractor and B-Register ........................................................................................................................ 2 Implementation of Input and MAR, RAM, RAM Programming, Instruction Register, Output Register & Binary Display ........................................................................................................... 8 Implementation of Controller / Sequencer for the SAP-1 and Complete Integration of SAP-1 ..................................................................................................................................................... 16 Introduction to 8051 micro controller and I/O port programing using LED Interfacing ....................... 23 7-Segment Display Interfacing and Programming with 8051 Microcontroller ...................................... 29 Keypad Interfacing with 8051 Microcontroller...................................................................................... 34 LCD Interfacing with 8051 Microcontroller .......................................................................................... 38 Analog to Digital Converter (ADC) Interfacing with 8051 Microcontroller ......................................... 44 Timer / Counter Mode Programming with 8051 Microcontroller.......................................................... 49 Serial Communication between PC and 8051 Microcontroller.............................................................. 56 Interrupt Based Programming with 8051 Microcontroller ..................................................................... 63

Microprocessor & Microcontroller Lab (EE212L)

Page 1

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 01

Introduction to SAP-1 and Implementation of Program Counter, Accumulator, Adder-Subtractor and B-Register

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature:

Microprocessor & Microcontroller Lab (EE212L)

Page 2

Introduction to SAP 1 and Implementation of Program Counter, Accumulator, Adder- Subtractor and B Register Objectives: The purpose of this lab is to introduce the basic concept of SAP-1, its functions and parts and simulate the following components of SAP-1 a) Program Counter which generates a 4-bit address code of memory b) the Accumulator register c) An 8-bit Adder-Subtractor d) B register

Resources Required: • A computer • Proteus 7.0x or higher

Introduction to SAP-1: SAP simply called Simple as Possible is a bus organized computer. SAP-1 is the first stage in evolution towards the modern computers. The main purpose of SAP is to introduce all the crucial ideas behind computer operations. Being a simple computer, SAP-1 also covers many advanced concepts.

Main Features: • Simple-As-Possible • One output device (8 LEDs) • 16 bytes of read-only memory • 5 instructions: 3 with 1 operand, 2 with implicit operands • Accumulator architecture: Accumulator, Out Register, B Register, Memory Address Register (MAR) and Instruction Register (IR)

Architecture: • 8-bit "W" bus • 4-bit program counter, only counts up (starts execution at 0) • 4-bit Memory Address Register (MAR) • 16x8-bit Memory • 8-bit Instruction Register (IR) • 6-cycle controller with 12-bit microinstruction word • 8-bit Accumulator • 8-bit B Register • 8-bit Adder-Subtractor • 8-bit Output Register SAP-1 is a bus organized computer. All registers are connected to the W bus with the help of tri-state buffers. A block diagram of SAP-1 is shown in figure below.

Microprocessor & Microcontroller Lab (EE212L)

Page 3

Brief introduction of Program counter, Accumulator, adder and subtractor is given below.

Program Counter (PC): Program Counter generates the memory addresses of the instruction to be fetched. Instructions to be executed are placed at the starting addresses of memory, e.g. the first instruction of a program will be placed at binary address 0000, the second instruction at address 0001, the third at address 0010, and so on. Now to execute one instruction, first step is to generate the address at which this instruction is placed in memory. So this address is generated by Program Counter, which can count from

Microprocessor & Microcontroller Lab (EE212L)

Page 4

0000 to 1111 (0 to 15). Because total memory locations are 16, Program Counter is a 4-bit counter. Program Counter for SAP-1 Digital Circuit diagram for Program Counter is as below.

Chip 74LS107, is a dual J-K flip flop that produces the upper 2 address bits. Chip C2, another 74LS107, produces the lower 2 address bits. Chip is a 74LS126, a quad tristate normally open switch, it gives the program counter a three state output. At the start of the computer run, a low CLR resets the program counter to 0000. During the T1 state, a high EP latches the address on W bus. During the T2 state, a high CP is applied to program counter, midway through this state, the negative CLR edge increments the program counter.

Accumulator: The Accumulator is a buffer register that stores intermediate answers during a computer run. The accumulator has both a two-state and a three-state output. The twostate output goes directly to the adder-subtractor and the three-state output goes to the W bus via a buffer. Therefore, the 8-bit Accumulator word continuously drives the adder-subtractor; the same word appears on the W bus when EA is high.

Microprocessor & Microcontroller Lab (EE212L)

Page 5

Chips 74LS173s, is the accumulator. Pins 1 and 2 are grounded on both chips to produce a two-state output for the adder-subtractor. Chips 74LS126s; these three-state switches place the accumulator contents on the W bus when EA is high.

Adder-Subtractor: SAP-1 uses a 2's complement adder-subtractor. When Su is low, the sum out of the adder-subtractor is A = A+B. When Su is high, the difference appears: A = A+B' (Recall that the 2's complement is equivalent to a decimal sign change). The adder-subtractor is asynchronous (unclocked); this means that its contents can change as soon as the input words change. When EU is high, these contents appear on the W bus. Chips 74LS86; these ExclusiveOR gates are a controlled inverter. When SU is low, the contents of the B register are transmitted. When SU is high, the 1's complement is transmitted and a 1 is added to the LSB to form the 2's complement. Chips 74LS83; these 4-bit full adders combine to produce an 8-bit sum or difference. Chips 74LS126s, convert the 8-bit answer into a three-state output for driving the W bus.

B-Register: This is another 8 bit buffer register. It is used in arithmetic operations. It supplies the number to be added or subtracted from the contents of accumulator to the addersubtractor. A low LB and a positive clock edge load the word on the W bus into the B register. The two state output of the B register drives the Adder-Subtractor, supplying the number to be added or subtracted from the contents of the accumulator. Accumulator Register, Adder-Subtractor and B Register Working: The input to the Accumulator should be through switches, which will be one 8-bit binary number. This number is later sent to adder-subtractor. There should be a static 8-bit binary number as the other input to the adder-subtractor. The output of the addersubtractor should be connected to LEDs. By proper input to the Su pin, the LEDs should be showing the results of adder-subtractor. Connect the circuit as shown in the following Figure:

Microprocessor & Microcontroller Lab (EE212L)

Page 6

Microprocessor & Microcontroller Lab (EE212L)

Page 7

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 02

Implementation of Input and MAR, RAM, RAM Programming, Instruction Register, Output Register & Binary Display

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature: Microprocessor & Microcontroller Lab (EE212L)

Page 8

Implementation of Input and MAR, RAM, RAM Programming, Instruction Register, Output Register & Binary Display Objective: Objective of this lab is to implement simulation of Input and MAR, Random Access Memory (RAM), RAM Programming, Instruction Register (IR), Output register and Binary Display for SAP-1 Computer.

Resources Required: • A computer • Proteus 7.0x or higher

Input & MAR: Input and MAR section contains 2 blocks. I) MAR II ) Input Unit

Memory Address Register (MAR): Address generated by program counter goes in Input and MAR section which then forwards it to RAM for read operation. MAR is temporary storage of the generated address before forwarding to RAM. Buffer register 74LS173 (4-bit buffer) serves as the MAR. Circuit for MAR is shown in figure. Notice that pins 1 and 2 are grounded; this converts the three-state output to a two-state output. In other words, the output of the MAR is not connected to the W bus and so there's no need to use the three-state output. Input Unit: Input unit is 2-to-1 nibble multiplexer. IC 74157 is used as input unit. It has 8bit inputs and 4 bit output. Circuit for input unit is shown in figure. The left nibble, (pins 14, 11, 5, 2), comes from the manual input address switch register S1 (these are just 4 DIP switches of your trainer and will be used to manually program your RAM). The right nibble, (pins 13, 10, 6, 3), comes from the MAR. The RUN-PROG switch S2 selects the nibble containing address to access RAM location. When S2 is in the PROG position (i.e. when it is low), the nibble out of the address switch register is selected. On the other hand, when S2 is in the RUN position (i.e. when it is high), the output of the MAR is selected.

Procedure: Connect the circuit as shown in the figure.

Microprocessor & Microcontroller Lab (EE212L)

Page 9

Random Access Memory (RAM): RAM is a 16x8 static TTL RAM. RAM can be programmed by address and data switch registers. This allows you to store a program and data in the memory before the computer run. During the computer run, RAM receives 4 bit addresses from the MAR and read operation is performed. In this way, the instruction and the data word is stored in the RAM is placed on the W-Bus for use in some other part of the computer.

Figure: Random Access Memory Programming Unit Microprocessor & Microcontroller Lab (EE212L)

Page 10

Instruction Register: The Instruction Register is part of the Control Unit. To fetch an instruction from the memory the computer does a memory read operation. This places the contents of the addressed memory location on the W bus. At the same time, the Instruction Register is set up for loading on the next positive clock edge. The contents of the instruction register are split into two nibbles. The upper nibble is a two-state output that goes directly to the block labeled "Controller-sequencer" The lower nibble is a three-state output that is read onto the W bus when needed. The chips used are 74LS173s. Each chip is a 4-bit three-state buffer register. The two chips are the Instruction Register. Grounding pins 1 and 2 of C8 convert the three state output to a two-state output, I7I6I5I4, this nibble goes to the instruction decoder in the controller sequencer. Signal E1 controls the output of C9, the lower nibble in the Instruction Register. When E1 is low, this nibble is placed on word bus. Instruction Register should be able to read instruction from RAM. When L1' is active and by making the E1' pin active, the upper nibble (Opcode) should be ready for control matrix circuit and lower nibble (memory address) should be ready to be fed to the MAR.

Figure: Instruction Register Circuit Diagram Microprocessor & Microcontroller Lab (EE212L)

Page 11

Output Register: At the end of an arithmetic operation the accumulator contains the word representing the answer; it is then loaded into the output register to be displayed to the outside world through the Binary Display. Binary Display: The binary display is a row of 8 LEDs. Since each LED is connected to one flip-flop of the output port, the binary display shows the contents of the Output register Circuit for B register in connection with Output Register, adder and accumulator is shown below.

Microprocessor & Microcontroller Lab (EE212L)

Page 12

Programming SAP-I: SAP-1 Instruction Set: SAP-1 computer has a set of five instructions. This instruction set is a list of basic operations this computer can perform. The instructions are: • LDA • ADD • SUB • OUT • HLT

Mnemonics: LDA, ADD, SUB, OUT and HLT represent the abbreviated form of the instruction set called Mnemonics. Memory referenced instructions: LDA, ADD and SUB are memory-referenced instructions because they use the data stored in memory. OUT and HLT are not memory-referenced instructions since they do not use the data stored in memory. Microprocessor & Microcontroller Lab (EE212L)

Page 13

LDA LDA stands for "Load the Accumulator". A complete LDA instruction includes the hexadecimal address of the data to be loaded. For instance, LDA 8H means load the accumulator with the data 8H. ADD ADD is another SAP-1 instruction. A complete ADD instruction includes the address of the word to be added. For instance Add 9H means add the contents of memory location 9H to the contents of the accumulator; the sum replaces the original contents of accumulator. First the contents of 9H are loaded into B register, and instantly the adder-subtractor forms the sum of A and B. SUB A complete SUB instruction includes the address of the word to be subtracted. For example SUB CH means subtract the contents of memory location CH from the contents of the accumulator. First, contents of CH are loaded into B register and then instantly the adder-subtractor forms the difference of A and B. OUT The OUT instruction transfers the contents of accumulator to the Output port. After the execution, the answer to the problem in the program can be seen on the LED display. OUT is not memory-referenced instruction; it does not need an address. HLT HLT stands for Halt. This instruction tells the computer to stop processing the data. HLT marks the end of a program similar to the way a period marks the end of a sentence. You must use a HLT instruction at the end of every SAP-1 program, otherwise you get computer trash. HLT is complete in itself; it does not require RAM word since this instruction does not involve memory. Programming: To load an instruction in memory we use some kind of code that the computer can interpret. Following table shows a set of codes. The number 0000 is a code for LDA, 0001 for ADD, 0010 for SUB, 1110 for OUT and 1111 for HLT. Since a code tells the computer which operation to perform, it is called Opcode.

Microprocessor & Microcontroller Lab (EE212L)

Page 14

Mnemonic LDA ADD SUB OUT HLT

Opcode 0000 0001 0010 1110 1111

Address 0H 1H 2H 3H 4H 5H

Mnemonics LDA 9H ADD AH ADD BH SUB CH OUT HLT

Example:

The data in memory is given below: Address 6H 7H 8H 9H AH BH CH DH EH FH

Microprocessor & Microcontroller Lab (EE212L)

Data FFH FFH FFH 01H 02H 03H 04H FFH FFH FFH

Page 15

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 03

Implementation of Controller / Sequencer for the SAP-1 and Complete Integration of SAP-1

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature:

Microprocessor & Microcontroller Lab (EE212L)

Page 16

Implementation of Controller/Sequencer and Complete Integration Objectives: Objective of the lab is to implement controller part of the SAP-1.

Resources Required: 1. A computer 2. Proteus V7 or higher

Components Required: 1. 2. 3. 4. 5. 6. 7. 8.

4 bit D-type Register, 74LS173 Quad 2-to-1 Data Selector/Multiplexer, 74LS157 Quad Two-Input NAND Gate, 74LS00 Tri Three-Input NAND Gate, 74LS10 Dual Four-Input NAND Gate, 74LS20 Hex Inverter, 74LS04 Dual J-K Flip Flop, 74LS107 Connecting Wires

(1) (1) (6) (1) (5) (5) (3)

Instruction Decoder: This part of the controller decodes the instruction that are fed by instruction register. A hex inverter produces complements of the Opcode bits, I7 I6 I5 I4. Then the 4-input NAND gates decode the five output signals, LDA, ADD, SUB, OUT and HLT. HLT is the only active low signal, while all others are active high. When the HLT instruction is in the Instruction Register, all bits I7 I6 I5 I4 are 1111 and HLT is low. This signal returns to the single-step clock (you made in Lab-1). In either case that is AUTO or MANUAL, the clock stops and the computer run ends. Ring Counter: The Ring counter, sometimes called the State Counter, consists of three flip flop chips, 74LS107. This counter is reset whenever the Clear-Start button S5 is pressed. The output of the last flip-flop is inverted so that the Q output drives the J input of the first flip-flop. Due to this, T1 output is initially high. The CLK signal drives an active low input; this means that the negative edge of the CLK signal initiates each T state.

Microprocessor & Microcontroller Lab (EE212L)

Page 17

Output of the Ring Counter is: T= T6 T5 T4 T3 T2 T1 At the beginning of the computer run, the ring-word is: T=000001 Successive clock pulses produce ring words: T=000010 T=000100 T=001000 T=010000 T=100000 Then the Ring Counter is reset to 000001 and the cycle repeats. Each ring-word represents one T state. Fig-1 shows the timing pulses out of the Ring Counter. The Microprocessor & Microcontroller Lab (EE212L)

Page 18

initial state T1 starts with a negative clock edge and ends with the next negative clock edge. During this T state the T1 output of the Ring Counter is high. During the next state, T2 is high; the following state T3 is high and so on. As you can see the ring counter produces six T states. Each instruction is fetched and executed during these six T states. Address State The T1 state is called the address state because the address in the PC is transferred to the MAR during this state. During this state, EP and LM are active; all other control bits are inactive. This means that the controller sequencer is sending out a control word of: CON = CP EP LM CE 0 1 0 1

LI EI LA EA 1 1 1 0

SU EU LB LO 0 0 1 1

Increment State During the Increment State T2, only CP is active, causing the PC to increment to the next memory location. CON = CP EP LM CE 1 0 1 1

LI EI LA EA 1 1 1 0

SU EU LB LO 0 0 1 1

Memory State The T3 state is called the memory state because the addressed RAM instruction is transferred from the memory to the Instruction Register. The only active control bits are CE and LI and the word out of the controller is: CON = CP EP LM CE 0 0 1 0

LI EI LA EA 0 1 1 0

SU EU LB LO 0 0 1 1

Fetch Cycle The address, increment and memory states are called the fetch cycle of SAP-1. Execution Cycle The next three states T4 T5 T6 are three states of the execution cycle of SAP-1. The register transfer during this execution depends on a particular instruction being executed. Each instruction has its own control routine.

Microprocessor & Microcontroller Lab (EE212L)

Page 19

Figure-1: T States generated by Ring Counter Control Matrix The LDA, SUB, ADD and OUT signals from the Instruction Decoder drive the control matrix. At the same time the Ring Counter signals T1 to T6 also drive the matrix. The matrix produces CON, a 12-bit micro-instruction that tells the rest of the computer what to do. State T1 T2 T3

CON 5E3H BE3H 263H

Active Bits EP, LM CP CE, LI

The control unit is the key to a computer's automatic operation. The Control unit generates the control words that fetch and execute each instruction. While each instruction is fetched and executed, the computer passes though different T states, or timing states, that is periods during which register contents change. Procedure Connect the circuit as shown in the circuit diagram. Connect I7 I6 I5 I4 to DIP switches on your trainer and give the different opcodes for different instructions. For instance for HLT instruction, opcode is 1111, this means keeping all DIP switches in "Hi" position will generate an active low HLT signal. Similarly you can check for other instructions. Check the signals with the oscilloscope and get your work verified by your lab instructor. You will be graded for this Lab on the output and functionality of your circuit.

Microprocessor & Microcontroller Lab (EE212L)

Page 20

Microprocessor & Microcontroller Lab (EE212L)

Page 21

Fig-2 Instruction Decoder, Ring Counter & Control Matrix

Microprocessor & Microcontroller Lab (EE212L)

Page 22

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 04

Introduction to 8051 micro controller and I/O port programing using LED Interfacing

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature: Microprocessor & Microcontroller Lab (EE212L)

Page 23

Introduction to 8051 micro controller and I/O port programing using LED Interfacing Objectives: 1. 2. 3. 4. 5. 6. 7. 8.

To understand the 89c51 Microcontroller To understand it pin configurations Introduction to Keil (89c51 compiler) and Genius G540 (Programmer / Burner) Introduction to 8051 Development Board To interface LEDs with microcontroller Writing first C code and program microcontroller Running a simple program to blink LEDs Use of Keil debugger

Introduction: AT89C51 is a powerful microcontroller which provides a highly-flexible and costeffective solution to many embedded control applications. It follows the basic architecture and instruction set of Intel’s 8bit, 8051 microcontroller. There are many variants of 8051 like AT89S51, AT89S52 etc. They differ each other in term of flash memory size, number of I/O, number of timers etc. Atmel is one of the leading manufacturers of microcontrollers.

Features of AT89C51 Microcontroller: • • • • • • •

128 bytes of RAM for storing data 4kB Flash code memory 32 I/O (8 x 4) lines for communicating with other devices Two 16-bit timers / counters Five vector two-level interrupt architecture Full duplex serial port, on-chip oscillator and clock circuitry 0 to 24MHz crystal frequency

Pin Configuration: 1–8 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.

10–17 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

Microprocessor & Microcontroller Lab (EE212L)

Page 24

associated with Timer 0 and Timer 1. Pin 16 and Pin 17 are used when working with external memory. 18–19 these pins are used to connect an external crystal, ceramic resonator or oscillator module to the microcontroller. 20

GND. This is the ‘ground’ pin.

21–28 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.

32–39 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).

Introduction to Keil Software: Keil Software provides with software development tools for the 8051 family of microcontrollers. Keil provides following tools for 8051 development: 1. 2. 3. 4.

C51 Optimizing C Cross Compiler A51 Macro Assembler 8051 Utilities (linker, object file converter, library manager) Source-Level Debugger/Simulator

Microprocessor & Microcontroller Lab (EE212L)

Page 25

5.

µVision for Windows Integrated Development Environment

Through Keil, you can write C or assembly language code and compile or assemble it for onward generation of Hex file. Hex file is burned into microcontroller to perform the required operation.

Introduction to Genius G540 Universal Programmer: Genius G540 is a universal programmer. It supports a wide range of different series microcontrollers which includes the Atmel 8051 series microcontrollers as well. It can be connected to the PC using its USB port.

Introduction to 8051 Development Board: All the lab experiments would be carried out on the 8051 Development Board. This board has various on-board modules. Following are the peripheral devices available for the better understanding of 8051 series microcontrollers: 1. 8-bit LED array 2. 4 multiplexed seven segment displays 3. 2x16 LCD 4. Two interrupt sources 5. Telephonic Keyboard 6. DIP switches 7. 8bit Analog to Digital converter 8. Stepper motor drivers 9. DC Motor drive 10. RS232 interface

Microprocessor & Microcontroller Lab (EE212L)

Page 26

I/O port Programming using LED Interfacing Hardware Required: Item  Bread Board  Resistor 10kΩ  Resistor 1kΩ  Crystal Oscillator 11.0592MHz  Power Supply 5V

Qty 01 01 01 01 01

Item  AT89C51 Microcontroller  Capacitor 10uF/16V  LED (any color)  Capacitor 33pF  Connecting Wires

Qty 01 01 01 02 Various

Circuit Diagram: XTAL1 is the crystal oscillator connected between Pin 18 and Pin 19. If you are using a clock source other than crystal oscillator, then the clock will be provided on XTAL1 (Pin 19) and XTAL2 (Pin 18) will remain un-connected. Pin 40 is connected to +5V and Pin 20 is connected to ground to power ON the microcontroller. R1 and C3 make the power ON reset circuitry. When power is switched ON, initially capacitor C3 acts as short circuit and initially +5V appears at Pin9 which resets the microcontroller. When capacitor is completely charged, it acts as open circuit and Pin9 is pulled low by the resistor R1. EA (Pin 31) will always be at high potential to disable the external code memory. We will always use the internal code memory of microcontroller, so this pin will always be connected to high potential throughout the labs.

Code: /* This program continuously toggles the Port1. Each toggle has a delay of one second approximately */ #include void delay (void) // { unsigned int x; for(x=0; x<25000; x++); } void main (void) { P1 = 0x00; while(1)

delay function

// approx 1 second delay

// Make Port1 as output // Forever Loop

Microprocessor & Microcontroller Lab (EE212L)

Page 27

{ P1 = ~P1; delay ();

// // // //

} }

Toggle Port1 call delay function End forever Loop End main

Lab Task: 1. Connect eight LEDs with Port 1 and lit the LEDs in progress bar fashion. Keep the LEDs running like forward and reverse progress bar, as shown in following figure: Hint: Use loops to complete the required task 1s 2s 3s 4s 5s 6s 7s 8s 9s 10s 11s 12s 13s 14s 15s

● ● ● ● ● ● ● ● ● ● ● ● ● ● ●

○ ● ● ● ● ● ● ● ● ● ● ● ● ● ○

○ ○ ● ● ● ● ● ● ● ● ● ● ● ○ ○

○ ○ ○ ● ● ● ● ● ● ● ● ● ○ ○ ○

○ ○ ○ ○ ● ● ● ● ● ● ● ○ ○ ○ ○

○ ○ ○ ○ ○ ● ● ● ● ● ○ ○ ○ ○ ○

○ ○ ○ ○ ○ ○ ● ● ● ○ ○ ○ ○ ○ ○

○ ○ ○ ○ ○ ○ ○ ● ○ ○ ○ ○ ○ ○ ○

2. Connect eight LEDs with Port 2 and lit the LEDs to show prime numbers from 0 to 100.

Microprocessor & Microcontroller Lab (EE212L)

Page 28

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 05

7-Segment Display Interfacing and Programming with 8051 Microcontroller

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature:

Microprocessor & Microcontroller Lab (EE212L)

Page 29

7-Segment Display Interfacing and Programming with 8051 Microcontroller Objectives: 1. Working principle of 7-segment displays 2. Interfacing multiple 7 segments together using multiplexing technique 3. Programming the multiplexed array of 7-segment displays

Introduction: A seven-segment display (SSD), or seven-segment indicator, is a form of electronic display device for displaying decimal numerals that is widely used in digital clocks, electronic meters, and other electronic devices for displaying numerical information. The light emitting diodes in seven segments are arranged as a rectangle as shown in figure. The segments of a 7-segment display are referred to by the letters A to G, where the optional DP decimal point (an "eighth segment") is used for the display of non-integer numbers. In a simple LED package, typically all of the cathodes (negative terminals) or all of the anodes (positive terminals) of the segment LEDs are connected and brought out to a common pin; this is referred to as a "common cathode" or "common anode" device. Hence a 7-segment plus decimal point package will only require nine pins but they usually have more pins due to packaging standards.

Multiplexing: In this experiment we will study the basic multiplexing technique of interfacing an array of four 7-segment displays with AT89C51 microcontroller. Multiplexing is required when we want to interface 3 or 4 or even more such displays with MCUs since it we go for normal way it will require lots of I/O port. So the smart way is multiplexing.

Microprocessor & Microcontroller Lab (EE212L)

Page 30

Multiplexing achieved by tricking our eyes. Only one display is active at a time but we see all of them active. For multiplexing all the displays are connected in parallel such that if you activate any segment, say ‘a’ the ‘a’ segment of all displays glows up. But the trick is that we can switch on and off the “common” line of the displays under MCU control. So if we wish to light up the ‘a’ segment of display 2 we simply switch on display 2 first by applying proper level at the base of its driving transistor as shown in figure. If we like to display the digit say “123” on three displays first we select disp-3 by applying a “low” level at the base of transistor Q1 and output the code of required digit at the data input terminals. Since display 3 is selected “1” is displayed in disp-3 then we wait for some time and select disp-2 and output code of digit “2”. This “2” will be shown in disp-2. Then we select display-1 and output code for digit “3”. If we repeat this step fast enough (not a problem with MCUs!) what we get due to persistence of vision is that we see the number “123” displayed “still” in the display as if all the displays are active simultaneously.

C code: #include //Seven Segment Display used in Common Cathode // // P1.0 = a P1.1 = b // P1.3 = d P1.4 = e // P1.6 = g P1.7 = dot // // a // _____ // f| | b // |__g__|

P1.2 = c P1.5 = f

.

Microprocessor & Microcontroller Lab (EE212L)

Page 31

// e| | c dot // |_____| . // d //________________________________________ // | No. | . g f e d c b a | //_|______|______________________________| // | 0 | 0 0 1 1 1 1 1 1 = 0x3F | // | 1 | 0 0 0 0 0 1 1 0 = 0x06 | // | 2 | 0 1 0 1 1 0 1 1 = 0x5B | // | 3 | 0 1 0 0 1 1 1 1 = 0x4F | // | 4 | 0 1 1 0 0 1 1 0 = 0x66 | // | 5 | 0 1 1 0 1 1 0 1 = 0x6D | // | 6 | 0 1 1 1 1 1 0 1 = 0x7D | // | 7 | 0 0 0 0 0 1 1 1 = 0x07 | // | 8 | 0 1 1 1 1 1 1 1 = 0x7F | // | 9 | 1 0 0 1 1 1 1 1 = 0x6F | //_|______|______________________________| void Display(unsigned char); unsigned char Seven_Segment[]={0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F}; void main(void) { unsigned char i = 0; while(1) { Display(i); i++; if(i > 99) i = 0; } } void delay(void) { unsigned int x; for(x=0; x<100; x++); } void Display(unsigned char n) { unsigned char units, tens; unsigned int x; tens = n/10; units = n%10; for(x = 0; x<500; x++) { P3 = 0x01; P1 = Seven_Segment[units]; delay(); P3 = 0x02; P1 = Seven_Segment[tens]; delay(); } Microprocessor & Microcontroller Lab (EE212L)

Page 32

}

Simulation:

Lab Tasks: 1. Show Fibonacci series from 00 to 99 on seven segment display. 2. Use three seven segment displays to display digits starting from 000 up to 999 with a delay of 0.5 seconds approximately. 3. Show hexadecimal numbers from 00 to FF on two seven segment display.

Microprocessor & Microcontroller Lab (EE212L)

Page 33

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 06

Keypad Interfacing with 8051 Microcontroller

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature:

Microprocessor & Microcontroller Lab (EE212L)

Page 34

Keypad Interfacing with 8051 Microcontroller Objectives: 1- Learn that how to interface keypad with AT89C51 microcontroller 2- Code AT89C51 to detect the pressed key and show its BCD on LEDs

Key Pad: Keypad is organized as a matrix of switches in rows and column. This lab uses a 4 x 3 matrix keypad. Different types of Keypads available are Phonetic, Calculator and Hex Keypad. In a keypad, there are physical switches for each digit / letter. Phonetic keypad has 0 to 9 digits and two more buttons are * and #. Multiplexing technique is used to access the 12 keys with only 7 I/O pins. There are total four rows and three columns. All the rows are connected to internally pulled-up port (Port 2) which means that if there is no signal applied on the rows, high signal would be there. By using polling method, we keep sending low to the rows one by one and each time we send a low signal to a row, we check all the three columns for a low signal. With the combination of low signal at a row and a low signal at a column, we can determine that which button is pressed. For example, if button 6 is presses. Microcontroller will send a low to Col 1, no low signal will be received on Row 1 to Row 4. Then it will send low to Col 2, again no low signal will be received on Row 1 to Row 4. Now it will send low to Col 3, then a low signal will be received on Row 2 which means that the button 6 is pressed.

C code: /* This program is written to interface the Keypad with 89C51. When a button is pressed, the BCD of the pressed digit is shown on Port 1 */

Microprocessor & Microcontroller Lab (EE212L)

Page 35

#include /*********************************************************************/ sbit colm1=P2^4; sbit colm2=P2^5; sbit colm3=P2^6; sbit row1 =P2^0; sbit row2 =P2^1; sbit row3 =P2^2; sbit row4 =P2^3; /*****************Check Colum 1**********************************/ void func_colm1() { row1=row2=row3=row4=1; row1=0; if(colm1==0) P1=1; row1=1; row2=0; if(colm1==0) P1=4; row2=1 row3=0; if(colm1==0) P1=7; row3=1; row4=0; if(colm1==0); row4=1; } /*************************Check Colum 2***************************/ void func_colm2() { row1=row2=row3=row4=1; row1=0; if(colm2==0) P1=2; row1=1; row2=0; if(colm2==0) P1=5; row2=1; row3=0; if(colm2==0) P1=8; row3=1; row4=0; if(colm2==0) P1=0; row4=1; } /*********************Check Colum 3*******************************/ void func_colm3() { row1=row2=row3=row4=1; row1=0; if(colm3==0) P1=3; row1=1; row2=0; if(colm3==0) P1=6; row2=1; row3=0; if(colm3==0) P1=9; Microprocessor & Microcontroller Lab (EE212L)

Page 36

row3=1; row4=0; if(colm3==0); row4=1; } void main(void) { P1 = 0; colm1=colm2=colm3=1; while(1) { row1=row2=row3=row4=0; if(colm1 == 0) func_colm1(); else if(colm2 == 0) func_colm2(); else if(colm3 == 0) func_colm3(); } }

// Make Port1 as Output // input port2

// Initially low logic on all Rows // Check if a button from Col 1 is pressed

// Check if a button from Col 2 is pressed

// Check if a button from Col 3 is pressed

Lab Task: Use # button to increment the value displayed on the LEDs and by pressing the * key, value displayed on the LEDs should be decremented.

Microprocessor & Microcontroller Lab (EE212L)

Page 37

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 07

LCD Interfacing with 8051 Microcontroller

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature:

Microprocessor & Microcontroller Lab (EE212L)

Page 38

LCD Interfacing with 8051 Microcontroller Objectives: 1. To interface the LCD with 8051 in 8 bit mode 2. Code 8051 for display of alphabets on LCD

Introduction: The LCD available on the 8051 development board is 2x16 LCD which means that this LCD can display 16 characters in a line and there are 2 lines. So maximum 32 characters can be displayed on the 16x2 LCD at a time. Each character is displayed in a 5x7 pixel matrix. There are two registers in an LCD:

1) Data Register: Data register contains the character to be displayed on the LCD. Data is the ASCII value of the character to be displayed

2) Command / Instruction Register: Stores the command / instructions given to the LCD. A command or instruction performs the predefined task for the LCD. Some of the predefined tasks are clearing the screen, Moving / setting cursor, scrolling the display etc. Some of the commands / instructions are given in the Table 2. Table 2: Pin Description of 16x2 LCD

PIN

SYMBOL

I/O

DESCRIPTION

1 2 3

Vss Vcc Vdd

-

4

RS

I

5

R/W

I

6

E

I

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)

15

LED+

-

Backlight Vcc

16

LED-

-

Backlight GND 0V

Power supply (GND) Power supply (+5V) Contrast Adjustment 0 = Select command register 1 = Select data register 0 = Write to LCD 1 = Read from LCD A high to low pulse (minimum 450ns wide) is given when data is sent to data pins

Microprocessor & Microcontroller Lab (EE212L)

+5V

Page 39

Pin No. 4, RS: Register Select (RS) Pin of LCD is used to select between Command Register and Data Register. If RS is set, Data Register is selected and if RS is zero, Command Register is selected. Pin No. 5, R/W: Read / Write (R/W) Pin of LCD is used to select whether to read from LCD or write something on the LCD. IF R/W pin is set, Read operation is performed. IF R/W is zero, a command / data can be written on the LCD. Pin No. 6, E: Enable (E) Pin of LCD is used to enable the LCD. When this bit goes from low to high, write operation is performed. To send data on the LCD, data is first written to the data pins with R/W = 0 (to specify the write operation) and RS = 1 (to select the data register). A high to low pulse is given at E pin when data is sent. Each write operation is performed on the positive edge of the Enable signal. To send a command on the LCD, a particular command is first specified to the data pins with R/W = 0 (to specify the write operation) and RS = 0 (to select the command register). A high to low pulse is given at E pin when data is sent. Pin No. 7-14, D0-D7: There are the data bits. An ASCII equivalent of the character to be displayed or a command required to be executed by the LCD is sent on these 8-data bits. Data pin8 (D7) of the LCD is busy flag and is read when R/W = 1 & RS = 0. When busy flag=1, it means that LCD is not ready to accept data since it is busy with the internal operations. Therefore before passing any data to LCD, its command register should be read and busy flag should be checked. Table 2: Command list of 16x2 LCD

S No.

Command Description

Command

1

Function Set: 8-bit, 1 Line, 5x7 Dots

0x30

2

Function Set: 8-bit, 2 Line, 5x7 Dots

0x38

3

Function Set: 4-bit, 1 Line, 5x7 Dots

0x20

4

Function Set: 4-bit, 2 Line, 5x7 Dots

0x28

5

Display off Cursor off (clearing display without clearing DDRAM content)

0x08

6

Display on Cursor on

0x0E

7

Display on Cursor off

0x0C

8

Display on Cursor blinking

0x0F

9

Shift entire display left

0x18

10

Shift entire display right

0x1C

11

Move cursor left by one character

0x10

Microprocessor & Microcontroller Lab (EE212L)

Page 40

12

Move cursor right by one character

0x14

13

Clear Display (also clear DDRAM content)

0x01

14

Return Home

0x02

15 16

During write operation only shift cursor left (decrement cursor) During write operation only shift cursor right (increment cursor)

0x04 0x06

17

Force the cursor at first line, position zero

0x80

18

Force the cursor at second line, position zero

0xC0

Fig 1: 8051 Development Board - Layout of LCD Interface and 8051 Input Output Ports

C code: //This program displays the alphabet from A to Z on two lines of LCD #include sbit sbit sbit sbit char

RS=P1^0; RW=P1^1; E=P1^2; BF=P2^7; data1;

int ready() { while (BF); return 1; }

//Register Select Pin on P1^0 //Read or Write Select Pin on P1^1 //Enable Select Pin on P1^2 //Busy Flag on MSB of Data Port

//For checking that the LCD is ready or not?

//Ready Function Ends

Microprocessor & Microcontroller Lab (EE212L)

Page 41

void delay(unsigned int z) //For delay (Starts) { int x, y; for(x = 0; x < z; x++) for(y = 0; y <= 1000; y++); } //Delay Function Ends int LCD_Run_Command(unsigned char COMMAND) { if(ready()) { P2 = COMMAND; RS = 0; delay(1); RW = 0; delay(1); E = 0; delay(1); E = 1; delay(1); } return 1; } void LCD_Show(unsigned char CHARACTER) { if(ready()) //if LCD internal controller is not busy { P2 = CHARACTER; RS = 1; delay(1); RW = 0; delay(1); E = 0; delay(1); E = 1; delay(1); } } void LCD_Initialize() { LCD_Run_Command(0x38); LCD_Run_Command(0x0E); LCD_Run_Command(0x01); position LCD_Run_Command(0x06); text)

// 8 data lines, two lines, Font 5x7. // Display=ON, Curson=ON, Cursor Blinking=ON // Clear display and return cursor to the home // During read/write operation only cursor (not // should move right

} void main(void) { while(1) { LCD_Initialize(); Microprocessor & Microcontroller Lab (EE212L)

Page 42

for(data1 = 'A'; data1 <= 'N'; data1++) LCD_Show(data1); //Display characters A to N on LCD Line 1 LCD_Run_Command(0xC0); // Cursor at Line 2, Position 0 for(data1 = 'O'; data1 <= 'Z'; data1++) LCD_Show(data1); //Display character O to Z on LCD Line 2 delay(50); } }

Simulation:

Lab Task: 1. At the center of first line of LCD, show “GROUP No. XX” where XX is your group number. At the center of second line, display the first name of your group leader. 2. Use two push buttons to move cursor from right to left and left to right respectively and two push buttons to move data from right to left and left to right respectively.

Microprocessor & Microcontroller Lab (EE212L)

Page 43

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 08

Analog to Digital Converter (ADC) Interfacing with 8051 Microcontroller

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature:

Microprocessor & Microcontroller Lab (EE212L)

Page 44

Analog to Digital Converter (ADC) Interfacing with 8051 Microcontroller Objectives: 1- Learn that how to interface ADC0804 with AT89C51 microcontroller 2- Program AT89C51 and use ADC0804 to convert an analog input voltage to a digital value and show the converted digital value of Port 3

Analog to Digital Converter (ADC): We need an analog-to-digital converter to translate the analog signals to digital numbers, so microcontroller can read them. ADCs find huge application as an intermediate device to convert the signals from analog to digital form. These digital signals are used for further processing by the digital processors. Various sensors like temperature, pressure, force etc. convert the physical characteristics into electrical signals that are analog in nature.

ADC0804 Features:     

80C48 Bus compatible, no interfacing circuitry required Conversion time <100us Differential analog inputs On-chip clock generator Analog input voltage range 0 to 5V

ADC0804 is a very commonly used 8-bit analog to digital convertor. It is a single channel IC, i.e., it can take only one analog signal as input. The digital outputs vary from 0 to a maximum of 255. The step size can be adjusted by setting the reference voltage at pin9. When this pin is not connected, the default reference voltage is the operating voltage, i.e., Vcc. The step size can be calculated from the following formula:

StepSize

Re ferenceVoltage 5V   19.53mV 256 28

For every 19.53mV rise in the analog input, the output varies by 1 unit. To set a particular voltage level as the reference value, this pin is connected to half the voltage. For example, to set a reference of 4V (Vref), Pin9 is connected to 2V (Vref / 2), thereby reducing the step size to 15.62mV (4V/256). ADC0804 needs a clock to operate. The time taken to convert the analog value to digital value is dependent on this clock source. An external clock can be given at the Clock IN (pin 4). ADC 0804 also has an inbuilt clock which can be used in absence of external clock. A suitable RC circuit is connected between the Clock IN (Pin 4) and Clock R (Pin 19) pins to use the internal clock. Following table shows a brief description / function of pins of ADC0804: Microprocessor & Microcontroller Lab (EE212L)

Page 45

Fig 1: ADC0804, typical application schematic

Pin # 1 2 3

Function This is an active low pin and used to activate the ADC0804 Input pin; High to low pulse brings the data from internal registers to the output pins after conversion This is an input pin and active low. This is used to instruct the ADC to start the conversion process. If CS=0 and WR makes a low to high transition, the ADC starts the conversion process

Name Chip select Read Write

4

Clock Input pin; to give external clock.

Clock IN

5

Output pin; Goes low when conversion is complete

Interrupt

6

Analog non-inverting input

Vin(+)

7

Analog inverting Input; normally ground

Vin(-)

8

Ground(0V)

9

Input pin; sets the reference voltage for analog input

10

Ground(0V)

Digital Ground

8 bit digital output pins

D7-D0

19

Used with Clock IN pin when internal clock source is used

Clock R

20

Supply voltage; 5V

11-18

Analog Ground Vref/2

Vcc

Operation of ADC0804: On the low to high transition of the WR input, the internal register latches and the shiftregister stages are reset, and the INTR output will be set high. As long as the CS input and WR input remain low, the A/D will remain in a reset state. Conversion will start from 1 to 8 clock periods after at least one of these inputs makes a low-to-high transition. After the requisite number of clock pulses to complete the conversion, the INTR pin will make a high-to-low transition. A RD operation (with CS low) will clear the INTR line high again.

Microprocessor & Microcontroller Lab (EE212L)

Page 46

C code: /*This program converts analog voltage at Pin 6 of ADC0804 and shows the converted digital value of Port 3 */ #include #define Read_Data #define Show_Data sbit Write = P1^1; sbit Read = P1^0; sbit Intr

= P1^2;

P2 // Input port to read the values of ADC P3 // Output port, connected to LED's. // Write pin. Start the conversion // Read pin. Brings data from internal register to output // pins of ADC // Interrupt pin. End of Conversion signal. It goes low // when conversion is done

void delay(unsigned int); void ADC(void); void main() { Read_Data = 0xFF; Show_Data = 0x00; while(1) { ADC(); } }

// Port 2 as input // Port 3 as output

void delay(unsigned int ms ) { unsigned int i,j ; for(i=0;i<ms;i++) for(j=0; j<113; j++); } void ADC(void) // Port3 { Read = 1; // Write = 0; // delay(1); Write = 1; while(Intr == 1); conversion Read = 0;

// This function generates msec delay

Function to read the values from ADC and display on the

Disable Read operation A low to high pulse on write pin starts conversion

// wait here until INTR pin is one which indicates // is done // A high to low pulse on RD pin bring data from ADC to

its // output pins Show_Data = Read_Data; // Read digital value from Port 2 and show on Port 3 delay(1); }

Microprocessor & Microcontroller Lab (EE212L)

Page 47

Schematic of interfacing ADC0804 with 89C51:

8051 Development Board wiring diagram:

Lab Task: When input voltage > 2, turn all LEDs ON, otherwise, keep all LEDs OFF

Microprocessor & Microcontroller Lab (EE212L)

Page 48

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 09

Timer / Counter Mode Programming with 8051 Microcontroller

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature:

Microprocessor & Microcontroller Lab (EE212L)

Page 49

Timer / Counter Mode Programming with 8051 Microcontroller Objectives: 1. 2. 3. 4. 5. 6.

To understand the modes and functionality of timers of 8051 To learn exact delay generation using timers To generate square wave of specified frequency using timers To understand the counter mode functionality of timers of 8051 To learn how to use the counters to count the external events Write a program to count the external events on Timer 0 and display it on 8 LEDs

Timers: Introduction: The 8051 has two 16-bit timers/counters, i-e T/C0 and T/C1. Timers are used to generate a time delay whereas counters are used to count events happening outside the microcontroller. In this lab we will learn to configure the timers of 8051 for exact delay generation.

Timer 0 and Timer 1 Registers: Both timer 0 and timer 1 are 16-bit timers. Each 16-bit timer is accessed as two separate registers of low byte and high byte. D15

D14

D13

D12

D11

D10

D9

D8

D7

D6

D5

D4

TH0

D3

D2

D1

D0

D2

D1

D0

TL0

Timer 0 Register D15

D14

D13

D12

D11

D10

D9

D8

D7

D6

D5

TH1

D4

D3

TL1

Timer 1 Register

TMOD (timer mode) Register: 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. GATE1

C/T1

T1M1

T1M0

GATE0

C/T0

T0M1

T0M0

TMOD Register The individual bits of TMOD have the following functions: 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. 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. T1M1: Timer mode bit (see table below) T1M0: Timer mode bit (see table below) GATE0: When this bit is set the timer will only run when INT0 (P3.2) is high. When this bit is clear, the timer will run regardless of the state of INT0. C/T0: When this bit is set the timer will count events on T0 (P3.4). When this bit is clear the timer will be incremented every machine cycle. T0M1: Timer mode bit (see table below) Microprocessor & Microcontroller Lab (EE212L)

Page 50

T0M0:

Timer mode bit (see table below)

The combinations of 4-bits of TMOD SFR (T1M1, T1M0, and T0M & T0M0) specify timer’s mode of operation. The modes of operation are: TxM1 0 0 1 1

TxM0 0 1 0 1

Timer Mode 0 1 2 3

Description of Mode 13-bit Timer 16-bit Timer 8-bit auto-reload Split timer mode

TCON Register: The TCON is a bit addressable special function register that controls the two timers and provides valuable information about them. The TCON SFR has the following structure: TF1

TR1

TF0

TR0

IE1

IT1

IE0

IT0

TCON Register The individual bits of TMOD have the following functions: TF1: over). TR1: TF0: TR0: IE1:

IT1:

IE0:

IT0:

Timer 1 Overflow: This bit is set by the microcontroller when Timer 1 overflows (timer rolls Timer 1 Run: When this bit is set Timer 1 is turned on. When this bit is clear Timer 1 is off. Timer 0 Overflow: This bit is set by the microcontroller when Timer 0 overflows. Timer 0 Run: When this bit is set Timer 0 is turned on. When this bit is clear Timer 0 is off. 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. 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. 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. 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 don’t have anything to do with timers. These are related to Interrupts.

Timer’s Clock Frequency Relationship: Relation between timer’s clock and XTAL frequency is given by: F (timer’s clock frequency) T (time period)

= XTAL Frequency / 12 =1/F

Steps to program timer 1 in 16-bit mode: 1. 2. 3. 4. 5. 6. 7.

Load the desired value in TMOD Register, specifying timer and its mode selection Load timer registers TH1 and TL1 with initial count Start timer through program by setting TR1 of TCON Register to 1 Monitor timer flag TF1 until it sets to 1 Stop the timer Clear the TF flag for next round Loop through step 2 by loading TH1 and TL1

Microprocessor & Microcontroller Lab (EE212L)

Page 51

C code: /* The following program generates a square wave with a clock frequency of about 2 KHz at P1^7 with a crystal of 12MHz */ #include sbit mybit = P1^7; void main(void) { TMOD = 0x10;

while(1) { TL1 = 0x10; TH1 = 0xFF;

// Timer 1, mode 1 (16 BIT )timer // GATE1=0; C/T1 =0; T1M1=0; T1M0=1; // GATE0=0; C/T0 =0; T0M1=0; T0M0=0;

// // // TR1 = 1; // while(!TF1); // TR1 = 0; // mybit = ~mybit; // TF1 = 0; // //

initial values FF10 = 65296, 16bitmax value = 65536 65536-65296 = 240, Start Timer 1 Wait until Timer1 overflow occurs Stop Timer 1 Complement P1^7. TF1 = Timer 1 Overflow. This bit is set by the microcontroller when Timer 1 overflows.

} }

Simulation:

Counters: Introduction: The 8051 has two 16-bit timers which can also be used as two independent counters. Counter are used to count the external events / pulses occur on the Pin T0 (P3.4) and T1 (P3.5) of the Counter0 and Counter1 respectively. So to use timers as event counters we need to provide pulses from outside the chip instead of using frequency of the crystal as the clock source. Microprocessor & Microcontroller Lab (EE212L)

Page 52

Timer/Counter Mode 2: 8-Bit (Auto-Reload)

Configuring Timers as Counters: We discussed the TMOD and TCON SFRs used to control the modes of operation of both the timers in previous Lab. Now we will learn to configure the timers of 8051 as counters, using the same SFRs. GATE1

C/T1

T1M1

T1M0

GATE0

C/T0

T0M1

T0M0

TMOD Register The individual bits of TMOD have the following functions: 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. C/T1: will

When this bit is set the timer will count events on T1 (P3.5). When this bit is clear the timer be Incremented every machine cycle.

T1M1:

Timer mode bit (see table below)

T1M0:

Timer mode bit (see table below)

Please Note: The lower nibble reserves same functions but for timer-0.

TxM1

TxM0

0 0 1 1

0 1 0 1

Timer Mode 0 1 2 3

Description of Mode 13-bit Timer 16-bit Timer 8-bit auto-reload Split timer mode

TCON Register: The TCON is a bit addressable special function register that controls the two timers and provides valuable information about them. The TCON SFR has the following structure: TF1

TR1

TF0

TR0

IE1

IT1

IE0

IT0

TCON Register The individual bits of TMOD have the following functions: TF1: over). TR1: TF0: TR0:

Timer 1 Overflow. This bit is set by the microcontroller when Timer 1 overflows (timer rolls Timer 1 Run. When this bit is set Timer 1 is turned on. When this bit is clear Timer 1 is off. Timer 0 Overflow. This bit is set by the microcontroller when Timer 0 overflows. Timer 0 Run. When this bit is set Timer 0 is turned on. When this bit is clear Timer 0 is off.

Please Note: The lower 4 bits (bit0 to bit3) of the TCON register don’t have anything to do with timers. These are related to Interrupts. Microprocessor & Microcontroller Lab (EE212L)

Page 53

Steps to Program Timer 1 as a Counter: 1. 2. 3. 4. 5. 6. 7. 8.

Load the desired value in TMOD Register, specifying counter and its mode. Load timer registers TH1 and TL1 with initial counts. Connect external frequency source to T1 (P3.5). Start counter through program by setting TR1 of TCON Register to 1. Monitor timer flag TF1 until it sets to 1. Stop the counter. Clear the TF flag for next round. Loop through step 2 by loading TH1 and TL1.

C code: /* The following program configures 8051 as an 8-bit (auto-reload) counter. Enables it to count events on its hardware pin P3^5 and displays the count on port-1 */ #include void main(void) { T1=1; TMOD = 0x60; TL1 = 0x00; TH1 = 0x00; while(1) { TR1 = 1; while(!TF1) { P1=TL1; } TR1 = 0; TF1 = 0;

// Make T1(P3.5) an input. // Timer 1, mode 2 (8 BIT )counter. // GATE1=0; C/T1 =1; M10=1; M00=0. //initial value to be loaded to TL1. //value to be assigned to TL1 upon roll-over.

// Start Timer 1.

// Pass contents of TL1 to PORT-1.

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

} }

Microprocessor & Microcontroller Lab (EE212L)

Page 54

Simulation:

Lab Task: 1. Generate a square waveform of frequency 𝐹 Hz on Port 1^0. Where,

𝐹=

𝑆𝑢𝑚 𝑜𝑓 𝑅𝑒𝑔# 𝑜𝑓 𝑆𝑡𝑢𝑑𝑒𝑛𝑡𝑠 𝑖𝑛 𝑔𝑟𝑜𝑢𝑝 𝑁𝑜. 𝑜𝑓 𝑆𝑡𝑢𝑑𝑒𝑛𝑡𝑠 𝑖𝑛 𝑔𝑟𝑜𝑢𝑝

2. Generate a square wave of 𝐹 Hz using Timer 0 on Port 1.0. Feed the generated signal to Counter 1 and display the contents of TL1 on the on-board LEDs. Where,

𝐹=

𝑆𝑢𝑚 𝑜𝑓 𝑅𝑒𝑔# 𝑜𝑓 𝑆𝑡𝑢𝑑𝑒𝑛𝑡𝑠 𝑖𝑛 𝑔𝑟𝑜𝑢𝑝 100 × 𝑁𝑜. 𝑜𝑓 𝑆𝑡𝑢𝑑𝑒𝑛𝑡𝑠 𝑖𝑛 𝑔𝑟𝑜𝑢𝑝

3. A sensor attached to P3.4 is sensing the persons entering premises. Use counter 0 to count the number of persons walking in a room. Persons leaving the premises are monitored by sensor at P3.5. Use Counter 1 to count the number of persons leaving the premises. Show entering and leaving numbers on P2 and P3 respectively.

Microprocessor & Microcontroller Lab (EE212L)

Page 55

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 10

Serial Communication between PC and 8051 Microcontroller

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature:

Microprocessor & Microcontroller Lab (EE212L)

Page 56

Serial Communication between PC & 8051 Microcontroller Objectives: 1- To understand the USART of 8051 and its interfacing with PC 2- Send a character to Microcontroller through serial port and receive it back.

MAX 232 – Level Converter IC: The serial port of computer sends/receives data serially at logic levels between -12 to +12V. 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. Pin # 1 2 3 4 5 6 7 8 9

Signal CD RxD TxD DTR SG DSR RTS CTS RI

Description Carrier Detect Receive Data Transmit Data Data Terminal Ready Signal Ground Data Set Ready Request to Send Clear to Send Ring Indicator

DB9 Male (Front View)

DB9 Female (Front View)

Serial Control (SCON) SFR (Bit Addressable) Bit#

Name

Description

7

SM0

Serial port mode bit 0

6

SM1

Serial port mode bit 1

5

SM2

Multiprocessor Communications Enable (explained later)

4

REN

Receiver Enable. This bit must be set in order to receive characters

3

TB8

Transmit bit 8. The 9th bit to transmit in mode 2 and 3

2

RB8

Receive bit 8. The 9th bit received in mode 2 and 3

1

TI

Transmit Flag. Set when a byte has been completely transmitted

0

RI

Receive Flag. Set when a byte has been completely received

Microprocessor & Microcontroller Lab (EE212L)

Page 57

Mode

SM0

SM1

Explanation

Baud Rate

0

0

0

8-bit Shift Register

Oscillator / 12

1

0

1

8-bit UART

Set by Timer 1 (*)

2

1

0

9-bit UART

Oscillator / 64 (*)

3

1

1

9-bit UART

Set by Timer 1 (*)

Following table shows some standard baud rates used for serial communication. Right most column shows the value of higher byte of timer 1, to generate the respective baud rate. Baud Rate 9600 4800 2400 1200

Crystal Freq 11.0592 MHz 11.0592 MHz 11.0592 MHz 11.0592 MHz

TH1 decimal -3 -6 -12 -24

TH1 Hex FD FA F4 E8

To calculate the value of TH1 for a required baud rate, following formula can also be used:

We can double the Baud Rate by setting high the SMOD (LSB, D7) bit of PCON register. When 8051 is powered up, SMOD bit is zero so Baud Rate is generated on normal speed.

Steps to receive a character through UART of 8051: 1. Configure SCON SFR to Mode 1 and enable the reception through REN bit. 2. Configure Timer 1 to 8 bit auto-reload mode by assigning appropriate value to TMOD SFR 3. Load TH1 and TL1 with a value given in theTH1 Hex column of above table for a required baud rate generation. 4. Set ES and EA bits in IE SFR to enable serial port and global interrupts 5. Start the Timer 1 by setting TR1 bit of TCON register. 6. Reset the RI bit of SCON SFR 7. Check for RI flag. 8. When RI goes up, copy the received byte from SBUF register and move it to a safe location. 9. Now reset the RI flag to enable reception of another byte.

Steps to transmit a character from UART of 8051: 1. There is no need to configure the serial port again from step 1 to 5. These steps are required to be configured only one time. 2. Reset TI flag of SCON SFR

Microprocessor & Microcontroller Lab (EE212L)

Page 58

3. Put the character in SBUF for start of transmission. When a character is copied into SBUF, transmission is started immediately. 4. Wait until TI flag is raised, which indicates that complete byte has been transmitted. 5. Now reset the TI flag and repeat the step 3 to transmit another byte. Steps to configure the PC for serial communication using RS232: Latest PCs / Laptops do not contain the serial ports. For serial communication on these PCs, we can use the USB to Serial converter which is easily available in the market. All you need to do is to attach the USB to serial converter to the serial port of your PC and the other end of converter cable can be used as serial interface. Generally, Hyper Terminal is the software used for serial communication which is not available in the Windows 7 and Windows 8. You can download the free Hyper Terminal from: http://files.digitizor.com/wp-content/uploads/2009/08/hyperterminal1.zip Make sure you keep the files hypertrm.dll and hypertrm.exe in the same folder. Now you can launch the HyperTerminal client by double clicking the hypertrm.exe. After running this file, Location Information window will appear. You can cancel this windows and proceed. Next, Connection Description windows will appear:

Enter new connection name and press OK. Now, Connect To window will appear. Here, you should select COM1 (or your available COM Port number) in Connect Using field and press OK

Microprocessor & Microcontroller Lab (EE212L)

Page 59

In the following window, select the baud rate (Bits per second), Data bits, Parity, Stop Bit and Flow control as per the settings done while programming the USART of 8051. Normally, we keep the flow control None. After pressing OK, your connection would be established. Now you can transmit or receive from PC to microcontroller or from microcontroller to PC.

At this stage, when you will type a letter on the hyper terminal, it will not be shown. You can see your typed character by navigatiNG to the following setting: File => Properties => Setting => ASCII Setup => and there you can enable the option of “Echo typed characters locally” by checking the check box.

Microprocessor & Microcontroller Lab (EE212L)

Page 60

C code: /*============================================================================ === This program receives a character from serial port, displays the ASCII of received character to Port 2. Increments the same character and transmits the result to serial port and Port 1. ============================================================================== =*/ // XTAL frequency 11.0592MHz // Baud rate = 9600 #include unsigned char Recv; void ISR_serial(void) interrupt 4 { if(RI==1) // If a character is received by serial port { Recv = SBUF; // move received character from serial buffer P2 = Recv; // Send received character to Port2 SBUF = Recv+1; // Increment received character and Transmit on serial port P1 = Recv+1; // Display incremented character on Port 1 RI = 0; // Clear Receive flag TI = 0; // Clear Transmit flag } } void main(void) { TMOD = 0x20; TH1 = 0xFD; TL1 = 0xFD; SCON = 0x50; ES = 1; EA = 1; TR1 = 1; TI = 0; RI = 0; P1 = 0; P2 = 0; while(1);

// // // // // // // // // // //

8 Bit auto-reload mode on Timer 1 Initialize TH1 for 9600 Baud rate Initialize TL1 for 9600 Baud rate Mode 1, 8-bit, through Timer 1, Enable Reception Enable serial Interrupt Enable Global Interrupt Start Time 1 Clear Transmit Flag Clear Receive Flag Initialized port 1 Initialized port 2

// Forever loop

}

Microprocessor & Microcontroller Lab (EE212L)

Page 61

Simulation:

Figure 1 – Circuit Diagram

Lab Task: Using UART of 8051, receive your registration number from PC and send back your group number. Configure the baud rate 19200 using crystal oscillator of 11.0592MHz

Microprocessor & Microcontroller Lab (EE212L)

Page 62

International Islamic University Islamabad Microprocessors & Microcontroller Lab

EXPERIMENT # 11

Interrupt Based Programming with 8051 Microcontroller

Name of Student: Roll No.: Date of Experiment:

Marks obtained: Remarks: Instructor’s Signature:

Microprocessor & Microcontroller Lab (EE212L)

Page 63

Interrupt Based Programming with 8051 Microcontroller Objectives: 1- To differentiate between polling and interrupt based programming 2- To learn using interrupts in 8051 3- Code for handling multiple tasks simultaneously

Introduction: There are two methods by which a microcontroller can serve a device 1- Polling: In polling, microcontroller continuously monitors the status of device, if the status is met, microcontroller serves. 2- Interrupt: In interrupt method, a device sends an interrupt signal to microcontroller. Upon reception of interrupt, microcontroller stops its working and serves the device. Program executed after receiving an interrupt is called Interrupt Service Routine (ISR). As the name implies, an interrupt is some event which interrupts normal program execution. However, interrupts give us a mechanism to "put on hold" the normal program flow, execute a subroutine, and then resume normal program flow as if we had never left it. This subroutine, called an interrupt handler, is only executed when a certain event (interrupt) occurs. The event may be one of the timers "overflowing," receiving a character via the serial port, transmitting a character via the serial port, or one of two "external events." In 8051, following events will cause an interrupt:  Timer 0 Overflow  Timer 1 Overflow  Reception/Transmission of Serial Character  External Event 0  External Event 1 We need to be able to distinguish between various interrupts and executing different code depending on what interrupt was triggered. This is accomplished by jumping to a fixed address when a given interrupt occurs. Each interrupt use unique identifier known as interrupt number. Interrupt

Flag

External 0 Timer 0 External 1 Timer 1 Serial

IE0 TF0 IE1 TF1 RI / TI

Interrupt Handler Address 0003h 000Bh 0013h 001Bh 0023h

Number/ID 0 1 2 3 4

Interrupt Enable (IE) Register:

Microprocessor & Microcontroller Lab (EE212L)

Page 64

Symbol Bit#

Function

EA

7

Disable all interrupts. If EA=0, no interrupt will be acknowledged. If EA = 1, each interrupt source is individually enabled or disabled by setting of clearing its enable pin

-

6

Reserved

-

5

Reserved

ES

4

Enables or disables Serial Port interrupt. If ES = 0, the Serial Port interrupt is disabled

ET1

3

Enables or disables the Timer 1 Overflow interrupt. If ET1 = 0, the Timer 1 Overflow interrupt is disabled

EX1

2

Enables or disables External Interrupt 1. If EX1 = 0, External Interrupt 1 is disabled.

ET0

1

Enables or disables the Timer 0 Overflow interrupt. If ET0 = 0, the Timer 0 Overflow interrupt is disabled

EX0

0

Enables or disables External Interrupt 0. If EX0 = 0, External Interrupt 0 is disabled.

Interrupt Priority (IP) Register (bit addressable):

Bit Name

Bit#

Function

7

Reserved

6

Reserved

5

Reserved

PS

4

Defines the Serial Port interrupt priority level. PS = 1 programs it to the higher priority level

PT1

3

Defines the Timer 1 interrupt priority level. PT1 = 1 programs it to the higher priority level

PX1

2

Defines the External Interrupt 1 priority level. PX1 = 1 programs it to the higher priority level

PT0

1

Defines the Timer 0 Interrupt priority level. PT0 = 1 programs it to the higher priority level

PX0

0

Defines the External Interrupt 0 priority level. PX0 = 1 programs it to the higher priority level

An interrupt may either be of low (0) priority or high (1) priority. When considering interrupt priorities, the following rules apply:    

Nothing can interrupt a high-priority interrupt--not even another high priority interrupt. A high-priority interrupt may interrupt a low-priority interrupt. A low-priority interrupt may only occur if no other interrupt is already executing. If two interrupts occur at the same time, the interrupt with higher priority will execute first. If both interrupts are of the same priority the interrupt which is serviced first by polling sequence will be executed first.

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

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

Microprocessor & Microcontroller Lab (EE212L)

Page 65

An interrupt ends when your program executes the RETI (Return from Interrupt) instruction. When the RETI instruction is executed the following actions are taken by the microcontroller:  Two bytes are popped off the stack into the Program Counter to restore normal program execution.  Interrupt status is restored to its pre-interrupt status.

C code: #include sbit Toggle = P3^0; unsigned char ex0_isr_counter = 0; unsigned char ex1_isr_counter = 0; void ex0_isr (void) interrupt 0 // External Interrupt 0 ISR { ex0_isr_counter++; // Increment the count P1 = ex0_isr_counter; // Place value of Port 1 } void ex1_isr (void) interrupt 2 // External Interrupt 1 ISR { ex1_isr_counter++; // Increment the count P2 = ex1_isr_counter; // Place value of Port 2 } void T1_isr (void) interrupt 3 { TR1 = 0; Toggle = ~Toggle; TF1 = 0; TR1 = 1; }

// Timer 1 overflow Interrupt ISR // // // //

Stop Timer 1 Toggle the bit Clear Timer1 overflow flag Start Timer 1 again

void main (void) { P1 = 0; // Initialize ports P2 = 0; /*-----------------------------------------------------------------------------Configure INT0 & INT1 (external interrupt 0 & 1) to generate an interrupt on the falling-edge of /INT0 & INT1 (P3.2 & P3.3). Enable the EX0 & EX1 interrupts and then enable the global interrupt flag. ------------------------------------------------------------------------------*/ IT0 = 1; // Configure interrupt 0 for falling edge on /INT0 (P3.2) IT1 = 1; // Configure interrupt 0 for falling edge on /INT1 (P3.3) EX0 = 1; // Enable EX0 Interrupt EX1 = 1; // Enable EX1 Interrupt ET1 = 1; // Enable Timer 1 Interrupt EA = 1; // Enable Global Interrupt Flag TMOD = 0x10; TL1 = 0x00; TH1 = 0x00;

// Configure Timer 1 to 16 bit mode Timer on Clk Freq / 12 // Initialize Timer1 value to zero

Microprocessor & Microcontroller Lab (EE212L)

Page 66

TR1 = 1;

// Start Timer 1

while (1);

// Forever Loop

}

Simulation:

Lab Task: Generate a square waves of any frequency using timer-0 interrupt. At the same time, use external interrupt 0 to decrement Port2

Microprocessor & Microcontroller Lab (EE212L)

Page 67

Related Documents