Google

Sep 20, 2008

Ebooks on Microprocessors and Microcontrollers

Here are a couple of ebooks related to Microprocessors and Microcontrollers.

Microcontroller Projects in C for the 8051


Microcontroller Projects in C for the 8051 This Page Intentionally Left Blank . Microcontroller Projects in C for the 8051 Dogan Ibrahim OXFORD AUCKLAND BOSTON JOHANNESBURG MELBOURNE NEW DELHI Newnes An imprint of Butterworth-Heinemann Linacre House, Jordan Hill, Oxford OX2 8DP 225 Wildwood Avenue, Woburn, MA 01801-2041 A division of Reed Education and Professional Publishing Ltd A member of the Reed Elsevier plc group First published 2000 # Dogan Ibrahim 2000 All rights reserved. No part of this publication may be reproduced in any material form (including photocopying or storing in any medium by electronic means and whether or not transiently or incidentally to some other use of this publication) without the written permission of the copyright holder except in accordance with the provisions of the Copyright, Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licensing Agency Ltd, 90 Tottenham Court Road, London, England W1P 9HE. Application for the copyright holder's written permission to reproduce any part of this publication should be addressed to the publishers British Library Cataloguing in Publication Data A catalogue record for this book is available from the British Library ISBN 0 7506 46403 Library of Congress Cataloguing in Publication Data A catalogue record for this book is available from the Library of Congress Tyeset by David Gregson Assciates, Beccles, Su€olk Printed and bound in Great Britain Contents Preface Chapter 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 Microcomputer Systems vii 1 1 1 2 3 4 4 10 11 12 13 15 16 16 16 17 17 18 18 18 19 19 19 20 21 22 22 24 24 Introduction Microcontroller Evolution Microcontroller Architecture 8051 Family Architecture of the 8051 Family Pin Con®guration Timer/Counters Interrupt Control Minimum Microcontroller Con®guration Project Development Programming Microcontrollers in C Chapter 2 2.1 2.2 2.3 2.4 2.5 Data Types 2.1.1 bit 2.1.2 signed char/unsigned char 2.1.3 signed short/unsigned short 2.1.4 signed int/unsigned int 2.1.5 signed long/unsigned long 2.1.6 ¯oat 2.1.7 sbit 2.1.8 sfr 2.1.9 sfr16 Memory Models Interrupts Structure of a Microcontroller-based C Program Program Description Language 2.5.1 START-END 2.5.2 Sequencing 2.5.3 IF-THEN-ELSE-ENDIF vi Microcontroller Projects in C for the 8051 2.6 2.7 2.5.4 DO-ENDO 2.5.5 REPEAT-UNTIL Internet Web Sites of Microcontroller Compilers Further Reading Light Projects 1 ± LED Binary Counter 2 ± LED Chasing Circuit 3 ± Random LED Pattern 4 ± Cyclic LED Pattern 5 ± LED Dice 6 ± Hexadecimal Display 7 ± Two-digit Decimal Count 8 ± TIL311 Dice 9 ± 7 Segment Display Driver 10 ± Four-digit LED Display Interface 11 ± Interrupt Driven Event Counter with 4-digit LED Display Sound Projects 24 25 25 27 29 29 33 34 37 38 46 50 53 57 62 75 85 86 90 94 95 101 107 108 119 125 126 132 147 151 155 161 167 171 177 Chapter 3 PROJECT PROJECT PROJECT PROJECT PROJECT PROJECT PROJECT PROJECT PROJECT PROJECT PROJECT Chapter 4 PROJECT 12 ± Simple Buzzer Interface PROJECT 13 ± Small Speaker Interface (Using the Timer Interrupt) PROJECT 14 ± Two-tone Small Speaker Interface (Using the Timer Interrupt) PROJECT 15 ± Electronic Siren (Using the Timer Interrupt) PROJECT 16 ± Electronic Siren (Using the Timer Interrupt) Chapter 5 Temperature Projects PROJECT 17 ± Using a Digital Temperature Sensor PROJECT 18 ± Digital Thermometer with Centigrade/Fahrenheit Output PROJECT 19 ± Digital Thermometer with High Alarm Output PROJECT 20 ± Digital Thermometer with High and Low Alarm Outputs PROJECT 21 ± Using Analogue Temperature Sensor IC with A/D Converter Chapter 6 RS232 Serial Communication Projects PROJECT 22 ± Output a Simple Text Message from the RS232 Port PROJECT 23 ± Input/Output Example Using the RS232 Port PROJECT 24 ± A Simple Calculator Program Using the RS232 Port Appendix ± ASCII code GLOSSARY Index Preface A microcontroller is a single chip microprocessor system which contains data and program memory, serial and parallel I/O, timers, external and internal interrupts, all integrated into a single chip that can be purchased for as little as $2.00. It is estimated that on average, a middle-class household in America has a minimum of 35 microcontrollers in it. About 34% of microcontroller applications are in o�ce automation, such as laser printers, fax machines, intelligent telephones, and so forth. About one-third of microcontrollers are found in consumer electronics goods. Products like CD players, hi-® equipment, video games, washing machines, cookers and so on ®t into this category. The communications market, automotive market, and the military share the rest of the application areas. Microcontrollers have traditionally been programmed using the assembly language of the target microcontroller. Di€erent microcontrollers from di€erent manufacturers have di€erent assembly languages. Assembly language consists of short mnemonic descriptions of the instruction sets. These mnemonics are di�cult to remember and the programs developed for one microcontroller cannot be used for other types of microcontrollers. The most common complaint about microcontroller programming is that the assembly language is somewhat di�cult to work with, especially during the development of complex projects. The solution to this problem is to use highlevel languages. This makes the programming a much simpler task and the programs are usually more readable, portable, and easier to maintain. There are various forms of BASIC and C compilers available for most microcontrollers. BASIC compilers are usually in the form of interpreters and the code produced is usually slow. Another disadvantage of BASIC is that most BASIC compilers are not structured and this makes the program maintenance a di�cult task. In this book we shall be using a fully featured professional C compiler to program our target microcontroller. viii Microcontroller Projects in C for the 8051 This book is about programming the 8051 family of microcontrollers using the C language, and I have chosen the AT89C2051 microcontroller for all the examples. AT89C2051 belongs to the industry standard 8051 family of microcontrollers. AT89C2051 is a 20-pin device which is fully code compatible with its bigger brother 8051. The device contains a serial port, 15 bits parallel I/O, two timer/counters, six interrupt sources, 128 bytes of data RAM, and 2 Kbytes of reprogrammable ¯ash program memory. There are many reasons for choosing the AT89C2051, including its compatibility with the 8051 family and the ease of erasing and reprogramming the device. There is no need to use a UV eraser to erase the program memory. The memory can be erased and then reprogrammed by using a low-cost programmer. Other reasons for using the AT89C2051 are its low cost and small size. All of the examples given herein can run on all members of the 8051 family. Chapter 1 provides an introduction to the architecture of the 8051 family, with special emphasis on the AT89C2051 microcontroller. Chapter 2 describes the features of the C compiler used throughout the projects in this book. Addresses of some popular web sites are also given in this chapter which contain information on the 8051 family. Chapter 3 provides many light-based projects. The circuit diagrams and the full C code of all the projects are given with full comments and explanations. All the projects have been built and tested on a breadboard. Chapter 4 is based on sound projects and there are working projects from simple buzzer circuits to electronic organ projects. Chapter 5 provides several working temperature-based projects using digital temperature sensors and analogue-to-digital converters. Finally, Chapter 6 describes several RS232-based projects which explain how information can be transferred between a microcontroller and external devices. Dogan Ibrahim 1999, London CHAPTER 1 MICROCOMPUTER SYSTEMS 1.1 Introduction The term microcomputer is used to describe a system that includes a microprocessor, program memory, data memory, and an input/output (I/O). Some microcomputer systems include additional components such as timers, counters, analogue-to-digital converters and so on. Thus, a microcomputer system can be anything from a large computer system having hard disks, ¯oppy disks and printers, to single chip computer systems. In this book we are going to consider only the type of microcomputers that consist of a single silicon chip. Such microcomputer systems are also called microcontrollers. 1.2 Microcontroller Evolution First, microcontrollers were developed in the mid-1970s. These were basically calculator-based processors with small ROM program memories, very limited RAM data memories, and a handful of input/output ports. As silicon technology developed, more powerful, 8-bit microcontrollers were produced. In addition to their improved instruction sets, these microcontrollers included on-chip counter/timers, interrupt facilities, and improved I/O handling. On-chip memory capacity was still small and was not adequate for many applications. One of the most signi®cant developments at this time was the availability of on-chip ultraviolet erasable EPROM memory. This simpli®ed the product development time considerably and, for the ®rst time, also allowed the use of microcontrollers in low-volume applications. The 8051 family was introduced in the early 1980s by Intel. Since its introduction, the 8051 has been one of the most popular microcontrollers and has been second-sourced by many manufacturers. The 8051 currently has many di€erent versions and some types include on-chip analogue-to-digital converters, a considerably large size of program and data memories, 2 Microcontroller Projects in C for the 8051 pulse-width modulation on outputs, and ¯ash memories that can be erased and reprogrammed by electrical signals. Microcontrollers have now moved into the 16-bit market. 16-bit microcontrollers are high-performance processors that ®nd applications in real-time and compute intensive ®elds (e.g. in digital signal processing or real-time control). Some of the 16-bit microcontrollers include large amounts of program and data memories, multi-channel analogue-to-digital converters, a large number of I/O ports, several serial ports, high-speed arithmetic and logic operations, and a powerful instruction set with signal processing capabilities. 1.3 Microcontroller Architecture The simplest microcontroller architecture consists of a microprocessor, memory, and input/output. The microprocessor consists of a central processing unit (CPU) and the control unit (CU). The CPU is the brain of a microprocessor and is where all of the arithmetic and logical operations are performed. The control unit controls the internal operations of the microprocessor and sends control signals to other parts of the microprocessor to carry out the required instructions. Memory is an important part of a microcomputer system. Depending upon the application we can classify memories into two groups: program memory and data memory. Program memory stores all the program code. This memory is usually a read-only memory (ROM). Other types of memories, e.g. EPROM and PEROM ¯ash memories, are used for low-volume applications and also during program development. Data memory is a read/write memory (RAM). In complex applications where there may be need for large amounts of memory it is possible to interface external memory chips to most microcontrollers. Input/Output (I/O) ports allow external digital signals to be connected to the microcontroller. I/O ports are usually organized into groups of 8 bits and each group is given a name. For example, the 8051 microcontroller contains four 8-bit I/O ports named P0, P1, P2, and P3. On some microcontrollers the direction of the I/O port lines are programmable so that di€erent bits of a port can be programmed as inputs or outputs. Some microcontrollers (including the 8051 family) provide bi-directional I/O ports. Each I/O port line of such microcontrollers can be used as inputs and outputs. Some microcontrollers provide `open-drain' outputs where the output transistors are left ¯oating (e.g. port P0 of the 8051 family). External pull-up resistors are normally used with such output port lines. Microcomputer Systems 3 1.4 8051 Family The 8051 family is a popular, industry standard 8-bit single chip microcomputer (microcontroller) family, manufactured by various companies with many di€erent capabilities. The basic standard device, which is the ®rst member of the family, is the 8051, which is a 40-pin microcontroller. This basic device is now available in several con®gurations. The 80C51 is the lowpower CMOS version of the family. The 8751 contains EPROM program memory, used mainly during development work. The 89C51 contains ¯ash programmable and erasable memory (PEROM) where the program memory can be reprogrammed without erasing the chip with ultraviolet light. The 8052 is an enhanced member of the family which contains more RAM and also more timer/counters. There are many versions of the 40-pin family which contain onchip analogue-to-digital converters, pulse-width modulators, and so on. At the lower end of the 8051 family we have the 20-pin microcontrollers which are code compatible with the 40-pin devices. The 20-pin devices have been manufactured for less complex applications where the I/O requirements are not very high and where less power is required (e.g. in portable applications). The AT89C1051 and AT89C2051 (manufactured by Atmel) are such microcontrollers, which are fully code compatible with the 8051 family and o€er reduced power and less functionality. Table 1.1 gives a list of the characteristics of some members of the 8051 family. Table 1.1 Device AT89C1051 AT89C2051 AT89C51 AT89C52 8051AH 87C51H 8052AH 87C52 87C54 87C58 Some popular members of the 8051 family Data memory 64 RAM 128 RAM 128 RAM 256 RAM 128 RAM 128 RAM 256 RAM 256 RAM 256 RAM 256 RAM Timer/ counters 1 2 2 3 2 2 3 3 3 3 I/O pins 15 15 32 32 32 32 32 32 32 32 Pin count 20 20 40 40 40 40 40 40 40 40 Program memory 1K ¯ash 2K ¯ash 4K ¯ash 8K ¯ash 4K ROM 4K EPROM 8K ROM 8K EPROM 16K EPROM 32K EPROM 4 Microcontroller Projects in C for the 8051 In this book all the projects are based upon the AT89C2051 microcontroller. The code given will run on other members of the family, including the 40-pin devices. The reasons for choosing the AT89C2051 are its low cost, low power consumption, small space (20 pin), and powerful features. In this chapter we shall be looking at the features of the 8051 family brie¯y with more emphasis on the smaller AT89C2051. More information on these microcontrollers can be obtained from the manufacturers' data sheets. 1.5 Architecture of the 8051 Family The 8051 is an 8-bit, low-power, high-performance microcontroller. There are a large number of devices in the 8051 family with similar architecture and each member of the family is downward compatible with each other. The basic 8051 microcontroller has the following features: . . . . . . . . 4 Kbytes of program memory 256  8 RAM data memory 32 programmable I/O lines Two 16-bit timer/counters Six interrupt sources Programmable serial UART port External memory interface Standard 40-pin package The EPROM versions of the family (e.g. 8751) are used for development and the program memory of these devices is erased with an ultraviolet light source. The pin con®guration of the standard 8051 microcontroller is shown in Fig. 1.1. The AT89C2051 is a low-end member of the 8051 family, aimed for less complex applications. This device contains a 2 Kbyte ¯ash programmable memory (PEROM) which can be erased and reprogrammed using a suitable programmer. The AT89C2051 contains 128 bytes of RAM and 15 programmable I/O lines. The code developed for this device runs on a standard 8051 without any modi®cation. As shown in Fig. 1.2, the AT89C2051 is housed in a 20-pin package. 1.6 Pin Con®guration Descriptions of the various pins are given below. Microcomputer Systems 5 Figure 1.1. Pin con®guration of the standard 8051 RST This is the reset input. This input should normally be at logic 0. A reset is accomplished by holding the RST pin high for at least two machine cycles. Power-on reset is normally performed by connecting an external capacitor and a resistor to this pin (see Figs 1.3 and 1.4). P3.0 This is a bi-directional I/O pin (bit 0 of port 3) with an internal pull-up resistor. This pin also acts as the data receive input (RXD) when the device is used as an asynchronous UART to receive serial data. 6 Microcontroller Projects in C for the 8051 Figure 1.2. Pin con®guration of the standard AT89C2051 P3.1 This is a bi-directional I/O pin (bit 1 of port 3) with an internal pull-up resistor. This pin also acts as the data transmit output (TXD) on the 8051 when the device is used as an asynchronous UART to transmit serial data. XTAL1 and XTAL2 These pins are where an external crystal should be connected for the operation of the internal oscillator. Normally two 33 pF capacitors are connected with the crystal as shown in Figs 1.3 and 1.4. A machine cycle is obtained by dividing the crystal frequency by 12. Thus, with a 12 MHz crystal, the machine cycle is 1 ms. Most machine instructions execute in one machine cycle. P3.2 This is a bi-directional I/O pin (bit 2 of port 3) with an internal pull-up resistor. This pin is also the external interrupt 0 (INT0) pin. Microcomputer Systems 7 Figure 1.3. Minimum 8051 con®guration P3.3 This is a bi-directional I/O pin (bit 3 of port 3) with an internal pull-up resistor. This pin is also the external interrupt 1 (INT1) pin. P3.4 This is a bi-directional I/O pin (bit 4 of port 3) with an internal pull-up resistor. This pin is also the counter 0 input (T0) pin. 8 Microcontroller Projects in C for the 8051 Figure 1.4. Minimum AT89C2051 con®guration P3.5 This is a bi-directional I/O pin (bit 5 of port 3) with an internal pull-up resistor. This pin is also the counter 1 input (T1) pin. GND Ground pin. P3.6 This is a bi-directional I/O pin. This pin is not available on the AT89C2051. It is also the external memory write (WR) pin. Microcomputer Systems 9 P3.7 This is a bi-directional I/O pin for bit 7 of port 3. On the standard 8051, this pin is also the external data memory read (RD) pin. P1.0 This is a bi-directional I/O pin for bit 0 of port 1. This pin has no internal pullup resistors on the 20-pin devices. It is also used as the positive input of the analogue comparator (AIN0) on the 20-pin device. P1.1 This is a bi-directional I/O pin for bit 1 of port 1. This pin has no internal pullup resistors on the 20-pin devices. It is also used as the positive input of the analogue comparator (AIN1) on the 20-pin device. P1.2 to P1.7 These are the remaining bi-directional I/O pins of port 1. These pins have internal pull-up resistors. VCC Supply voltage. P0.0 to P0.7 These are the eight I/O pins of port 0 of the standard 8051. These pins have no pull-up resistors. P0.0 to P0.7 are also used to provide the low addresses (A0 to A7) and the data during fetches from external program memory and during accesses to external data memory. P2.0 to P2.7 These are the eight I/O pins of port 2 of the standard 8051. These pins have pull-up resistors. P2.0 to P2.7 are also used to provide the high address (A8 to A15) byte during fetches from external program memory and during accesses to external data memory. EA/VPP This is the external access enable pin on the standard 8051. EA should be connected to VCC for internal program executions. This pin also receives the programming voltage during programming. 10 Microcontroller Projects in C for the 8051 PSEN This is the program store enable pin on the 8051 devices. This pin is activated when the device is executing code from external memory. ALE/PROG This is the address latch enable pin on the standard 8051 devices. This pin is used to latch the low byte of the address during accesses to external memory. 1.7 Timer/Counters The 8051 and AT89C2051 contain two timer/counters known as timer/counter 0 and timer/counter 1 (larger members of the 8051 family contain more timers/ counters). These timer/counters can be operated in several di€erent modes depending upon the programming of two registers TCON and TMOD, as shown in Tables 1.2 and 1.3. These registers should be programmed before using any timer or counter facilities of the microcontroller. Table 1.2 Bit name TF1 TR1 TF0 TR0 IE1 IT1 Bit position 7 6 5 4 3 2 TCON timer/counter control register Description Timer 1 over¯ow ¯ag. Set and cleared by hardware Timer 1 run control bit. Timer 1 is turned on when TR1 ˆ 1, and stopped when TR1 ˆ 0 Timer 0 over¯ow ¯ag. Set and cleared by hardware Timer 0 run control bit. Timer 0 is turned on when TR0 ˆ 1, and stopped when TR0 ˆ 0 External interrupt 1 edge ¯ag. Set and cleared by hardware External interrupt 1 type. IT1 ˆ 1 speci®es interrupt on falling edge. IT1 ˆ 0 speci®es interrupt on low level External interrupt 0 edge ¯ag. Set and cleared by hardware External interrupt 0 type. IT0 ˆ 1 speci®es interrupt on falling edge. IT0 ˆ 0 speci®es interrupt on low level IE0 IT0 1 0 Microcomputer Systems 11 Table 1.3 TIMER 1 GATE GATE: C/T TMOD timer/counter mode control register TIMER 0 M1 M0 GATE C/T M1 M0 C/T: M1, M0: When TRx is set and GATE ˆ 1, TIMER/COUNTERx runs only while the INTx pin is high. When GATE ˆ 0, TIMER/COUNTERx will run only while TRx ˆ 1. Timer or counter select bit. When C/T ˆ 0, operates as a timer (from internal clock). When C/T ˆ 1, it operates as a counter (input from Tx input). Timer/counter mode select bits are de®ned in Table 1.4. TCON is the timer/counter control register and this register is bit addressable. Table 1.4 M1, M0 mode control bits M1 0 0 1 1 M0 0 1 0 1 Operating mode 13-bit timer 16-bit timer/counter 8-bit auto-reload timer/counter Two 8-bit timers For example, bit 4 of TCON is the counter 0 run control bit and setting this bit starts counter 0. TCON register is at address 88 (hex) and bits in this register can be accessed either by making reference to the address or by using compiler reserved names (e.g. TR0). TMOD is the timer/counter mode control register. This register sets the operating modes of the two timer/counters as shown in Table 1.3. There are three operating modes, known as modes 0, 1, and 2. TMOD is not bit addressable and should be loaded by specifying all the 8 bits. For example, loading hexadecimal byte 01 into TMOD sets timer 0 into mode 1 which is a 16-bit timer and is turned on and o€ by bit TR0 of TCON. Also, timer 1 is set into mode 0 which is a 13-bit timer and is turned on and o€ by bit TR1 of TCON. 1.8 Interrupt Control The standard 8051 and AT89C2051 provide six interrupt sources: 12 Microcontroller Projects in C for the 8051 Table 1.5 Interrupt source External interrupt 0 Timer 0 External interrupt 1 Timer 1 Serial port Interrupt entry locations in memory Interrupt number 0 1 2 3 4 Location in memory (hex) 0003 000B 0013 001B 0023 Table 1.6 EA Where: EA: ± ± Interrupt enable/disable bits ES ET1 EX1 ET0 EX0 ES: ET1: EX1: ET0: EX0: Global interrupt enable/disable. If EA ˆ 0, no interrupt will be accepted. If EA ˆ 1, each interrupt source is individually enabled or disabled by setting or clearing its bit, given below. Serial port interrupt enable bit. Timer 1 interrupt enable bit. External interrupt 1 enable bit. Timer 0 interrupt enable bit. External interrupt 0 enable bit. . . . . Two external interrupts (INT0 and INT1) Two timer interrupts (timer 0 and timer 1) One serial port receive interrupt One serial port transmit interrupt Each interrupt is assigned a ®xed location in memory and an interrupt causes the CPU to jump to that location, where it executes the interrupt service routine. Table 1.5 gives the interrupt sources and the start of their service routines in memory. Note that the serial port receive and transmit interrupts point to the same location. Each interrupt source can be individually enabled or disabled by setting or clearing its interrupt enable bit. Table 1.6 gives the interrupt enable bit patterns. 1.9 Minimum Microcontroller Con®guration The minimum microcontroller con®gurations of the 8051- and AT89C2051based microcontroller systems are shown in Figs 1.3 and 1.4. As can be seen Microcomputer Systems 13 from these ®gures, only the following external components are required to have a working microcontroller: X1 C1, C2 C3 R1 Crystal (e.g. 12 MHz) 33 pF capacitors 10 mF, 10 V electrolytic capacitor 8.2K, 0.125 W resistor We shall be using the circuit in Fig. 1.4 in all of the projects described in this book, except the last project which is based on a 40-pin device. The crystal chosen for the projects is 12 MHz, which gives a basic instruction timing of 1 ms. The power supply current of the AT89C2051 is around 15 mA, but a power supply which can deliver up to a few hundred milliamperes is recommended so that the interface circuitry attached to the microcontroller can be powered. 1.10 Project Development Development of a AT89C2051 microcontroller project requires several development tools. The following is a list of the tools that are essential: . Suitable assembler or compiler which can generate machine code for the AT89C2051 microcontroller. In this book we shall be developing the projects using a C compiler. Chip programmer suitable to program AT89C2051 devices. There are many programmers available on the market for this purpose. For example, PG302 by Inguana labs, Evalu8r by Equinox Technologies, and others. The programmer should be compatible with the code generated by the assembler or the compiler so that the code can be downloaded to the microcontroller. Notice that there is no ultraviolet erasing process. AT89C2051 devices contain reprogrammmable ¯ash memories which can be erased and reprogrammed by electrical signals. A minimum AT89C2051 microcontroller hardware. Many manufacturers o€er development systems, consisting of a basic microcontroller, LED lights, switches, buzzers etc. Some development systems include both language compilers and hardware and such systems can be very useful during project development. . . Although the microcontroller used in the projects is the 20-pin AT89C2051, the code given will run on all members of the 8051 family provided that there is enough program and data memories. This Page Intentionally Left Blank . CHAPTER 2 PROGRAMMING MICROCONTROLLERS IN C The C programming language is a general-purpose high-level programming language that o€ers e�cient and compact code and provides elements of structured programming. Many control and monitoring-based applications can be solved more e�ciently with C than with any other programming language. C was originally available on mainframe computers, minicomputers, and personal computers (PCs). The C programming language is now available on most microcontrollers and microprocessors. This book is not intended for teaching the C programming language. It is assumed that the reader is familiar with programming in C. The aim of this chapter is to show the special features of the C language when programming microcontrollers. In this book, the industry standard C51 optimizing C compiler is used throughout. This compiler has been developed by Keil Elektronik GmbH. C51 is available on both MS-DOS and Windows-based operating systems and the compiler implements the American National Standards Institute (ANSI) standard for the C language. There are many other high-level language compilers available for microcontrollers, including PASCAL, BASIC, and other C compilers. Some of these compilers are freely available as shareware products and some can be obtained from the Internet with little cost. Also, some companies supply free limited capability compilers, mainly for evaluation purposes. These compilers can be used for learning the features of a speci®c product and in some cases small projects can be developed with such compilers. Section 2.5 gives a list of some sites where readers can ®nd more information on high-level microcontroller compilers. The C51 compiler has been developed for the 8051 family of microcontrollers. This is one of the most commonly used industry standard C compilers for the 8051 family, and can generate machine code for most of the 20-pin and 40-pin 8051 devices and its derivatives, including the following microcontrollers: Intel and others 8051, 80C51, and 87C51 Atmel 89C51, 89C52, 89C55, 89S8252, and 89S53 Atmel 89C1051 and 89C2051 16 Microcontroller Projects in C for the 8051 AMD 80C321, 80C521, and 80C541 Dallas 80C320, 80C520, and 80C530 Signetics 8xC750, 8xC751, and 8xC752 Siemens 80C517 and 80C537 C51 is a professional, industry standard compiler with many features, including a large number of built-in functions. In this chapter we shall be looking at the features of the C51 programming language as applied to programming single chip microcontrollers. More information on the C51 compiler is available from Keil Elektronik GmbH (see the C51 Optimizing 8051 Compiler and Library Reference Manual). 2.1 Data Types The C51 compiler provides the standard C data types and in addition several extended data types are o€ered to support the 8051 microcontroller family. Table 2.1 lists the available data types (see the C51 reference manual for more information). Some of the data types are described below in more detail. 2.1.1 bit These data types may be used to declare 1-bit variables. Example: bit my_¯ag; my_¯ag ˆ 1; /* declare my_¯ag as a bit variable */ /* set my_¯ag to 1 */ 2.1.2 signed char/unsigned char These data types are as in standard C language and are used to declare signed and unsigned character variables. Each character variable is 1 byte long (8 bits). Signed character variables range from À128 to ‡127; unsigned character variables range from 0 to 255. Example: unsigned char var1,var2; var1 ˆ 0xA4; var2 ˆ var1; /* declare var1 and var2 as unsigned char */ /* assign hexadecimal A4 to variable var1 */ /* assign var1 to var2 */ Programming Microcontrollers In C 17 Table 2.1 Data type bit signed char unsigned char enum signed short unsigned short signed int unsigned int signed long unsigned long ¯oat sbit sfr sfr16 Bits 1 8 8 16 16 16 16 16 32 32 32 1 8 16 CSI data types Range 0 or 1 À128 to ‡127 0 to ‡255 À32768 to ‡32767 À32786 to ‡32767 0 to 65535 À32768 to ‡32767 0 to 65535 À2147483648 to 2147483647 0 to 4294967295 Æ1.175494E-38 to Æ3.402823E+38 0 or 1 0 to 255 0 to 65535 2.1.3 signed short/unsigned short These data types are as in standard C language and are used to declare signed and unsigned short variables. Each short variable is 2 bytes long (16 bits). Signed short variables range from À32 768 to ‡32 767 and unsigned short variables range from 0 to 65 535. Example: unsigned short temp; unsigned short wind; temp ˆ 0x0C200; wind ˆ temp; /* declare temp as unsigned short */ /* declare wind as unsigned short */ /* assign hexadecimal C200 to variable temp */ /* assign variable temp to wind */ 2.1.4 signed int/unsigned int As in the standard C language, these data types are used to declare signed and 18 Microcontroller Projects in C for the 8051 unsigned integer variables. Integer variables are 2 bytes long (16 bits). Signed integers range from À32 768 to ‡32 767 and unsigned integers range from 0 to 65 535. Example: unsigned int n1,n2; n1 ˆ 10; n2 ˆ 2*n1; /* declare n1 and n2 as unsigned integers */ /* assign 10 to n1 */ /* multiply n1 by 2 and assign to n2 */ 2.1.5 signed long/unsigned long These data types are as in standard C language and are used to declare signed and unsigned long integer variables. Each long integer variable is 4 bytes long (32 bits). Example: unsigned long temp; temp ˆ 250 000; /* declare temp as long integer variable */ /* assign 250 000 to variable temp */ 2.1.6 ¯oat This data type is used to declare a ¯oating point variable. Example: ¯oat t1,t2; t1 ˆ 25.4; t2 ˆ sqrt(t1); /* declare t1 and t2 as ¯oating point variables */ /* assign 25.4 to t1 */ /* assign the square-root of t1 to t2 */ 2.1.7 sbit This data type is provided for the 8051 family and is used to declare an individual bit within the SFR of the 8051 family. For example, using this data type one can access individual bits of an I/O port. Example: sbit switch ˆ P1^3; switch ˆ 0; /* variable switch is assigned to bit 3 of port 1 */ /* clear bit 3 of port 1 */ Programming Microcontrollers In C 19 2.1.8 sfr This data type is similar to sbit but is used to declare 8-bit variables. Example: sfr P1 ˆ 0x90; sfr P2 ˆ 0xA0; unsigned char my_data; my_data ˆ P1; P2 ˆ my_data++; /* Port 1 address 0x90 assigned to P1 */ /* Port 2 address 0xA0 assigned to P2 */ /* declare my_data as unsigned character */ /* read 8 bit data from port 1 and assign to my_data */ /* increment my_data and send to port 2 */ 2.1.9 sfr16 This data type is similar to sfr but is used to declare 16-bit variables. When using this data type, the low byte should precede the high byte. Example: Timer 2 of the 8052 microcontroller uses addresses 0xCC and 0xCD for the low and high bytes. We can declare variable T2 to access both timer locations. sfr16 T2 ˆ 0xCC; T2 ˆ 0xAE01; /* Timer 2, T2L=CC and T2H=CD */ /* load Timer 2 with hexadecimal value AE01 */ 2.2 Memory Models 8051 architecture supports both program (or code) and data memory areas. Program memory is read-only and it cannot be written to. Depending upon the type of processor used di€erent amounts of internal program memory are available. For example, 8051 provides 4 Kbytes of internal program memory. Similarly, 89C2051 provides only 2 Kbytes of internal program memory. The program memory can be increased by connecting additional external memory to the basic microcontroller. There may be up to 64 Kbytes of program memory. Data memory resides within the 8051 CPU and can be read from and written into. Up to 256 bytes of data memory are available depending upon the type of microcontroller used. The memory model determines what type of program memory is to be used for a given application. There are three memory models, known as SMALL, COMPACT, and LARGE, and the required model is speci®ed using the compiler directives. The SMALL memory model is used if all the variables 20 Microcontroller Projects in C for the 8051 reside in the internal data memory of the 8051. This memory model generates the fastest and the most e�cient code and should be used whenever possible. In the COMPACT memory model, all variables reside in one page of external data memory. A maximum of 256 bytes of variables can be used. This memory model is not as e�cient as the SMALL model. In the LARGE memory model, all variables reside in external data memory. A maximum of 64 Kbytes of data can be used. The LARGE model generates more code than the other two models and thus it is not very e�cient. Compiling in the SMALL memory model always generates the fastest and the smallest code possible since accessing the internal memory is always faster than accessing any external memory. 2.3 Interrupts The C51 compiler allows us to declare interrupt service routines (ISRs) in our C code and then the program automatically jumps to this code when an interrupt occurs. The compiler automatically generates the interrupt vectors and entry and exit code for interrupt routines. An ISR is declared similar to a function declaration but the interrupt number is speci®ed as part of the function declaration. For example, the following is a declaration of the ISR for timer 1 interrupts (interrupt number 3): Void timer1() interrupt 3 { interrupt service code goes in here } Similarly, the ISR for timer 0 (interrupt number 1) is declared as: void timer0() interrupt 1 { interrupt service code goes in here } Note that we can specify the register bank to be used for the ISR with the using function attribute: void timer0() interrupt 1 using 2 { interrupt service code goes in here } Programming Microcontrollers In C 21 2.4 Structure of a Microcontroller-based C Program The structure of a C program developed for a microcontroller is basically the same as the structure of a standard C program, with a few minor changes. The structure of a typical microcontroller-based C program is shown in Fig. 2.1. It is always advisable to describe the project at the beginning of a program using comment lines. The project name, ®lename, date, and the target processor type should also be included in this part of the program. The register de®nition ®le should then be included for the type of target processor used. This ®le is supplied as part of the compiler and includes the de®nitions for various registers of the microcontroller. In the example in Fig. 2.1, the register de®nition ®le for the Atmel 89C2051 type microcontroller is included. The global de®nitions of the variables used should then be entered, one line for each de®nition. The functions used in the program should then be included with the appropriate comments added to the heading and also to each line of the /**************************************************************************************************** Project: File: Date: Processor: Give project name Give ®lename Date program was developed Give target processor type This is the program header. Describe your program here brie¯y. ****************************************************************************************************/ #include #de®ne ...... sbit ...... int ...... char ...... void func1() { } /* include your global declarations here */ /* include you functions here */ /* include your de®ne statements here */ /* include your bit de®nitions here */ main() { /* main code */ /* include comments here */ } Figure 2.1. Structure of a microcontroller C program 22 Microcontroller Projects in C for the 8051 functions. The main program starts with the keyword main(), followed by the opening brackets `{'. The lines of the main program should also contain comments to clarify the operation of the program. The program is terminated by a closing bracket `}'. An example program is shown in Fig. 2.2. This program receives an 8-bit data from port 1 of an 89C2051 type microcontroller. The state of a switch, connected to bit 0 of port 3, is then checked. If the switch is 1, the value of the data is doubled by calling function double_it. If, on the other hand, the state of the switch is 0, the data value is incremented by 2 by calling function inc_by2, and then the program stops. It is important to realize that there is no returning point in a microcontroller program. Thus, where necessary, an endless loop should be formed at the end to stop the program from going into unde®ned parts of its code memory. 2.5 Program Description Language (PDL) There are many methods that a programmer may choose to describe the algorithm to be implemented by a program. Flow charts have been used extensively in the past in many computer programming tasks. Although ¯ow charts are useful, they tend to create an unstructured code and also a lot of time is usually wasted drawing them, especially when developing complex programs. In this section we shall be looking at a di€erent way of describing the operation of a program, namely by using a program description language (PDL). A PDL is an English-like language which can be used to describe the operation of a program. Although there are many variants of PDL, we shall be using simple constructs of PDL in our programming exercises, as described below. 2.5.1 START-END Every PDL program (or sub-program) should start with a START statement and terminate with an END statement. The keywords in a PDL code should be highlighted in bold to make the code more clear. It is also good practice to indent program statements between the PDL keywords. Example: START ............ ............ END Programming Microcontrollers In C 23 /**************************************************************************************************** Project: A simple test File: Date: Processor: TEST.C 10 August 1999 89C2051 This program receives an 8-bit data from port 1 of the microcontroller and stores this data in variable ®rst. The state of a switch, connected to bit 0 of port 3, is then checked. If the switch is 1, variable ®rst is doubled by calling function double_it. If, on the other hand, the state of the switch is 0, variable ®rst is incremented by 2 by calling to inc_by2 ****************************************************************************************************/ #include #de®ne ON 1 #de®ne OFF 0 sbit switch = P3^0; /* switch is connected to bit 0 of port 3 */ /* Function to double a value */ unsigned char double_it(unsigned char x) { return (2*x); } /* Function to increment a value by 2 */ unsigned char inc_by2(unsigned char x) { return (x+2); } /* Start of MAIN program */ main() { unsigned char ®rst,second; ®rst = P1; if(switch = = ON) second=double_it(®rst); else second=inc_by2(®rst); for(;;) { } } /* end of MAIN program */ /* otherwise increment by 2 */ /* wait here forever */ /* get 8-bit data from port 1 */ /* double the data if switch = 1 */ Figure 2.2. Example of a microcontroller C program 24 Microcontroller Projects in C for the 8051 2.5.2 Sequencing For normal sequencing in a program, write the steps as short English text as if you are describing the program. Example: Turn on the valve Clear the bu€er Turn on the LED 2.5.3 IF-THEN-ELSE-ENDIF Use IF, THEN, ELSE, and ENDIF statements to describe the ¯ow of control in your programs. Example: IF switch = 1 THEN Turn on buzzer ELSE Turn o€ buzzer T urn o€ LED ENDIF 2.5.4 DO-ENDDO Use DO and ENDDO control statements to show iteration in your PDL code. Example: Turn on LED DO 5 times Set clock to 1 Set clock to 0 ENDDO A variation of the DO-ENDDO construct is to use other keywords like DOFOREVER, DO-UNTIL etc. as shown in the following examples. Turn o€ the buzzer IF switch = 1 THEN DO UNTIL Port 1 = 2 Turn on LED Read port 1 ENDDO ENDIF Programming Microcontrollers In C 25 or DO FOREVER Read data from port 1 Display data Delay a second ENDDO 2.5.5 REPEAT-UNTIL This is another useful control construct which can be used in PDL codes. An example is shown below where the program waits until a switch value is equal to 1. REPEAT Turn on buzzer Read switch value UNTIL switch = 1 2.6 Internet Web Sites of Microcontroller Compilers The amount of microcontroller software available on the Internet is huge and there are many di€erent example programs. Internet web sites of some popular 8051 family microcontroller compilers and other useful sites are given below. Pascal compilers Embedded Pascal ± 8051/8051 http://www.grifo.it/SOFT/Lawicel/uk_EP_51.htm Pascal 51 http://www.grifo.com/SOFT/KSC/Pascal51.htm Embedded Pascal http://www/users.iafrica.com/r/ra/rainier/index.htm ElProg Pascal51 http://www.geocoties.com/SiliconValley/Campus/9592/index.html SYSTEM51 Pascal http://www.spacetools.de/tools/space-program/space/products/s_050006.htm 26 Microcontroller Projects in C for the 8051 C Compilers MICRO/C-51 htp://www.mcc-us.com/51tools.htm Small C http://www.newmicros.com/smallc51.html IDE51-C http://www.spjsystems.com/ide51.htm SDCC (freeware 8051 C compiler) http://www.geocoties.com/ResearchTriangle/Forum/1353/ C51 ttp://www.keilsoftware.com/home.htm Various BASIC and C compilers http://www.equinox-tech.com MICRO-C http://www.dun®eld.com/dks.htm Basic compilers BASCOM http://www.x54all.nl/$mcselec/bascom.html TINY BASIC http://www.code.archive.aisnota.com/ BASIKIT http://www.mdllabs.com/basikit.htm BXC-51 http://www.mindspring.com/$tavve/8051/bxc51.html BEC-51 http://www.windspring.com/$tavve/8051/bec51.html Useful site on 8051 software and hardware http://www.cis.ohio-state.edu/hypertext/faq/usenet/microcontroller-faq/8051/ faq.html Programming Microcontrollers In C 27 2.7 Further Reading The following books and reference manuals are useful in learning to program in C. The C Programming Language (2nd edn) Kernighan & Richie Prentice-Hall, Inc. ISBN 0-13-110370-9 C and the 8051: Programming and Multitasking Schultz PTR Prentice-Hall, Inc. ISBN 0-13-753815-4 C for Dummies Dan Gookin ISBN 1-878058-78-9 C The Complete Reference Herbert Schildt ISBN 0-07-882101-0 E�cient C Plum & Brodie Plum Hall Inc. ISBN 0-911537-05-8 C51 Compiler, Optimizing 8051 C Compiler and Library Reference User's Guide Keil Elektronik GmbH This Page Intentionally Left Blank . CHAPTER 3 LIGHT PROJECTS This chapter describes simple light projects using the basic 89C2051 microcontroller circuit described in earlier chapters. Over ten projects are given, from very simple LED display projects to complex projects incorporating alphanumeric displays. For each project, the following information is given as appropriate: . . . . . Function: what the project does, its inputs and outputs. Circuit diagram: full circuit diagram of the project and explanation of how the circuit works. Program description: functional description of the software in simple English-like language (PDL). Program listing: full tested and working C program listing for each project, including comments. Components required: listing of components required to build each project. PROJECT 1 ± LED Binary Counter Function This project counts up in binary and displays the result on eight LEDs connected to port 1 of the microcontroller as shown in Fig. 3.1. Circuit Diagram As shown in Fig. 3.2 the circuit is extremely simple, consisting of the basic 89C2051-based microcontroller and eight LEDs connected to port 1 of the microcontroller. Each microcontroller output pin can sink a maximum of 80 mA and source up to 20 mA. The manufacturers specify that the total source current of a port should not exceed 80 mA. There are many di€erent types of LED lights on the market, emitting red, green, amber, white, or yellow colours. Standard red LEDs require about 5 to 10 mA to emit visible bright light. There are also low-current small LEDs operating from as low as 1 mA. 30 Microcontroller Projects in C for the 8051 Figure 3.1. Output pattern of Project 1 In Fig. 3.2, the microcontroller outputs operate in current source mode where an LED is turned on if the corresponding output is at logic LOW level. The required value of the current limiting resistors can be calculated as follows: Rˆ Vs À Vf If where Vs is the supply voltage ( ‡5 V), Vf is the LED forward voltage drop (about 2 V), and If is the LED forward current (1 to 30 mA depending on the type of LED used). In this design if we assume an LED current of about 6 mA, the required resistors will be: Rˆ 5À2 � 470 6 Although eight individual resistors are shown in this circuit, it is possible to replace these resistors with a single DIL (dual-in-line) resistor chain. Program Description The program is required to increment a value and then output to port 1 of the microcontroller. Because the microcontroller operates at a very high speed, it is Light Projects 31 Figure 3.2. Circuit diagram of Project 1 necessary to insert a delay in the program so that the LED outputs can be seen visually. The following PDL describes the functions of the program: START Set count to 1 DO FOREVER Output count to port 1 Increment count Delay ENDDO END 32 Microcontroller Projects in C for the 8051 /**************************************************************************************************** PROJECT: PROJECT 1 FILE: DATE: PROCESSOR: PROJ1.C August 1999 AT892051 This project counts up in binary and displays the result on eight LEDs connected to port 1. The data is displayed with about 1 second delay between each output. ****************************************************************************************************/ #include /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); led="1;" p1="~LED;" count =" 0"> /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); led="128;" p1="~LED;" led="LED">> 1; if(LED == 0)LED=128; wait_a_second(); } } /*Invert and output*/ /*Shift to right*/ /*Set to 128*/ /*Wait a second*/ /*initialize to 128*/ /*Start of loop*/ Figure 3.5. Program listing of Project 2 Circuit Diagram The same circuit (Fig. 3.2) as in Project 1 is used . The LEDs can be mounted in di€erent patterns and in di€erent colours depending upon the application. Program Description The program is required to generate a random number and then output this number to port 1 in order to turn on the corresponding LEDs. A small delay is required between each output so that the LED patterns can be seen. The following PDL describes the functions of the program: 36 Microcontroller Projects in C for the 8051 START DO FOREVER Generate a random number Output number to port 1 Delay ENDDO END Program Listing The full program listing is shown in Fig. 3.6. Variable LED is used to hold the data. The endless loop is set using the for statement with no parameters. /**************************************************************************************************** PROJECT: PROJECT 3 FILE: DATE: PROCESSOR: PROJ3.C August 1999 AT892051 This project turns on the LEDs connected to port 1 randomly. A random number is generated between 0 and 32 767 and then this is output to turn on the corresponding LEDs. The data is displayed with about 1 second delay between each output. ****************************************************************************************************/ #include #include /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); led="rand();" p1="~LED;" count =" 255" led =" 255),"> /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); led="128;" p1="~LED;" led="LED">> 1); if(LED == 255) { wait_a_second(); P1=~LED; LED=128; } wait_a_second(); } } /*Wait a second*/ /*Invert and output*/ /*Obtain next value*/ /*If end of pattern . . . */ /*Initialize count*/ /*Start of loop*/ Figure 3.8. Program listing of Project 4 shown in Fig. 3.9, the seven LEDs have been mounted in a pattern to emulate the dots on a real dice. The pattern displayed for di€erent numbers is shown in Fig. 3.10. As in a real dice, the ®rst row can have up to two LEDs on (corresponding to two dots on a dice), the second row up to three LEDs on, and the third row can have up to two LEDs on. 40 Microcontroller Projects in C for the 8051 Figure 3.9. Circuit diagram of Project 5 Figure 3.10. LED pattern displayed for different dice numbers Program Description A random dice number is obtained during scanning of the push-button switch as follows. The program scans the push-button switch continuously. If the switch is not pressed (i.e. at logic HIGH), a number is incremented between 1 and 6. Whenever the push-button is pressed, the current value of the number is read and this value is used as the new dice number. Since the switch is pressed by the user in random, the numbers generated are also random numbers from 1 to 6. The new random number is displayed on the seven LEDs appropriately. Light Projects 41 After about 2 seconds delay, all LEDs are turned o€ and the above process is repeated forever. The following PDL describes the functions of the program: START Initialize count to 0 DO FOREVER IF Push-button is pressed THEN Read the new dice number from count Turn on the appropriate dice LEDs Delay about 2 seconds Turn o€ all LEDs ELSE Increment count IF count = 7 THEN Count = 1 ENDIF ENDIF ENDDO END Table 3.1 shows the random numbers generated and the corresponding LEDs that will be turned on to give the dice display of Fig. 3.10. As an example, if the number 3 is to be displayed then only LEDs D3, D4, and D5 will be turned on. Similarly, for number 6, all LEDs except LED 4 will be turned on. Program Listing The full program listing is shown in Fig. 3.11. Variable ON is de®ned as 0 and Table 3.1 Number 1 2 3 4 5 6 Dice Numbers and corresponding LED patterns LED on D4 D3, D5 D3, D4, D5 D1, D2, D6, D7 D1, D2, D4, D6, D7 D1, D2, D3, D5, D6, D7 42 Microcontroller Projects in C for the 8051 /**************************************************************************************************** PROJECT: PROJECT 5 FILE: DATE: PROCESSOR: PROJ5.C August 1998 AT892051 This is a dice simulator project. Seven LEDs are connected to port 1 of the microcontroller and arranged as shown in the text. A push-button switch is connected to bit 0 of port 3 and when this switch is pressed, a new number is obtained between 1 and 6 and the corresponding LEDs are turned on to simulate a real dice. After 2 seconds delay, all LEDs are turned off and the user can throw a dice again. ****************************************************************************************************/ #include #de®ne ON 0 #de®ne ALL_OFF 0xFF sbit button = P3^0; sbit D1=P1^0; sbit D2=P1^1; sbit D3=P1^2; sbit D4=P1^3; sbit D5=P1^4; sbit D6=P1^5; sbit D7=P1^6; /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); dice="0;" button ="=" d4="ON;" dice="1*/" d3="ON;" d5="ON;" d3="ON;" d4="ON;" d5="ON;" d1="ON;" d2="ON;" d6="ON;" d7="ON;" d1="ON;" d2="ON;" d4="ON;" d6="ON;" d7="ON;" d1="ON;" d2="ON;" d3="ON;" d5="ON;" d6="ON;" d7="ON;" p1="ALL_OFF;" dice =" =" dice="1;" dice="2*/" dice="3*/" dice="4*/" dice="5*/" dice="6*/"> #de®ne ALL_OFF 0xFF /*Bit P3.0 is the push-button*/ sbit button = P3^0; /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); dice="0;" button ="=" p1="~DICE_ARRAY[DICE-1];" p1="ALL_OFF;" dice ="=" dice="1;" count =" 16" count =" 0"> sbit latch = P1^7; /*Bit P1.7 is the latch*/ /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); p1="x" latch="0;" latch="1;" cnt="0;" latch="1;" cnt ="=" cnt="0;" latch="1*/" cnt ="=" cnt="0;" cnt ="=" cnt="0;" count =" 100" count =" 0"> sbit latch_msd = P1^7; sbit latch_lsd = P1^6; /*Bit P1.7 is the msd latch*/ /*Bit P1.6 is the lsd latch*/ /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); msd="x/10;" lsd="x-10*msd;" p1="msd" latch_msd="0;" latch_msd="1;" p1="lsd" latch_lsd="0;" latch_lsd="1;" cnt="0;" latch_msd="1;" latch_lsd="1;" cnt ="=" cnt="0;" count =" 7" count =" 1" button =" 1),"> sbit latch = P1^7; sbit button = P3^0; /*Bit P1.7 is the latch*/ /*Bit P3.0 is push-button*/ /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); p1="x" latch="0;" latch="1;" latch="1;" button ="=" dice ="=" dice="1;" count =" 10" count =" 0"> /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); led="0;" p1="~LED_ARRAY[LED];" led ="=" led="0;" bit =" 0"> sbit DISPLAY_CLOCK=P1^6; sbit DISPLAY_DATA =P1^7; /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); display_clock="1;" display_clock="0;" n="LED_ARRAY[x];" i="1;i<=" top_bit="n" display_data="1;" display_data="0;" n="n" rst="n/1000;" r="n-1000*®rst;" second="r/100;" r="r-100*second;" third="r/10;" fourth="r-third*10;" display_data="1;" display_data="0;" display_data="0;" display_clock="0;" display_data="1;" display_data="0;" i="1;i<=" led="0;" lz="0," lz="1," dp1="0" dp1="1"> sbit DISPLAY_CLOCK=P1^6; sbit DISPLAY_DATA =P1^7; /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); display_clock="1;" display_clock="0;" n="LED_ARRAY[x];" i="1;i<=" top_bit="n" display_data="1;" display_data="0;" n="n" rst="n/1000;" r="n-1000*®rst;" second="r/100;" r="r-100*second;" third="r/10;" fourth="r-third*10;" display_data="1;" display_data="0;" display_data="0;" display_clock="0;" display_data="1;" display_data="0;" i="1;i<=" led="0;"> sbit DISPLAY_CLOCK=P1^6; sbit DISPLAY_DATA =P1^7; /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); display_clock="1;" display_clock="0;" n="LED_ARRAY[x]" i="1;i<=" top_bit="n" display_data="1;" display_data="0;" n="n" rst="n/1000;" r="n-1000*®rst;" second="r/100;" r="r-100*second;" third="r/10;" fourth="r-third*10;" display_data="1;" lz ="=" lz ="=" lz ="=" lz ="=" display_data="0;" display_data="0;" display_clock="0;" display_data="1;" display_data="0;" i="1;i<=" led="0;"> sbit DISPLAY_CLOCK=P1^6; sbit DISPLAY_DATA =P1^7; sbit RESET_COUNTER=P3^0; int EVENT=0; /*initialize to 0*/ /* Function to send a clock pulse to the display */ void send_clock() { DISPLAY_CLOCK=1; DISPLAY_CLOCK=0; } /* Function to display a digit */ void display_digit(int x,char dp) { unsigned char LED_ARRAY[11]= { 0xFC,0x60,0xDA,0xF2,0x66,0xB6,0xBE,0xE0,0xFE,0xF6,0 }; unsigned char n,top_bit,i; n=LED_ARRAY[x] | dp; for(i=1;i<=8;i++) { top_bit=n & 0x80; if(top_bit != 0) DISPLAY_DATA=1; else DISPLAY_DATA=0; send_clock(); n=n << rst="n/1000;" r="n-1000*®rst;" second="r/100;" r="r-100*second;" third="r/10;" fourth="r-third*10;" display_data="1;" lz ="=" lz ="=" lz ="=" lz ="=" display_data="0;" display_data="0;" display_clock="0;" display_data="1;" display_data="0;" i="1;i<=" it0="1;" ex0="1;" ea="1;" reset_counter ="=" event="0;"> sbit BUZZER=P1^7; sbit PUSH_BUTTON =P3^0; #de®ne ON 0 #de®ne OFF 1 /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); buzzer="OFF;" push_button ="=" i="1;i<=" buzzer="ON;" buzzer="OFF;"> sbit SPEAKER=P1^7; sbit PUSH_BUTTON =P3^0; int count; /* Timer 1 initialization routine */ void init_timer() { ET1=1; TMOD=0x20; TH1=0x6; EA=1; TR1=1; } /* Timer 1 interrupt service routine */ timer1() interrupt 3 { count++; if(count == 2) { count=0; SPEAKER=~SPEAKER; } } /* Start of main program */ main() /*Reset count*/ /*Inc. count*/ /*count=2*/ /*Enable timer 1 int*/ /*Timer 1 in Mode 2*/ /*250 ms count*/ /*Enable interrupts*/ /*Turn on timer 1*/ Sound Projects 93 { count=0; SPEAKER=0; while(PUSH_BUTTON == 1) { } init_timer(); /*Initialize timer*/ /*Initialize count*/ /*Speaker OFF*/ /* Endless loop. Wait here for timer interrupt */ for(;;) { } } Figure 4.4. Program listing of Project 13 Figure 4.5. Output waveform produced by Project 13 elapsed. The state of the speaker is then changed after 500 ms. As shown in Fig. 4.5, the period of the generated waveform is thus 1 ms (500 ms ON time and 500 ms OFF time, i.e. a frequency of 1 kHz). You can change the frequency of the tone easily by loading a di€erent value into the timer register. Components Required In addition to the components used for the basic microcontroller circuit, the following components will be required: B1 R2 T1 S1 small speaker (e.g. T70L015H) 100K, 0.5 W resistor VN66AFD MOSFET push-button switch 94 Microcontroller Projects in C for the 8051 PROJECT 14 ± Two-tone Small Speaker Interface (Using the Timer Interrupt) Function This project shows how we can interface our microcontroller to a small speaker type audible device and generate two di€erent tones. When power is applied to the circuit, a continuous single tone of frequency 1 kHz is output to the speaker. When a push-button switch is pressed, the tone frequency is changed to 500 Hz. Timer 1 interrupt of the microcontroller is used to generate the time delay required for the tones. Circuit Diagram The circuit diagram of this project is the same as the one in Project 12 (i.e. Fig. 4.3) except that the buzzer is replaced with a small speaker. Bit 7 of port 1 is connected directly to a small speaker via a MOSFET transistor. The port output is in voltage mode so that the buzzer will turn on when the port output is at logic HIGH ( ‡ 5 V). Bit 0 of port 3 is connected to a push-button switch, which is normally held at logic HIGH by the pull-up resistor R2. Program Description The speaker is initially turned OFF. Timer 1 of the microcontroller is then initialized to generate a continuous tone with a frequency of 1 kHz, as in Project 13. The push-button switch is then checked and when the switch is pressed, the timer register value is doubled, i.e. the interrupt interval is increased from 500 ms to 1 ms. A waveform with a 1 ms on and 1 ms o€ time has a frequency of 500 Hz. The following PDL describes the functions of the program: Main program START Turn OFF speaker Initialize timer 1 to generate interrupts at 500 ms (int_rate=2) DO FOREVER IF push-button switch is pressed THEN Reload timer register for 1 ms interrupts (int_rate ˆ 4) ENDIF ENDDO END Sound Projects 95 Timer 1 initialisation START Enable timer 1 interrupts Set timer 1 to mode 8-bit auto-reload Load timer value 6 (i.e. count of 250 ms) into timer register Enable microcontroller interrupts Turn on timer 1 END Timer 1 interrupt service routine START IF (int_rate*250) ms has elapsed THEN Complement speaker output ENDIF END Program Listing The full program listing is shown in Fig. 4.6. When the program starts a variable called count is set to 0 and the speaker is turned o€. Timer 1 is then initialized with the int_rate=2 so that interrupts are generated every 500 ms, i.e. an output frequency of 1 kHz. The state of the push-button switch is then checked. If the switch is pressed, the interrupt rate, int_rate, is changed to 4 so that interrupts will be generated at every 4  250 ms ˆ 1 ms i.e. the frequency of the generated waveform is changed to 500 Hz (1 ms on time and 1 ms o€ time). timer1() is the timer 1 interrupt service routine with interrupt number 3. In this routine, variable count is incremented and compared with the int_rate. When the two are equal, the speaker output is complemented, i.e. if the speaker is on it is turned o€, and if o€ it is turned on. The frequency of the generated tones can easily be changed by loading a di€erent value into the timer register or by changing the value of variable int_rate. PROJECT 15 ± Electronic Siren (Using the Timer Interrupt) Function This project shows how we can interface our microcontroller to a small speaker type audible device and generate a siren sound. When power is 96 Microcontroller Projects in C for the 8051 /**************************************************************************************************** PROJECT: PROJECT 14 FILE: DATE: PROCESSOR: PROJ14.C August 1999 AT892051 This is a simple speaker-based project. A miniature speaker is connected to bit 7 of port 1. The speaker normally operates when a varying signal is applied with the frequency in the audible range. A push-button switch is connected to bit 0 of port 3. When power is applied to the circuit, a 1 kHz audio signal is sent to the speaker. When the push-button switch is pressed, the signal frequency is changed to 500 Hz (period ˆ 2 ms). The speaker is connected to bit 7 of port 1 via a MOSFET transistor and the speaker is ON when the output of the port is at logic HIGH. Timer 1 is used to control the period of the square wave signals generated. ****************************************************************************************************/ #include sbit SPEAKER=P1^7; sbit PUSH_BUTTON =P3^0; int count,int_rate; /* Timer 1 initialization routine */ void init_timer() { ET1=1; TMOD=0x20; TH1=0x6; EA=1; TR1=1; } /* Timer 1 interrupt service routine */ timer1() interrupt 3 { count++; if(count == int_rate) { count=0; SPEAKER=~SPEAKER; } } /* Start of main program */ main() /*Reset count*/ /*Inc. count*/ /*Enable timer 1 int.*/ /*Timer 1 in Mode 2*/ /*Load for 250 ms count*/ /*Enable interrupts*/ /*Turn on timer 1*/ Sound Projects 97 { count=0; SPEAKER=0; Int_rate=2; init_timer(); for(;;) { if(PUSH_BUTTON == 0)int_rate=4; } } /*Set to 1 ms*/ /*Initialize count*/ /*Speaker OFF*/ /*Set for 500 ms*/ /*Initialize timer*/ /*Endless loop*/ Figure 4.6. Program listing of Project 14 applied to the circuit, a continuous siren type sound is output from the speaker. Both timer 0 and timer 1 of the microcontroller are used to generate the required tones. Circuit Diagram The circuit diagram of this project is the same as the one in Project 12 (i.e. Fig. 4.3) but there is no push-button switch and the buzzer is replaced with a small speaker. Bit 7 of port 1 is connected directly to a small speaker via a MOSFET transistor. The port output is in voltage mode so that the speaker will turn on when the port output is at logic HIGH (+5 V). Program Description In this project the frequency of the generated tone is varied continuously from 500 Hz to 10 kHz, thus producing a siren sound. Both timer 0 and timer 1 run at the same time and generate interrupts. Timer 1 generates the output tone and timer 0 changes the frequency of the generated tone continuously. This is how the timers operate: Timer 1 is in 8-bit auto-reload mode and the timer register is loaded with 50 ms (count of 206). Thus a timer 1 interrupt is generated every 50 ms. Inside the timer 1 interrupt service routine, a counter is incremented and its value compared to a global variable called int_rate. When the two are equal the speaker output is changed. The frequency of the generated output waveform is then as follows (notice that the period is twice the timer count value since half of the period is o€ and the other half is on): 98 Microcontroller Projects in C for the 8051 int_rate = 1 period = 100 ms frequency = 10 kHz int_rate = 2 period = 200 ms frequency = 5 kHz ............................................................... int_rate = 4 period = 400 ms frequency = 2.5 kHz int_rate = 5 period = 500 ms frequency = 2 kHz In general, we can say that the frequency of the generated tone is given by: freq = 10/int_rate where freq is in kHz. In this project, variable int_rate is varied from 100 down to 1, i.e. the frequency of the generated tone varies between 100 Hz and 10 kHz. Timer 0 of the microcontroller is used to change the frequency of the tone by changing the value of variable int_rate. Timer 0 is in 8-bit auto-reload mode and the timer register is loaded with 56 so that it generates interrupts at every 200 ms. Inside the timer 0 interrupt service routine a counter is used and variable int_rate is decremented by 1 when the counter counts by 200. Thus, variable int_rate will be decremented every 200  200 ms ˆ 40,000 ms or 40 ms. In summary, the frequency of the generated tone will vary every 20 ms from 100 Hz to 10 kHz. The result is that a siren type output will be generated on the speaker. The following PDL describes the functions of the program: Main program START Turn OFF speaker Initialize timer 1 for auto-reload 50 ms interrupts Initialize timer 0 for auto-reload 200 ms interrupts Set int_rate for 100 Hz DO FOREVER Wait for timer interrupts ENDDO Timer initialization routine START Enable timer 1 interrupts Set timer 1 to mode 8-bit auto-reload Load timer 1 with 206 (i.e. count of 50 ms) Sound Projects 99 Enable timer 0 interrupts Set timer 0 to mode 8-bit auto-reload Load timer 0 with 56 (i.e. count of 200 ms) Enable timer 0 interrupts Turn timer 1 on Turn timer 0 on END Timer 1 interrupt service routine START IF int_rate ms has elapsed THEN Complement speaker output ENDIF END Timer 0 interrupt service routine START IF 40 ms has elapsed THEN Decrement int_rate IF int_rate = 0 THEN Set int_rate for 100 Hz ENDIF ENDIF END Program Listing The full program listing is shown in Fig. 4.7. Variable SPEAKER is assigned to bit 7 of port 1. When the program starts, variables count and timer1_over¯ow are set to 0. The speaker is then turned o€. Timers 0 and 1 are initialized by calling function init_timers. The program then enters an endless loop and waits until the timer interrupts occur. Inside the timer 1 interrupt service routine, variable count is incremented and compared to variable int_rate. When the two are equal, count is reset to 0 and the speaker output is complemented. Inside the timer 0 interrupt service routine, variable timer1_over¯ow is incremented and when it reaches 200 (i.e. 200  200 ms ˆ 40 ms), it is reset to 0 and int_rate is decremented so that a higher frequency tone could be generated by timer 1. When int_rate reaches 0 it is reset back to 100 so that the process can repeat. 100 Microcontroller Projects in C for the 8051 /**************************************************************************************************** PROJECT: PROJECT 15 FILE: DATE: PROCESSOR: PROJ15.C August 1999 AT892051 This is a simple speaker-based siren project. A miniature speaker is connected to bit 7 of port 1. The speaker normally operates when an alternating signal is applied with the frequency in the audible range. When power is applied to the circuit, a 100 Hz audio signal is ®rst sent to the speaker using timer 1. Timer 0 then runs and changes the frequency of the tone from 100 Hz to 10 kHz, every 40 ms. The effect is that an audible siren type output is produced. The speaker is connected to bit 7 of port 1 via a MOSFET transistor and the buzzer is ON when the output of the port is at logic HIGH. Timers 0 and 1 are used to generate variable frequency and variable pitch output. ****************************************************************************************************/ #include sbit SPEAKER=P1^7; int count,timer1_over¯ow,int_rate; /* Timer initialization routine */ void init_timers() { ET1=1; TMOD=0x20; TH1=206; ET0=1; TMOD=TMOD | 2; TH0=56; EA=1; TR1=1; TR0=1; } /* Timer 1 interrupt service routine */ timer1() interrupt 3 { count++; if(count == int_rate) { count=0; SPEAKER=~SPEAKER; } } /*Reset count*/ /*Inc. count*/ /*Enable timer 1 interrupt*/ /*Timer 1 in Mode 2*/ /*Timer 1 50 ms count*/ /*Enable timer 0 int.*/ /*Timer 0 in Mode 2*/ /*Timer 0 200 ms count*/ /*Enable interrupts*/ /*Turn on timer 1*/ /*Turn on timer 0*/ Sound Projects 101 /* Timer 0 interrupt service routine */ timer0() interrupt 1 { timer1_over¯ow++; if(timer1_over¯ow == 200) { timer1_over¯ow=0; int_rate±; count=0; } } /* Start of main program */ main() { count=0; timer1_over¯ow=0; SPEAKER=0; int_rate=100; init_timers(); for(;;) { } } /*Speaker OFF*/ /*Set for 100 Hz */ /*Initialize timers*/ /*Endless loop*/ /*Initialize count*/ /*clear count*/ if(int_rate == 0)int_rate=100; /*if 40 ms */ Figure 4.7. Program listing of Project 15 PROJECT 16 ± Electronic Organ (Using the Timer Interrupt) Function This is a simple electronic organ project. A small speaker is connected to bit 0 of port 3 via a MOSFET transistor. Eight push-button switches are connected to port 1 to act as the keyboard for the electronic organ. Timer 1 of the microcontroller is used to generate time delays for the required frequencies. Only one octave (eight notes) is provided. Circuit Diagram The circuit diagram of this project is shown in Fig. 4.8. The speaker is connected to bit 0 of port 3. The keyboard switches are connected to port 1. 102 Microcontroller Projects in C for the 8051 Figure 4.8. Circuit diagram of Project 16 Bit 0 is assigned to note C, bit 1 is assigned to note D, bit 2 is assigned to note E and so on. The switches are normally held at logic HIGH with pull-up resistors (R2 to R9). Pressing a switch sends a logic LOW to the microcontroller port. Program Description In this project timer 1 is used to generate the tones for the electronic organ. The timer is in auto-reload mode and loaded to generate an interrupt every 50 ms (i.e. loaded with 206 for a 12 MHz crystal). An endless for loop is formed and the keyboard is scanned. When a key is pressed, the timer is reloaded with the correct value so that the required tone can be generated. The following octave was used for this project (the frequencies are in Hz): Notes: C D E F G A B C Freq: 262 294 330 349 392 440 494 524 Sound Projects 103 The periods of the notes in ms are then given by (period ˆ 1/frequency): Notes: C D E F G A B C Period: 3816 3401 3030 2865 2551 2272 2024 1908 The counter is loaded so that it generates an interrupt every 50 ms. The number of counts (N) required for each note is therefore given by dividing the period by 50 ms, as shown below: Notes: C N: 76 D 68 E 60 F 57 G 51 A 45 B 40 C 38 The following PDL describes the functions of the program: Main program START Turn o€ speaker Initialize timer 1 Initialize count DO FOREVER IF a key is pressed THEN Load value of the key into variable tone ENDIF ENDDO END Timer 1 interrupt service routine START Increment count IF count = tone THEN count = 0 Complement speaker output ENDIF END Program Listing The full program listing is shown in Fig. 4.9. When the program is started, the speaker is turned o€ and timer 1 is initialized to 8-bit auto-reload mode by calling function init_timer. An endless for loop is then formed and the keyboard is scanned. Normally port 1 contains the value 0xFF (255) when no keys are pressed. When a key is pressed the pin corresponding to that key goes to logic LOW. Variable key_pressed reads port 1 and complements the 104 Microcontroller Projects in C for the 8051 /**************************************************************************************************** PROJECT: PROJECT 16 FILE: DATE: PROCESSOR: PROJ16.C August 1999 AT892051 This is a simple electronic organ project. A small speaker is connected to bit 0 of port 3 via a MOSFET transistor. The speaker normally operates when an alternating signal is applied with the frequency in the audible range. Eight push-button switches are connected to port 1 to act as the keyboard for the electronic organ. Timer 1 is used to generate time delays for the required frequencies. ****************************************************************************************************/ #include sbit SPEAKER=P3^0; int count,tone; /* Timer 1 initialization routine */ void init_timer() { ET1=1; TMOD=0x20; TH1=206; TR1=1; EA=1; } /* Timer 1 interrupt service routine */ timer1() interrupt 3 { count++; if(count == tone) { count=0; SPEAKER=~SPEAKER; } } /* Start of main program */ main() { unsigned char key_pressed; count=0; SPEAKER=0; init_timer(); for(;;) /*Initialize count*/ /*Initialize timers*/ /*Endless loop*/ /*Reset count*/ /*Increment count*/ /*Enable timer 1 int.*/ /*Timer 1 in Mode 2*/ /*Timer 1 50 ms count*/ /*Run timer 1*/ /*Enable interrupts*/ Sound Projects 105 { if(P1 != 0xFF) { TR1=1; key_pressed=~P1; /*Turn on timer*/ /*Complement key*/ /*If a key pressed*/ /* Check which key pressed */ switch(key_pressed) { case 1: tone=76; break; case 2: tone=68; break; case 4: tone=60; break; case 8: tone=57; break; case 16: tone=51; break; case 32: tone=45; break; case 64: tone=40; break; case 128: tone=38; break; } } else { /* No key pressed */ SPEAKER=0; count=0; TR1=0; } } } /*Reset count*/ /*Stop timer*/ /*If key 1 is pressed...*/ Figure 4.9. Program listing of Project 16 106 Microcontroller Projects in C for the 8051 value read so that the numbers obtained correspond to the key numbers as powers of 2. Thus, as an example, when key C is pressed, key_pressed contains 1, when D is pressed, key_pressed is 2, when key E is pressed, key_pressed is 4 and so on. A switch statement is used to load variable tone with the correct timer value so that the required tone can be generated on the speaker. Components Required In addition to the standard components used for the microcontroller, the following components will be required for this project: S1 to S8 R2 to R9 B1 T1 SPDT switches 100K, 0.125 W resistors small speaker n-channel MOSFET transistor (e.g. VN66AFD) CHAPTER 5 TEMPERATURE PROJECTS Temperature measurement and control is one of the most common applications of microcontroller-based data acquisition systems. Four types of sensors are commonly used to measure temperature in commercial and industrial applications. These are thermocouples, resistive temperature devices (RTDs), thermistors, and integrated circuit (IC) temperature sensors. Each sensor has its unique advantages and disadvantages and by understanding how these sensors work, and what types of signal conditioning are required for each, we can make more accurate and reliable temperature measurement, monitoring, and control. The typical characteristics of various temperature sensors are: . Thermocouples: these are inexpensive, and the most common temperature sensors with a wide range of temperature range. Thermocouples work on the principle that when two dissimilar metals are combined, a voltage appears across the junction between the metals. By measuring this voltage, we can get a temperature reading. Di€erent combinations of metals create di€erent thermocouple voltages and there is a wide range of thermocouples available for di€erent applications. Thermocouples generate very low voltages, typically 50 mV=  C. These low-level signals require special signal conditioning to remove any possible noise. Thermocouples have non-linear relationships to the measured temperature and as a result it is necessary either to linearize the characteristics or to use look-up tables to obtain the actual temperature from the measured voltage. RTDs: an RTD is a resistor with its resistance changing with temperature. The most popular type of RTD is made of platinum and has a resistance of 100 at 0  C. Because RTDs are resistive devices, a current must pass through the RTD to produce a voltage that can be measured. The change in resistance is very small (about 0.4 /  C) and special circuitry is generally needed to measure the small changes in temperature. One of the drawbacks of RTDs is their non-linear change in resistance with temperature. Thermistors: thermistors are metal oxide semiconductor devices whose resistance changes with temperature. One of the advantages of thermistors is their fast responses and high sensitivity. For example, a typical thermistor . . 108 Microcontroller Projects in C for the 8051 may have a resistance of 50 k at 25  C, but have a resistance of only 2 k at 85  C. Like RTDs, a current is passed through a thermistor and the voltage across the thermistor is measured. Thermistors are very non-linear devices and look-up tables are usually used to convert the measured voltage to temperature. Thermistors are very small and one disadvantage of this is that they can be self-heating under a large excitation current. This of course increases the temperature of the device and can give erroneous results. . IC temperature sensors: integrated circuit temperature sensors are usually 3or 8-pin active devices that require a power supply to operate and give out a voltage which is directly proportional to the temperature. There are basically two types of IC temperature sensor: analogue sensors are usually 3-pin devices and give out an analogue voltage of typically 10 mV/  C which is directly proportional to the temperature; digital temperature sensors provide 8- or 9-bit serial digital output data which is directly proportional to the temperature. In this chapter we shall be looking at how we can interface various temperature sensors to our microcontroller in order to measure and display the ambient temperature. PROJECT 17 ± Using a Digital Temperature Sensor Function This project shows how we can interface a DS1620 type digital temperature sensor to our microcontroller. The ambient temperature is measured continuously and then displayed in degrees centigrade on three TIL311 type alphanumeric displays. Positive temperature is displayed from 0  C to 125  C. Negative temperature is displayed with a leading letter `E' in the range down to À55  C. Circuit Diagram The block diagram of this project is shown in Fig. 5.1. DS1620 is a digital IC temperature sensor which measures the ambient temperature and provides the output as 9 bits of digital serial data. The microcontroller extracts the temperature data from the DS1620 and then displays the temperature on three TIL311 type alphanumeric displays. Before describing the circuit diagram in detail, it is useful to look at the operation of the DS1620 temperature sensor IC. Temperature Projects 109 Figure 5.1. Block diagram of Project 17 DS1620 Digital Thermometer IC DS1620 is a digital thermometer and thermostat IC that provides 9 bits of serial data to indicate the temperature of the device. The pin con®guration of the DS1620 is shown in Fig. 5.2. VDD is the power supply which is normally connected to a ‡5 V supply. DQ is the data input/output pin. CLK is the clock input. RST is the reset input. The device can also act as a thermostat. THIGH is driven high if the DS1620's temperature is greater than or equal to a user de®ned temperature TH. Similarly, TLOW is driven high if the DS1620's temperature is less than or equal to a user de®ned temperature TL. TCOM is driven high when the temperature exceeds TH and stays high until the temperature falls below TL. User de®ned temperatures TL and TH are stored in non-volatile memory of the device so that they are not lost even after removal of the power. Data is output from the device as 9 bits, with the LSB sent out ®rst. The temperature is provided in 2's complement format from À55  C to ‡125  C, in steps of 0.5  C. Table 5.1 shows the relationship between the temperature and data output by the device. Figure 5.2. Pin con®guration of DS1620 110 Microcontroller Projects in C for the 8051 Table 5.1 Temperature/data relationship of DS1620 2's complement ± ± ± ± 001 032 06E Digital output (decimal) 250 50 1 0 511 462 402 Temp. (  C) Digital output Digital output (binary) (hex) ‡125 ‡25 0.5 0 À0.5 À25 À55 0 11111010 0 00110010 0 00000001 0 00000000 1 11111111 1 11001110 1 10010010 0FA 032 001 000 1FF 1CE 192 Operation of DS1620 Data input and output is through the DQ pin. When RST input is high, serial data can be written or read by pulsing the clock input. Data is written or read from the device in two parts. First, a protocol is sent and then the required data is read or written. The protocol is 8-bit data and the protocol de®nitions are given in Table 5.2. For example, to write the thermostat value TH, the hexadecimal protocol data 01 is ®rst sent to the device. After issuing this Table 5.2 PROTOCOL Write TH Write TL Write con®guration Stop conversion Read TH Read TL Read temperature Read con®guration Start conversion DS1620 Protocol de®nitions PROTOCOL DATA (hex) 01 02 0C 22 A1 A2 AA AC EE Temperature Projects 111 command, the next nine clock cycles clock in the 9-bit temperature limit which will set the threshold for operation of the THIGH output. For example, the following data (in hexadecimal) should be sent to the device to set it for a TH limit of ‡50  C and TL limit of ‡20  C and then subsequently to start the conversion: 01 64 02 28 EE Send Send Send Send Send TH protocol TH limit of 50 (64 hex ˆ 100 decimal) TL protocol TL limit of 20 (28 hex ˆ 40 decimal) conversion start protocol A con®guration/status register is used to program various operating modes of the device. This register is written with protocol 0C (hex) and the status is read with protocol AC (hex). Some of the important con®guration/status register bits are as follows: Bit 0: This is the 1 shot mode. If this bit is set, the DS1620 will perform one temperature conversion when the start convert protocol is sent. If this bit is 0, the device will perform continuous temperature conversions. This bit should be set to 1 for operation with a microcontroller or microprocessor. This is the TLF ¯ag and is set to 1 when the temperature is less than or equal to the value TL. This is the THF bit and is set to 1 when the temperature is greater than or equal to the value of TH. This is the DONE bit and is set to 1 when a conversion is complete. Bit 1: Bit 5: Bit 6: Bit 7: The complete circuit diagram of this project is shown in Fig. 5.3. Bit 2 of port 3 is connected to the RST input of DS1620, bit 1 is connected to the clock input and bit 0 of port 3 is connected to the DQ pin of the DS1620. Three TL311 type alphanumeric displays are connected to port 1 of the microcontroller. Digit 1 is controlled from bit 7 of port 1, digit 2 from bit 6 of port 1, and digit 3 from bit 5 of port 1. Program Description The program reads the temperature from the DS1620 thermometer IC and displays the temperature on three TIL311 type displays continuously with 1 second delay between each displayed output. The following PDL describes the operation of the program: 112 Microcontroller Projects in C for the 8051 Figure 5.3. Circuit diagram of Project 17 Main program START Set digit latches to 1 Con®gure DS1620 Start temperature conversion DO FOREVER Read temperature Display temperature Wait a second ENDDO END Function con®gure DS1620 START Set con®guration/status register to 2 (i.e. continuous operation) END Temperature Projects 113 Function start temperature conversion START Send protocol EE (hex) to start temperature conversion END Function read temperature START Call function read_from_ds1620 to get the temperature END Function read_from_ds1620 START Set RST bit to 1 Read 9-bit serial temperature data from DS1620 Set RST bit to 0 END Function display temperature START IF temperature is negative THEN Get 2's complement of the temperature reading Divide temperature by 2 to get real temperature Set digit 1 to display letter `E' Display temperature digits ELSE Divide temperature by 2 to get real temperature Display temperature digits ENDIF END Program Listing The full program listing is given in Fig. 5.4. The display digit latches and the DS1620 control lines are assigned to bit variables at the beginning of the program. Also the used protocols are de®ned and assigned to global variables. For example, read_temp is assigned to hexadecimal number AA, start_conv is assigned to hexadecimal number EE and so on. When the program starts, the digit latches digit1_latch, digit2_latch, and digit3_latch are all set to 1 to avoid any erroneous writes to the displays. A function con®gure_ds1620 is then called to set the con®guration register/status 114 Microcontroller Projects in C for the 8051 /**************************************************************************************************** PROJECT: PROJECT 17 FILE: DATE: PROCESSOR: PROJ17.C August 1999 AT892051 This is a temperature monitoring project. A DS1620 type digital thermometer is used to read the ambient temperature. The temperature is then displayed on three TL311 type alphanumeric displays. The temperature range is À55 C to ‡125 C. Positive temperature is displayed with leading zeros. Negative temperatures are displayed by inserting the letter `E' in front of the display. The display accuracy is ‡/À 1  C, i.e. there is no decimal point in the displayed data. The display is updated every second. ****************************************************************************************************/ #include sbit digit1_latch = P1^7; sbit digit2_latch = P1^6; sbit digit3_latch = P1^5; sbit ds1620_dq = P3^0; sbit ds1620_clk = P3^1; sbit ds1620_rst = P3^2; #de®ne read_temp 0xAA #de®ne start_conv 0xEE #de®ne write_con®g 0x0C /*digit 1 latch*/ /*digit 2 latch*/ /*digit 3 latch*/ /*DS1620 data pin*/ /*DS1620 clock pin*/ /*DS1620 reset pin*/ /*read temp command*/ /*start conversion command*/ /*write con®g command*/ /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++);> 255) { x=~x; x++; x=x & 0xFF; x=x/2; /*complement temp*/ /*add 1 for 2s comp*/ /*extract lower 8 bits*/ /*get real temp*/ /*if negative*/ Temperature Projects 115 ®rst=14; second=x/10; third=x-10*second; } else { x=x/2; ®rst=x/100; s=x-100*®rst; second=s/10; third=s-second*10; } P1=®rst | 0xE0; digit1_latch=0; digit1_latch=1; P1=second | 0xE0; digit2_latch=0; digit2_latch=1; P1=third | 0xE0; digit3_latch=0; digit3_latch=1; } /*display leading `E'*/ /*temp is positive*/ /*extract digit data*/ /*Send digit1 data*/ /*Latch the digit1 data*/ /*Set digit1 latch on*/ /*Send digit2 data*/ /*Latch the digit2 data*/ /*Set digit2 latch on*/ /*Send digit3 data*/ /*Latch digit3 data*/ /*Set digit3 latch on*/ /* This function sends a data bit to DS1620 thermometer IC */ void write_ds1620_bit(unsigned char b) { ds1620_dq=b; ds1620_clk=0; ds1620_clk=1; ds1620_dq=1; } /* This function reads a data bit from DS1620 */ unsigned char read_ds1620_bit() { unsigned char b; ds1620_clk=0; b=ds1620_dq; ds1620_clk=1; return (b); } /* This function writes data/con®guration to DS1620 */ /*set clock 0*/ /*read a bit*/ /*set clock 1*/ /*return bit*/ /*send bit*/ /*set clock 0*/ /*set clock 1*/ /*set data 1*/ 116 Microcontroller Projects in C for the 8051 void write_to_ds1620(unsigned char ds1620_function, unsigned char ds1620_data, unsigned char bit_count) { unsigned char i,this_bit; ds1620_rst=1; for(i=0;i<8;i++) this_bit="ds1620_function">> i; this_bit=this_bit & 0x01; write_ds1620_bit(this_bit); } for(i=0;i> i; this_bit=this_bit & 0x01; write_ds1620_bit(this_bit); } ds1620_rst=0; } /*set reset to 0*/ /*send data...*/ /*set reset to 1*/ /*send function...*/ /* This function reads data/con®guration from the DS1620 */ unsigned int read_from_ds1620(unsigned char ds1620_function, unsigned char bit_count) { unsigned char i,this_bit; unsigned int ds1620_data; ds1620_data=0; ds1620_rst=1; for(i=0;i<8;i++) this_bit="this_bit" i="0;i<< ds1620_rst="0;" this_bit="ds1620_function">> i; /*initialize data*/ /*set reset to 1*/ Temperature Projects 117 { write_to_ds1620(write_con®g,2,8); wait_a_second(); } /* This function starts the conversion */ void start_temp_conv() { write_to_ds1620(start_conv,0,0); } /* This function reads the temperature */ unsigned int read_temperature() { unsigned int t; t=read_from_ds1620(read_temp,9); return (t); } /* Start of main program */ main() { unsigned int TEMP; digit1_latch=1; digit2_latch=1; digit3_latch=1; con®gure_ds1620(); start_temp_conv(); for(;;) { TEMP=read_temperature(); display_temperature(TEMP); wait_a_second(); } } /*read temperature*/ /*Output to TIL311*/ /*wait a second*/ /*Set digit1 latch*/ /*set digit2 latch*/ /*set digit3 latch*/ /*con®gure DS1620*/ /*start conversion*/ /*endless loop*/ /*read temp*/ /*return temp*/ Figure 5.4. Program listing of Project 17 for continuous operation. Temperature conversion is then started by calling the function start_temp_conversion. This function sends protocol EE (hex) to the DS1620. An endless loop is then formed using the for statement with no parameters. Inside this loop, function read_temperature reads 118 Microcontroller Projects in C for the 8051 the 9-bit temperature value and returns in variable TEMP. Function display_temperature displays the temperature on the three TIL311 displays. This loop is repeated with about a 1 second delay between each output. Function read_temperature returns the temperature to the calling program as an unsigned integer. This function calls function read_from_ds1620 with the argument AA (in hex) to get the temperature. Function read_from_ds1620 is a general routine which reads data from the DS1620. This function sends a protocol data to the DS1620 and then reads data bytes from the DS1620 corresponding to the sent protocol. The RST input of the device is ®rst set to 1. A for loop is then formed to iterate eight times to send serial protocol data to the DS1620. LSB is sent out ®rst. Local variable this_bit stores the bit to be sent out at each iteration. Another for loop reads data from the DS1620 and stores this data in variable ds1620_data. At the end of the read cycle the RST input is set back to 0 and the data in ds1620_data is returned to the caller. Function write_to_ds1620 is a general function and it sends a protocol, followed by data bits, to the DS1620. The RST input of the DS1620 is ®rst set to 1. A for loop is then formed to iterate eight times and the protocol bits are sent out serially to the DQ input of the DS1620. Variable this_bit stores the bit to be sent out at each iteration. After this, another for loop sends out the required number of data bits to the DS1620. At the end of the write cycle, the RST input is returned to 0. Function display_temperature receives the temperature data as its argument and displays the temperature on the three TIL311 type alphanumeric displays. If the temperature is negative, the ®rst display digit is set to display letter `E'. The temperature value to be displayed is divided by 2 since the temperature is returned by the DS1620 in 0.5  C intervals. For example, a reading of decimal 100 corresponds to 50  C. Each digit is displayed after converting the data to decimal format. Components Required In addition to the basic components required by the microcontroller, the following components will be required for this project: DS1620 TIL311 thermometer IC alphanumeric displays (3 o€) Temperature Projects 119 PROJECT 18 ± Digital Thermometer with Centigrade/ Fahrenheit Output Function This project is similar to Project 17, but in addition the outputs can display the temperature in both Centigrade (  C) and Fahrenheit (  F). An SPDT switch is connected to bit 3 of port 3 and the output of this switch is normally held at logic high with a pull-up resistor. In this state the output display is in  C. When the switch is pressed, the display changes to show the temperature in  F. The rest of the project is the same as Project 17, i.e. the temperature is measured with a DS1620 type thermometer IC and the output is displayed on three TIL311 type alphanumeric displays. Circuit Diagram The block diagram of this project is shown in Fig. 5.5. The circuit diagram is similar to the circuit of Project 17 with the addition of an SPDT switch to bit 3 of port 3. The temperature is sensed by the DS1620 thermometer IC and the output is displayed either in  C or in  F based upon the state of the SPDT switch. The full circuit diagram is shown in Fig. 5.6. Program Description The program is the same as the one in Project 17 except that the state of the SPDT switch is monitored and when the switch is pressed, the temperature is converted from  C to  F and then displayed accordingly. Negative temperatures are displayed by inserting the leading letter `E'. Figure 5.5. Block diagram of Project 18 120 Microcontroller Projects in C for the 8051 Figure 5.6. Circuit diagram of Project 18 Program Listing The full program listing of this project is shown in Fig. 5.7. Only the parts which are di€erent from Project 17 are described here. Variable mode is assigned to bit 3 of port 3. The value of mode is checked in function display_temperature. If mode is zero (i.e. in Fahrenheit mode), the temperature is converted to  F by multiplying by 1.8 and adding 32. The ®nal temperature is then displayed as in Project 17. Components Required In addition to the standard components required by the microcontroller, the following components will be required for this project: Temperature Projects 121 /**************************************************************************************************** PROJECT: PROJECT 18 FILE: DATE: PROCESSOR: PROJ18.C August 1999 AT892051 This is a temperature monitoring project. A DS1620 type digital thermometer is used to read the ambient temperature. The temperature is then displayed on three TL311 type alphanumeric displays. The temperature range is À55  C to ‡125  C. Positive temperature is displayed with leading zeros. Negative temperatures are displayed by inserting the letter `E' in front of the display. The display accuracy is ‡/À1  C, i.e. there is no decimal point in the displayed data. The display is updated every second. Bit 3 of port 3 is connected to a switch. This switch is normally held at logic 1 with a pull-up resistor. When the switch is 1, the temperature is displayed in degrees centigrade. When the switch is 0, the temperature is displayed in degrees Fahrenheit. ****************************************************************************************************/ #include sbit digit1_latch = P1^7; sbit digit2_latch = P1^6; sbit digit3_latch = P1^5; sbit mode = P3^3; sbit ds1620_dq = P3^0; sbit ds1620_clk = P3^1; sbit ds1620_rst = P3^2; #de®ne read_temp 0xAA #de®ne start_conv 0xEE #de®ne write_con®g 0x0C /*digit 1 latch*/ /*digit 2 latch*/ /*digit 3 latch*/ /*centigrade/fahrenheit select*/ /*DS1620 data pin*/ /*DS1620 clock pin*/ /*DS1620 reset pin*/ /*read temp command*/ /*start conversion command*/ /*write con®g command*/ /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++);> 255) { x=~x; x++; x=x & 0xFF; x=x/2; if(mode == 0)x=1.8*x+32; ®rst=14; second=x/10; third=x-10*second; } else { x=x/2; if(mode == 0)x=1.8*x+32; ®rst=x/100; s=x-100*®rst; second=s/10; third=s-second*10; } P1=®rst | 0xE0; digit1_latch=0; digit1_latch=1; P1=second | 0xE0; digit2_latch=0; digit2_latch=1; P1=third | 0xE0; digit3_latch=0; digit3_latch=1; } /* This function sends a data bit to DS1620 thermometer IC */ void write_ds1620_bit(unsigned char b) { ds1620_dq=b; ds1620_clk=0; ds1620_clk=1; ds1620_dq=1; } /* This function reads a data bit from DS1620 */ unsigned char read_ds1620_bit() { /*send bit*/ /*set clock 0*/ /*set clock 1*/ /*set data 1*/ /*Send digit1 data*/ /*Latch the digit1 data*/ /*Set digit1 latch on*/ /*Send digit2 data*/ /*Latch the digit2 data*/ /*Set digit2 latch on*/ /*Send digit3 data*/ /*Latch digit3 data*/ /*Set digit3 latch on*/ /*temp is positive*/ /*in fahrenheit*/ /*extract digit data*/ /*complement temp*/ /*add 1 for 2s comp*/ /*extract lower 8 bits*/ /*get real temp*/ /*in fahrenheit*/ /*display leading `E'*/ /*if negative*/ Temperature Projects 123 unsigned char b; ds1620_clk=0; b=ds1620_dq; ds1620_clk=1; return (b); } /* This function writes data/con®guration to DS1620 */ void write_to_ds1620(unsigned char ds1620_function, unsigned char ds1620_data, unsigned char bit_count) { unsigned char i,this_bit; ds1620_rst=1; for(i=0;i<8;i++) this_bit="ds1620_function">> i; this_bit=this_bit & 0x01; write_ds1620_bit(this_bit); } for(i=0;i> i; this_bit=this_bit & 0x01; write_ds1620_bit(this_bit); } ds1620_rst=0; } /*set reset to 0*/ /*send data...*/ /*set reset to 1*/ /*send function...*/ /*set clock 0*/ /*read a bit*/ /*set clock 1*/ /*return bit*/ /* This function reads data/con®guration from the DS1620 */ unsigned int read_from_ds1620(unsigned char ds1620_function, unsigned char bit_count) { unsigned char i,this_bit; unsigned int ds1620_data; ds1620_data=0; ds1620_rst=1; for(i=0;i<8;i++) this_bit="this_bit" i="0;i> i; /*initialize data*/ /*set reset to 1*/ 124 Microcontroller Projects in C for the 8051 { ds1620_data=ds1620_data | read_ds1620_bit() << ds1620_rst="0;" t="read_from_ds1620(read_temp,9);" digit1_latch="1;" digit2_latch="1;" digit3_latch="1;" temp="read_temperature();"> sbit digit1_latch = P1^7; sbit digit2_latch = P1^6; sbit digit3_latch = P1^5; sbit ds1620_dq = P3^0; sbit ds1620_clk = P3^1; sbit ds1620_rst = P3^2; #de®ne read_temp 0xAA #de®ne start_conv 0xEE #de®ne write_con®g 0x0C #de®ne write_thigh 0x01 /*digit 1 latch*/ /*digit 2 latch*/ /*digit 3 latch*/ /*DS1620 data pin*/ /*DS1620 clock pin*/ /*DS1620 reset pin*/ /*read temp command*/ /*start conversion command*/ /*write con®g command*/ /*write THIGH*/ /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++);> 255) { x=~x; x++; x=x & 0xFF; x=x/2; ®rst=14; second=x/10; third=x-10*second; } else { x=x/2; ®rst=x/100; s=x-100*®rst; second=s/10; third=s-second*10; } P1=®rst | 0xE0; digit1_latch=0; digit1_latch=1; P1=second | 0xE0; digit2_latch=0; digit2_latch=1; P1=third | 0xE0; digit3_latch=0; digit3_latch=1; } /* This function sends a data bit to DS1620 thermometer IC */ void write_ds1620_bit(unsigned char b) { ds1620_dq=b; ds1620_clk=0; ds1620_clk=1; ds1620_dq=1; } /* This function reads a data bit from DS1620 */ unsigned char read_ds1620_bit() { unsigned char b; /*send bit*/ /*set clock 0*/ /*set clock 1*/ /*set data 1*/ /*Send digit1 data*/ /*Latch the digit1 data*/ /*Set digit1 latch on*/ /*Send digit2 data*/ /*Latch the digit2 data*/ /*Set digit2 latch on*/ /*Send digit3 data*/ /*Latch digit3 data*/ /*Set digit3 latch on*/ /*temp is positive*/ /*extract digit data*/ /*complement temp*/ /*add 1 for 2s comp*/ /*extract lower 8 bits*/ /*get real temp*/ /*display leading `E'*/ /*if negative*/ Temperature Projects 129 ds1620_clk=0; b=ds1620_dq; ds1620_clk=1; return (b); } /*set clock 0*/ /*read a bit*/ /*set clock 1*/ /*return bit*/ /* This function writes data/con®guration to DS1620 */ void write_to_ds1620(unsigned char ds1620_function, unsigned char ds1620_data, unsigned char bit_count) { unsigned char i,this_bit; ds1620_rst=1; for(i=0;i<8;i++) this_bit="ds1620_function">> i; this_bit=this_bit & 0x01; write_ds1620_bit(this_bit); } for(i=0;i> i; this_bit=this_bit & 0x01; write_ds1620_bit(this_bit); } ds1620_rst=0; } /*set reset to 0*/ /*send data...*/ /*set reset to 1*/ /*send function...*/ /* This function reads data/con®guration from the DS1620 */ unsigned int read_from_ds1620(unsigned char ds1620_function, unsigned char bit_count) { unsigned char i,this_bit; unsigned int ds1620_data; ds1620_data=0; ds1620_rst=1; for(i=0;i<8;i++) this_bit="this_bit" i="0;i> i; /*initialize data*/ /*set reset to 1*/ 130 Microcontroller Projects in C for the 8051 ds1620_data=ds1620_data | read_ds1620_bit() << ds1620_rst="0;" t="read_from_ds1620(read_temp,9);" digit1_latch="1;" digit2_latch="1;" digit3_latch="1;" temp="read_temperature();"> sbit digit1_latch = P1^7; sbit digit2_latch = P1^6; sbit digit3_latch = P1^5; sbit ds1620_dq = P3^0; sbit ds1620_clk = P3^1; sbit ds1620_rst = P3^2; #de®ne read_temp 0xAA #de®ne start_conv 0xEE #de®ne write_con®g 0x0C #de®ne write_thigh 0x01 #de®ne write_tlow 0x02 /*digit 1 latch*/ /*digit 2 latch*/ /*digit 3 latch*/ /*DS1620 data pin*/ /*DS1620 clock pin*/ /*DS1620 reset pin*/ /*read temp command*/ /*start conversion command*/ /*write con®g command*/ /*write THIGH*/ /*write TLOW*/ /* Function to delay about a second */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++);> 255) { x=~x; x++; x=x & 0xFF; x=x/2; ®rst=14; second=x/10; third=x-10*second; } else { x=x/2; ®rst=x/100; s=x-100*®rst; second=s/10; third=s-second*10; } P1=®rst | 0xE0; digit1_latch=0; digit1_latch=1; P1=second | 0xE0; digit2_latch=0; digit2_latch=1; P1=third | 0xE0; digit3_latch=0; digit3_latch=1; } /* This function sends a data bit to DS1620 thermometer IC */ void write_ds1620_bit(unsigned char b) { ds1620_dq=b; ds1620_clk=0; ds1620_clk=1; ds1620_dq=1; } /* This function reads a data bit from DS1620 */ unsigned char read_ds1620_bit() { unsigned char b; /*send bit*/ /*set clock 0*/ /*set clock 1*/ /*set data 1*/ /*Send digit1 data*/ /*Latch the digit1 data*/ /*Set digit1 latch on*/ /*Send digit2 data*/ /*Latch the digit2 data*/ /*Set digit2 latch on*/ /*Send digit3 data*/ /*Latch digit3 data*/ /*Set digit3 latch on*/ /*temp is positive*/ /*extract digit data*/ /*complement temp*/ /*add 1 for 2s comp*/ /*extract lower 8 bits*/ /*get real temp*/ /*display leading `E'*/ /*if negative*/ Temperature Projects 135 ds1620_clk=0; b=ds1620_dq; ds1620_clk=1; return (b); } /*set clock 0*/ /*read a bit*/ /*set clock 1*/ /*return bit*/ /* This function writes data/con®guration to DS1620 */ void write_to_ds1620(unsigned char ds1620_function, unsigned char ds1620_data, unsigned char bit_count) { unsigned char i,this_bit; ds1620_rst=1; for(i=0;i<8;i++) this_bit="ds1620_function">> i; this_bit=this_bit & 0x01; write_ds1620_bit(this_bit); } for(i=0;i> i; this_bit=this_bit & 0x01; write_ds1620_bit(this_bit); } ds1620_rst=0; } /*set reset to 0*/ /*send data...*/ /*set reset to 1*/ /*send function...*/ /* This function reads data/con®guration from the DS1620 */ unsigned int read_from_ds1620(unsigned char ds1620_function, unsigned char bit_count) { unsigned char i,this_bit; unsigned int ds1620_data; ds1620_data=0; ds1620_rst=1; for(i=0;i<8;i++) this_bit="this_bit" i="0;i> i; /*initialize data*/ /*set reset to 1*/ 136 Microcontroller Projects in C for the 8051 ds1620_data=ds1620_data | read_ds1620_bit() << ds1620_rst="0;" t="read_from_ds1620(read_temp,9);" digit1_latch="1;" digit2_latch="1;" digit3_latch="1;" temp="read_temperature();"> sbit DISPLAY_CLOCK=P3^0; sbit DISPLAY_DATA =P3^1; sbit ADC_RD = P3^2; sbit ADC_WR = P3^4; unsigned int TEMPERATURE; /*display clock*/ /*display data*/ /*A-D RD input*/ /*A-D WR input*/ /*A-D data*/ /* This function provides a 1 second delay */ void wait_a_second() { unsigned int x; for(x=0;x<33000;x++); display_clock="1;" display_clock="0;" n="LED_ARRAY[x]" i="1;i<=" top_bit="n" display_data="1;" display_data="0;" n="n" rst="n/1000;" r="n-1000*®rst;" second="r/100;" r="r-100*second;" third="r/10;" fourth="r-third*10;" display_data="1;" display_data="0;" display_data="0;" display_clock="0;" display_data="1;" display_data="0;" i="1;i<=" adc_rd="1;" adc_wr="1;" it1="1;" ex1="1;" ea="1;" adc_wr="0;" adc_wr="1;" adc_rd="0;" temperature="P1;" adc_rd="1;" temperature="TEMPERATURE*19.60;" scon="0x50;" tmod="0x20;" th1="0xF3;" tr1="1;" ti="1;"> #include /* Function to initialize the RS232 serial port */ void serial_init() { SCON=0x50; TMOD=0x20; TH1=0xF3; TR1=1; TI=1; } /* Start of main program */ main() { serial_init(); for(;;) { printf(`THIS IS AN RS232 TEST MESSAGE\n'); } } /*initialize serial port*/ /*Start of loop*/ /* setup for 8-bit data */ /* setup timer 1 for auto-reload */ /* setup for 2400 baud */ /* turn on timer 1 */ /* indicate ready to transmit */ Figure 6.6. Program listing of Project 22 A Simple Serial Output Function The 89C2051 microcontroller is equipped with 2 Kbytes of memory. It was shown in the previous example that using the built-in printf function causes a large part of this memory to be used, leaving little space for other operations. Figure 6.7 shows a program listing that performs serial output functions without using the printf function and the complete program occupies about 400 bytes of memory. In this program, the serial transmit register of the RS232 Serial Communication Projects 155 microcontroller (SBUF) is used to send out data directly. Function send_serial transmits a null-terminated string to the RS232 port of the microcontroller. The program waits until the transmit register is empty (TI ˆ 1) before sending out the next character. In this example, the string `ANOTHER TEST' is output continuously. Notice that calling this function with variable crlf causes a carriage return and line feed to be output at the end of the test message. Components Required The following components will be required in addition to the standard microcontroller components: MAX232 IC C4 22 mF capacitor (4 o€) 9 way or 25 way RS232 connector PROJECT 23 ± Input/Output Example Using the RS232 Port Function This project shows how we can input and output serial data using the built-in C functions. In this example, the user is prompted to enter a character through the RS232 terminal. The program then ®nds the next character (i.e. increments the character by one) and outputs it to the user's terminal. Circuit Diagram The circuit diagram of this project is the same as in Project 22 (i.e. Fig. 6.5). Program Description The RS232 serial port is initialized to operate at 2400 baud. The user is then prompted to enter a character. This character is incremented by one and sent to the serial output port. The following PDL describes the functions of the program: START Initialize serial port DO FOREVER Display `Enter a character' Read a character Increment the character Display the next character ENDDO END 156 Microcontroller Projects in C for the 8051 /*************************************************************************************************** PROJECT: PROJECT 22 FILE: DATE: PROCESSOR: PROJ22-1.C August 1999 AT892051 This project sends the text message: `ANOTHER TEST' to the RS232 serial port of the microcontroller. The message is sent out continuously with a carriage return and line feed at the end of each line. This program does not use the built-in function printf. The program occupies about 400 bytes of memory. ***************************************************************************************************/ #include #include /* Function to initialize the RS232 serial port */ void serial_init() { SCON=0x50; TMOD=0x20; TH1=0xF3; TR1=1; TI=1; } /* This function displays a null-terminated string on the RS232 port */ void send_serial(unsigned char *s) { while(*s != 0x0) { SBUF=*s; While(! TI) { } TI=0; s++; } } /* Start of main program */ main() { unsigned char crlf[ ]={0x0D,0x0A,0x0}; /*carriage return, line feed*/ serial_init(); for(;;) /*initialize serial port*/ /*Start of loop*/ /*get the next character*/ /*send out the character*/ /*wait until sent*/ /* setup for 8-bit data */ /* setup timer 1 for auto-reload */ /* setup for 2400 baud */ /* turn on timer 1 */ /* indicate ready to transmit */ RS232 Serial Communication Projects 157 { send_serial(`ANOTHER TEST'); send_serial(crlf); } } Figure 6.7. Output program which does not use the printf function Program Listing The program listing is shown in Fig. 6.8. Function serial_init initializes the serial port for operation at 2400 baud with a 12 MHz crystal. Built-in function printf is used to prompt the user to enter a character. A character is then read from the user's terminal using the standard C built-in function getchar and this character is stored in a variable called c. Finally, this character is incremented by one and is output to the RS232 port using function printf. The above process is repeated inde®nitely. This program occupies 1164 bytes of memory. Input/Output Without Using the Built-in Functions The above program uses the standard C built-in functions printf and getchar. As a result the program is big. An example program is given in Fig. 6.9 which does not use these built-in functions and thus occupies much less space in memory. Function serial_init is the same as before but note that the serial port interrupts are enabled (EA ˆ 1 and ES ˆ 1). Function send_serial sends a null-terminated string to the serial output port. Similarly, function send_1_char sends a single character to the serial port. Serial data is read in via the serial port interrupt service routine (serial). Whenever a character is transmitted or received, the interrupt service routine is activated automatically. The interrupt number of the serial port is 4. Here, the receive interrupt register (RI) is checked and a character is assumed to be received from the serial port if RI is non-zero. The received character is copied from SBUF to a variable called received_character. The main program calls function send_serial to display the message `Enter a character'. If a character is received, this character is echoed on the user's terminal and the next character is displayed by incrementing and outputting the variable received_character. Function send_1_char is then used to send a carriage return and line feed after each output. 158 Microcontroller Projects in C for the 8051 /**************************************************************************************************** PROJECT: PROJECT 23 FILE: DATE: PROCESSOR: PROJ23.C August 1999 AT892051 This project is an example of using both the input and the output serial data routines. A character is received from the serial port. The next character is then calculated and output to the user's RS232 terminal. This program occupies 1164 bytes in memory. ****************************************************************************************************/ #include #include /* Function to initialize the RS232 serial port */ void serial_init() { SCON=0x50; TMOD=0x20; TH1=0xF3; TR1=1; TI=1; } /* Start of main program */ main() { char c; serial_init(); for(;;) { printf(`\nEnter a character'); c=getchar(); c++; } } /*read a character*/ /*next character*/ /*initialize serial port*/ /*Start of loop*/ /* setup for 8-bit data */ /* setup timer 1 for auto-reload */ /* setup for 2400 baud */ /* turn on timer 1 */ /* indicate ready to transmit */ printf(`The next character is: %c:,c); Figure 6.8. Program listing of Project 23 RS232 Serial Communication Projects 159 /**************************************************************************************************** PROJECT: PROJECT 23 FILE: DATE: PROCESSOR: PROJ23-1.C August 1999 AT892051 This project reads a character from the user's terminal, ®nds the next character and displays on the user's terminal. C built-in functions are not used in this program. This program occupies 225 bytes of memory. ****************************************************************************************************/ #include #include unsigned char received_character; int received_¯ag; /* Function to initialize the RS232 serial port */ void serial_init() { SCON=0x50; TMOD=0x20; TH1=0xF3; TR1=1; TI=1; EA=1; ES=1; } /* This function displays a null-terminated string on the RS232 port */ void send_serial(unsigned char *s) { while(*s != 0x0) { SBUF=*s; while(! TI) { } TI=0; s++; } } /* This function sends a single character to the serial port */ void send_1_char(unsigned char c) /*get the next character*/ /*send out the character*/ /*wait until sent*/ /* setup for 8-bit data */ /* setup timer 1 for auto-reload */ /* setup for 2400 baud */ /* turn on timer 1 */ /* indicate ready to transmit */ /*enable interrupts*/ /*enable serial port interrupts*/ 160 Microcontroller Projects in C for the 8051 { SBUF=c; while(! TI) { } TI=0; } /* Serial port interrupt service routine. Program jumps to this routine when a character is transmitted or received */ serial() interrupt 4 { if(RI) { received_character=SBUF; RI=0; received_¯ag=1; } } /* Start of main program */ main() { received_¯ag=0; serial_init(); for(;;) { send_serial(`Enter a character:'); while(received_¯ag == 0) { } received_¯ag=0; send_1_char(received_character); send_serial(`The next character is:'); received_character++; send_1_char(received_character); send_1_char(0x0D); send_1_char(0x0A); } } /*send carriage return*/ /*send line feed*/ /*next char*/ /*echo*/ /*initialize serial port*/ /*Start of loop*/ /set received ¯ag*/ /*if a character received*/ /*send out the character*/ /*wait until transmitted*/ Figure 6.9. Program not using the built-in C functions RS232 Serial Communication Projects 161 PROJECT 24 ± A Simple Calculator Program Using the RS232 Port Function This is a simple calculator project based upon the 89C51 type microcontroller. The microcontroller is connected to an RS232 serial terminal. The user can perform simple addition, subtraction, multiplication, and division of numbers using the microcontroller. Circuit Diagram This project is based upon the 89C51 microcontroller. This is a 40-pin device which is software compatible with the 89C2051 microcontroller. The 89C51 contains a 4 Kbyte ¯ash program memory, 128 bytes of RAM, 32 programmable input/output lines, and six interrupt sources. The circuit diagram of this project is shown in Fig. 6.10. A 12 MHz crystal and two capacitors are connected to pins 18 and 19 of the microcontroller. Reset input is connected to a capacitor and a resistor. Transmit output (TXD) and receive input (RXD) of the device are connected to a MAX232 type RS232 converter IC. EA is the external program enable pin and this pin should be connected to ‡5 V for internal program executions. Program Description The program operates as a simple calculator. When power is applied to the microcontroller, a menu is displayed on the user's terminal and the user is prompted to enter two numbers and the operation to be performed. A typical dialogue is given below (note that the characters typed by the user are underlined for clarity): A SIMPLE MICROCONTROLLER-BASED CALCULATOR ========================================= Enter 2 integer numbers and the operation to be performed. Valid operations are: ‡ À à ADD SUBTRACT MULTIPLY DIVIDE / Enter First Number: 5 Enter Second Number: 3 Enter Operation: ‡ Result ˆ 8 A SIMPLE . . . Figure 6.10. Circuit diagram of Project 24 RS232 Serial Communication Projects 163 The following PDL describes the operation of the program: START Initialize serial port Display heading Get a number 1 Get number 2 WHILE Operation is not valid Get Operation to be performed WEND IF Operation ˆ `‡' ADD the numbers ELSE IF Operation ˆ `À' SUBTRACT the numbers ELSE IF Operation ˆ `*' MULTIPLY the numbers ELSE IF Operation ˆ `/' DIVIDE the numbers ENDIF Display the result END Program Listing The program listing is given in Fig. 6.11. The serial port is initialized by the function serial_init. The program then prints a heading and a menu using the built-in function printf. The user is prompted to enter the numbers and the operation to be performed. The ®rst number is stored in variable num1 using the built-in function scanf. The second number is stored in variable num2. The operation to be performed is stored in variable oper. A switch statement is then used to select the required operation. The result of the calculation is stored in variable result and this is then displayed using a printf function. The program repeats forever unless stopped by the user. Components Required The following components will be required for this project: 89C51 microcontroller MAX232 IC 12 MHz crystal C1 33 mF capacitors (2 o€) C2 10 mF capacitor C3 22 mF capacitors (4 o€) R1 8.2K resistor (0.125 W) 9 way or 25 way RS232 connector 164 Microcontroller Projects in C for the 8051 /**************************************************************************************************** PROJECT: PROJECT 24 FILE: DATE: PROCESSOR: PROJ24.C August 1999 AT892051 This is a simple calculator project based upon the 89C51 type 40-pin microcontroller. The project enables the user to perform integer addition, subtraction, multiplication, and division. This program occupies just over 2720 bytes of memory. ****************************************************************************************************/ #include #include /* Function to initialize the RS232 serial port */ void serial_init() { SCON=0x50; TMOD=0x20; TH1=0xF3; TR1=1; TI=1; } /* Start of main program */ main() { int num1,num2,result; char c,oper; serial_init(); for(;;) { printf(`\n\nA SIMPLE MICROCONTROLLER BASED CALCULATOR\n'); printf(`==============================================='); printf(`Enter 2 integer numbers and the operation\n'); printf(`to be performed. Valid operations are:\n'); printf(`‡ ADD\n'); printf(`À SUBTRACT\n'); printf(`* MULTIPLY\n'); printf(/ DIVIDE\n\n'); printf(`Enter First Number:'); scanf(`%d',&num1); c=gethar(); printf(`Enter Second Number:'); /*initialize serial port*/ /*Start of loop*/ /* setup for 8-bit data */ /* setup timer 1 for auto-reload */ /* setup for 2400 baud */ /* turn on timer 1 */ /* indicate ready to transmit */ RS232 Serial Communication Projects 165 scanf(`%d,&num2'); c=getchar(); oper=` '; while(oper !ˆ `‡' && oper !ˆ `À' && oper !ˆ `*' && oper !ˆ `/') { printf(`Enter Operation:'); oper=getchar(); printf(`\n'); } switch (oper) { case `‡': result=num1+num2; break; case `À': result=num1-num2; break; case `*': resut=num1*num2; break; case `/': result=num1/num2; break; } printf(`Result = %d\n',result); } } Figure 6.11. Program listing of Project 24 This Page Intentionally Left Blank . Appendix ASCII CODE ASCII codes of the ®rst 128 characters are standard and the same code is used between di€erent equipment manufacturers. ASCII codes of characters between 128 and 255 are also known as the extended ASCII characters and these characters and their codes may di€er between di€erent computer manufacturers. Below is a list of the most commonly used ASCII characters and their codes both in hexadecimal and in binary. Character NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI DLE XON DC2 XOFF DC4 NAK SYN ETB CAN Hex 00 0l 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 Binary 00000000 00000001 00000010 00000110 00000100 00000101 00000110 00000111 00001000 00001001 00001010 00001011 00001100 00001101 00001110 00001111 00010000 00010001 00010010 00010110 00010100 00010101 00010110 00010111 00011000 Character EM SUB ESC FS GS RS US SP ! " # $ % & ' ( ) * + , . / 0 1 Hex 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 Binary 00011001 00011010 00011011 00011100 00011101 00011110 00011111 00100000 00100001 00100010 00100011 00100100 00100101 00100110 00100111 00101000 00101001 00101010 00101011 00101100 00101101 00101110 00101111 00110000 00110001 168 Microcontroller Projects in C for the 8051 Character 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` Hex 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 60 Binary 00110010 00110011 00110100 00110101 00110110 00110111 00111000 00111001 00111010 00111011 00111100 00111101 00111110 00111111 01000000 01000001 01000010 01000011 01000100 01000101 01000110 01000111 01001000 01001001 01001010 01001011 01001100 01001101 01001110 01001111 01010000 01010001 01010010 01010011 01010100 01010101 01010110 01010111 01011000 01011001 01011010 01011011 01011100 01011101 01011110 01011111 01100000 Character a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ Hex 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F Binary 01100001 01100010 01100011 01100100 01100101 01100110 01100111 01101000 01101001 01101010 01101011 01101100 01101101 01101110 01101111 01110000 01110001 01110010 01110011 01110100 01110101 01110110 01110111 01111000 01111001 01111010 01111011 01111100 01111101 01111110 01111111 10000000 10000001 10000010 10000011 10000100 10000101 10000110 10000111 10001000 10001001 10001010 10001011 10001100 10001101 10001110 10001111 ' f " ÁÁÁ { { ^ % Æ S < ê Glossary 169 Character Hex 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 BA BB BC BD Binary 10010000 10010001 10010010 10010011 10010100 10010101 10010110 10010111 10011060 10011001 10011010 10011011 10011100 10011101 10011110 10011111 10100000 10100001 10100010 10100011 10100100 10100101 10100110 10100111 10101000 10101001 10101010 10101011 10101100 10101101 10101110 10101111 10110000 10110001 10110010 10110011 10110100 10110101 10110110 10110111 10111000 10111001 10111010 10111011 10111100 10111101 Character 3 4 Hex BE BF C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF DO Dl D2 D3 D4 D5 D6 D7 DB D9 DA DB DC DD DE DF E0 El E2 E3 E4 E5 E6 E7 E8 E9 EA EB Binary 10111110 10111111 11000000 11000001 11000010 11000011 11000100 11000101 11000110 11000111 11001000 11001001 11001010 11001011 11001100 11001101 11001110 11001111 11010000 11010001 11010010 11010011 11010100 11010101 11010110 11010111 11011000 11011001 11011010 11011011 11011100 11011101 11011110 11011111 11100000 11100001 11100010 11100011 11100100 11100101 11100110 11100111 11101000 11101001 11101010 11101011 Á  ÁÁ HH E ± Ð ~ TM Æ S > ú È Y ¡ ¢ £ ¨ ¥ | § È # a « D ± 1 Ð Ê Æ 2 3 H m } Á ° 1 Ê » 1 4 1 2 ¿ Á A  A à A Ä A È A Ê A á C Ë Á E  E à E È E ÁI I Ià IÈ D Ä N Á O  O à O Ä O È O  é Á U  U à U È U  Y “ û Á a  a a à a Ä a È Ê a ñ c Ë Á e  e e à e È 170 Microcontroller Projects in C for the 8051 Character õÁ õ õà õÈ ” n Ä Á o  o o à o Ä Hex EC ED EE EF F0 Fl F2 F3 F4 F5 Binary 11101100 11101101 11101110 11101111 11110000 11110001 11110010 11110011 11110100 11110101 Character o È Ä é Hex F6 F7 F8 F9 FA FB FC FD FE FF Binary 11110110 11110111 11111000 11111001 11111010 11111011 11111100 11111101 11111110 11111111 u Á u  u à u È y  “ y È Glossary ADC Analogue-to-digital converter. A device that converts analogue signals to a digital form for use by a computer. Algorithm A ®xed step-by-step procedure for ®nding a solution to a problem. ANSI American National Standards Institute. Architecture The arrangement of functional blocks in a computer system. ASCII American Standard Code for Information Interchange. A widely used code in which alphanumeric characters and certain other special characters are represented by unique 7-bit binary numbers. For example, the ASCII code of the letter `A' is 65. Assembler A software that translates symbolically represented instructions into their binary equivalents. Assembly language A source language that is made up of the symbolic machine language statements. Assembly language is very e�cient since there is a one-to-one correspondence with the instruction formats and data formats of the computer. BASIC Beginners All-purpose Symbolic Instruction Code. A high-level programming language commonly used in personal computers. BASIC is usually an interpreted language. Baud The unit of data transmission speed. Baud is often equated to the number of serial bits transferred per second. Baud rate Measurement of data ¯ow in a serial communication system. Baud rate is typically equal to bits per second. Some typical baud rates are 9600, 4800, 2400 and so on. BCD Binary Coded Decimal. A code in which each decimal digit is binary coded into 4-bit words. By representing binary numbers in this form, it is readily possible to display and print numbers. Bi-directional port direction. Binary Bit Byte An interface port that can be used to transfer data in either The representation of numbers in a base two system. A group of 8 binary digits. A single binary digit. 172 Microcontroller Projects in C for the 8051 Chip A small rectangle of silicon on which an integrated circuit is fabricated. Clock A circuit generating regular timing signals for a digital logic system. In microcomputer systems clocks are usually generated by using crystal devices. A typical clock frequency is 12 MHz. CMOS Complementary Metal Oxide Semiconductor. A family of integrated circuits that o€ers extremely high packing density and low power. Compiler code. A program designed to translate high-level languages into machine Counter A register or a memory location used to record numbers of events as they occur. CRT Cathode Ray Tube. A display screen. Cycle time The time required to access a memory location or to carry out an operation in a computer system. DAC Digital-to-analogue converter. A device that converts digital signals into analogue form. Decimal system Base 10 numbering system. Development system Equipment used to develop microprocessor- and microcomputer-based software and hardware projects. Dot matrix Method of printing or displaying characters in which each character is formed by a rectangular array of dots to give the required shape. EAROM Electrically Alterable Read Only Memory. In this type of memory part or all of the data can be erased and rewritten by applying electrical signals. Edge triggered Circuit action initiated by the change of a signal. An edge could be the change of a signal from 0 to 1 or from 1 to 0. Emulator Software or hardware system that duplicates the actions of a microprocessor or a microcomputer system. EPROM Erasable Programmable Read Only Memory. This type of memory can be erased by exposure to ultraviolet light and then reprogrammed using a programmer. Execute File To perform a speci®ed operational sequence in a program. Graphical representation of the operation of a program. Logical collection of data. Flow chart Gate A logic circuit having one or more inputs and a single output. For example, NAND gate. Half duplex A two-way communication system that permits communication in one direction at a time. Hardware The physical parts or electronic circuitry of a computer system. Base 16 numbering system. In hexadecimal notation, numbers Hexadecimal Glossary 173 are represented by the digits 0±9 and the characters A±F. For example, decimal number 165 is represented as A5. High-level language Programming language in which each instruction or statement corresponds to several machine code instructions. Some high-level languages are BASIC, FORTRAN, C, PASCAL and so on. Input device An external device connected to the input port of a computer. For example, a keyboard is an input device. Input port Part of a computer that allows external signals to be passed into it. Microcomputer input ports are usually 8 bits wide. I/O Short for Input Output. Input/Output The hardware within the computer that connects the computer to external peripherals and devices. Instruction cycle executing it. The process of fetching an instruction from memory and Instruction set The complete set of instructions of a microprocessor or a microcomputer. Interface To interconnect a computer to external devices and circuits. Interrupt An external or internal event that suspends the normal program ¯ow within a computer and causes entry into a special interrupt program (also called the interrupt service routine). For example, an external interrupt could be generated when a button is pressed. An internal interrupt could be generated when a timer reaches a certain value. Interrupt vector Reserved memory locations where a program jumps when an interrupt is detected. ISR Interrupt Service Routine. A program that is entered when an external or an internal interrupt occurrs. Interrupt service routines are usually highpriority routines. K Multiplier for 1024. For example, 1 Kbyte is 1024 bytes. Language A prescribed set of characters and symbols which is used to convey a program to a computer. LCD Liquid Crystal Display. A low-powered display that operates on the principle of re¯ecting incident light. An LCD does not itself emit light. There are many varieties of LCDs. For example, numeric, alphanumeric, or graphical. LED Light Emitting Diode. A semiconductor device that emits a light when a current is passed in the forward direction. There are many colours of LEDs. For example, red, yellow, green, and white. Level triggered Circuit action initiated by the presence of a signal. Logic levels Voltage levels representing the two logical states (0 and 1) of a digital signal. Logic HIGH is also called state 1 and logic LOW is called state 0. 174 Microcontroller Projects in C for the 8051 LSD Least Signi®cant Digit. The right-most digit. For example, the LSD of number 123 is 3. Machine code Lowest level in which programs are written. Machine code is usually written in hexadecimal. Microcomputer General-purpose computer using a microprocessor as the CPU. A microcomputer consists of a microprocessor, memory, and input/ output. Microprocessor A single large-scale integrated circuit which performs the functions of a CPU. Mnemonic A programming shorthand using letters, numbers, and symbols adopted by each manufacturer to represent the instruction set of a microprocessor. MSD Most Signi®cant Digit. The left-most digit of a number. For example, the MSD of number 123 is 1. Nibble A group of 4 binary bits. NMOS Negative channel Metal Oxide Semiconductor. A device based on an n-channel ®eld-e€ect transistor cell. Non-volatile memory A semiconductor memory type that holds data even if power has been disconnected. Octal Representation of numbers in base 8. Op-code Operation Code. That part of an instruction which speci®es the function to be performed. Output device An external device connected to the output port of a computer. For example, a printer is an output device. Output port Part of a computer that allows electrical signals to pass outside it. Microcomputer output ports are usually 8 bits wide. Parity A binary digit added to the end of an array of bits to make the sum of all ones either odd or even. Parity is a method of checking the accuracy of transmitted or received binary data. PDL Program Description Language. Representation of the control and data ¯ow in a program using simple English-like sentences. PEROM Flash Programmable and Erasable Memory. This type of memory can be erased and reprogrammed using electrical signals only, i.e. there is no need to use an ultraviolet light source to erase the memory. Port An electrical logic circuit that is a signal input or output access point of a computer. Programmed I/O software control. PROM The control of data ¯ow in and out of a computer under Programmable Read Only Memory. A type of semiconductor Glossary 175 memory which can be programmed by the user using a special piece of equipment called a PROM programmer (or PROM blower). Pull-up resistor A resistor connected to the output of an open collector (or open drain) transistor of a gate in order to load the output. RAM Random Access Memory, also called read/write memory. Data in RAM is said to be volatile and it is present only as long as the chips have power supplied to them. When the power is cut o€, all information disappears. Register A storage element in a computer. A register is usually 8 bits wide in most microprocessors and microcomputers. ROM Read Only Memory. A type of semiconductor memory that is read only. RS232 An internationally recognized speci®cation for serial data transfer between two devices. Serial Information transfer on a single wire where each bit is transferred sequentially with a time delay in between. Software Program. Start bit The ®rst bit sent in a serial communication. There is only one start bit in a frame of serial communication. Stop bit The last bit sent in a serial communication. There can be one or two stop bits per frame of a serial communication. Syntax The rules governing the structure of a programming language. Transducer A device that converts a measurable quantity into an electronic signal. For example, a temperature transducer gives out an electrical signal which may be proportional to the temperature. TTL Transistor Transistor Logic. A kind of bipolar digital circuit. UART Universal Asynchronous Receiver Transmitter. This is a semiconductor chip that converts parallel data into serial form and serial data into parallel form. A UART is used in RS232 type serial communication. USART Synchronous version of UART. UV Ultraviolet light. Used to erase EPROM memories. VDU Visual Display Unit. Word A group of 16 binary digits. This Page Intentionally Left Blank . Index ADC0804, 132,137,138 Analogue to digital converter, 132 Architecture of AT89C2051, 4 ASCII, 147,167 BASIC, 16 Baud rate, 147 Bit, 16 Binary counter, 29 Buzzer, 85,86 Byte, 4 Calculator program, 161 C programming language, 13,15 C51, 15, 16 Counter, 10, 50 Compiler, 13, 15 CPU, 2, 12 CTS, 149 CU, 2 Data type, 16 Data memory, 2 Data width, 147 Digital thermometer, 119 Do-enddo, 24 DS1620, 109 DSR, 149 DTR, 149 Electronic siren, 95 End, 22 Electronic organ, 101 Enum, 17 EPROM, 1,3, 4 External interrupt, 10,12 Event counter, 75 Float, 18 Hexadecimal display, 46 High current buzzer, 87 IE0, 10 IE1, 10 If-then-else, 24 Interrupt, 11, 20 Interrupt number, 12, 20 Interrupt service routine, 20 Interrupt source, 12 INT0, 6, 78, 79, 80, 83 INT1, 7 ISR, 20 IT0, 10 IT1, 10 LED, 29, 57 LED dice, 38 LM35DZ, 132, 140 LSD, 50, 51 MAX232, 150, 152 Memory model, 19 Minimum con®guration, 12 MOSFET, 89, 90, 92, 93, 94, 101, 131 MSD, 50, 51 Parity, 147 PASCAL, 15 PDL, 22, 29 PEROM, 2, 3, 4 Piezo sounder, 85 Pin con®guration, 4 Program memory, 2 PSEN, 10 178 Index RAM, 1, 3, 4 Repeat-until, 25 ROM, 1 RS232, 147, 148, 149, 150, 151, 155 RS232 connector, 148 RS232 signal level, 149 RST, 5 RTD, 107 RTS, 149 RXD, 150 Sbit, 17, 18 Serial port interrupt, 12 Sequencing, 24 Seven segment display, 57 Sfr, 17, 19 Sfr16, 17, 19 Signed char, 16 Signed int, 17 Signed long, 17 Signed short, 17 Sounder, 85 Start, 22 Start-end, 22 Stop bit, 147 TCON, 10 Temperature sensor, 107 TF0, 10 TF1, 10 Thermistor, 107 Thermocouple, 107 THIGH, 109, 111, 125, 131 TIL311, 53 Timer, 10 Timer interrupt, 12, 90 TLOW, 109 TMOD, 10 Transducer, 85 TR0, 10 TR1, 10 TSM5034, 63, 64, 69, 75, 83 TXD, 150, 152 Unsigned Unsigned Unsigned Unsigned char, 16 int, 18 long, 17,18 short, 17,18 VN66AFD, 89 WR, 8 XTAL, 6




Microprocessor Systems: CPU on a single chip is called microprocessor. A microprocessor is a Very Large Scale Integrated (VLSI) logic IC whose logical function is controlled be an instruction code. This instruction code is a specific combination of logic bits needed for a microprocessor to execute its logic operations. These codes may include instructions to perform logical, arithmetic or input/output operations. A microprocessor system is one type of computer system. All computer systems have three basic functional blocks: a processing unit, memory, and input/output. In practice these components are connected together using either address bus, data bus or control lines. ASSEMBLY LANGUAGE CODE: CNT EQU 03FD6H APORT EQU 03FD0H BPORT EQU 03FD2H CODE SEGMENT ASSUME CS: CODE ORG 0 START: MOV AL, 90H MOV DX, CNT OUT DX, AL J1: MOV DX, APORT IN AL, DX MOV DX, BPORT OUT DX, AL JMP J1 CODE ENDS END START  ASSEMBLER DIRECTIVES USED:  What is assembler directive;  These are just instructions for assemble having no code.  EQU; assigns value to a variable  Segment; it is used when we are going to start a specific segment  Assume; it tells the assembler to start the ‘cs ’ from the keyword ‘code (in this specific code)’  Org; org directive allows to set the location counter to a desired value at any point in the Program. The statement ORG 2000H tells the assembler to set the location counter to 2000H.  ENDS/END; ‘end’ is used to terminate the execution and ‘ends’ is used to to end the any segment LABEL: A label is a symbol or group of symbols used to represent an address, which is not known at the time the statement, is written. PROGRAM ANALYZATON: • CNT EQU 03FD6H: It assigns ‘03FD6H’ to variable CNT. CNT=03FD6H • APORT EQU 03FD0H: APORT=03FD0H • BPORT EQU 03FD2H: BPORT=03FD2H • START: MOV AL, 90H: It loads no.90H in AL register. AL=90H • MOV DX, CNT: It copies the contents of CNT to DX register. DX=03FD6H • OUT DX, AL: It sends out the data present in AL on the address present in DX. • J1: MOV DX, APORT: J1 is label This instruction loads the contents of APORT in DX register. DX=03FD0H • IN AL, DX: This instruction inputs the data from port present at offset address [03FD0H] to AL register. • MOV DX, BPORT: This instruction copies the content present at offset of BPORT to DX register. • OUT DX, AL: This instruction sends the data present in AL to the output port present at the offset address of DX. • JMP JI: JMP is unconditional jump it continuously jumps to the label ‘J1’ Without checking any condition. • END: END OF PROGRAM EXECUTION. CONSTRUCTING MACHINE LANGUAGE CODES FOR 8086 INSTRUCTONS: Whenever we write a assembly language program these instructions are first converted to machine language code so that microprocessor can read it and this is done by assembler software. FLOW CHART: START MOV AL,90H MOV DX,CNT JI:Out Dx,APo rt MOV DX,APort IN Al.Dx MOV Dx,BP OUT DX,Al JMP JI STOP BLOCK DIAGRAM OF PROJECT: SCHEMATIC DIAGRAM: VCC 10k 3 4 7 8 13 14 17 18 16 15 14 13 12 11 10 9 19 31 18 33 17 22 21 23 8 7 6 5 4 3 2 39 D0 D1 D2 D3 D4 D5 D6 D7 Q0 Q1 Q2 Q3 Q4 Q5 Q6 Q7 2 5 6 9 12 15 16 19 A0-A2 1 2 3 4 A14-A19 2 3 1 A8-A16 3 4 7 8 13 14 17 18 D0 D1 D2 D3 D4 D5 D6 D7 Q0 Q1 Q2 Q3 Q4 Q5 Q6 Q7 2 5 6 9 12 15 16 19 OR2 6 34 33 32 31 30 29 28 27 D0 D1 D2 D3 D4 D5 D6 D7 PA0 PA1 PA2 PA3 PA4 PA5 PA6 PA7 4 3 2 1 40 39 38 37 18 19 20 21 22 23 24 25 14 15 16 17 13 12 11 10 2 4 A1 6 A2 8 A3 A4 1 G 74LS 240 330ohm 18 Y 1 16 Y 2 14 Y 3 12 Y4 PB0 PB1 PB2 35 5 RESET PB3 PB4 36 R D PB5 6 WR CS PB6 PB7 PC0 PC1 PC2 PC3 PC4 PC5 PC6 PC7 8255 2 3 2 1 A8-A13 10 9 8 7 6 5 4 3 25 24 21 23 2 2 3 6 1 74LS 14 24 13 A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 7 4 L S 1 41 1 D 0 12 D 1 13 D 2 15 D 3 16 D 4 17 D 5 18 D 6 19 D7 11 13 A1 15 A2 17 A3 A4 19 G 74LS240 9 8 A0 A1 1 2A 3B C 6 4 G1 0 5 G 2A G 2B 74LS138 A8-A15 Y0 Y1 Y2 Y3 Y4 Y5 Y6 Y7 15 14 13 12 11 10 9 7 1 1 2 3 4 VCC 9 Y1 7 Y2 5 Y3 3 Y4 VCC 8 7 6 5 8 7 6 5 AD0 AD1 AD2 AD3 AD4 AD5 AD6 AD7 C LK H O LD IN T R MN NMI READY RST TEST AD8 AD9 AD 10 AD 11 AD 12 AD 13 AD 14 AD 15 11 1 LE OE 74LS 373 38 A 1 6 /S 3 3 7 A 1 7 /S 4 3 6 A 1 8 /S 5 3 5 A 1 9 /S 6 A LE B H E /S 7 DEN D T /R H LD A IN TA M /IO RD WR 25 34 26 27 30 24 28 32 29 11 1 LE OE 74LS373 A16-A17 8 0 8 6 M IN 22 27 O E 20 W E 26 C S1 CS2 6264 510 C RY S TA L O S CI LA T OR C P U- C LK 510 100 CL K 8 C LK 2 PC LK 5 R EAD Y 10 RESET 123 S Y S- C LK P CL K U 16 3 7 AEN1 AEN2 1 4 .7 4 5 6 M H Z 14 EFI R AM - VC C 12 17 O S C 16 X1 X2 C R Y STAL C1 15 1 13 4 6 11 D 10 ASY NC CSYNC F /C RDY1 RDY2 RES 8284 2K R A M- A R A M- B 2K1 470K V CC 511 D 3 -1 N 4 1 4 8 1 M IC R O F 100 RA M -V C C D4 C 6 -4 7 3 .6 V B A TTE R Y VCC 470K 74LS14 SW2 NMI R3 100 1 M IC R O F 2 1 2 TO NMI PINOF MP M/IO' 3 2 3 1 IOR' RD' 4 2 3 1 MEMR' 2 WR' 3 1 1OW' 2 3 1 MEMW' RECTIFIER BRIDGE STEPDOWN TRANSFORMER D1 VOLTAGE REGULATOR T1 1 1 220V 4 8 TR A N S F O R M E R 3 B R ID G E 5 2 + 4 FILTERS +5V VCC VCC 470K SW 1 100 1uF 9 IC 6 D 8 7 4 L S 1 4 /S O VCC NMI IN 4 1 4 8 100 R A M -V C C 47 IN 4 1 4 8 3 .6 V BATTER Y ADDRESS DECODING: PORT A: 8255 I/P ENB 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 10 DEC IP HEX CODE: 03FD0H PORT B: 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 10 0 1 0 0 0 0 HEX CODE: 03FD2H PORT C: 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 10 1 0 0 HEX CODE: 03FD4H CONTROL REGISTER: 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 10 1 1 0 HEX CODE:03FD6H Intel 8086 microprocessor architecture: The Intel 8086 is16 bit microprocessor that is use as CPU in microcomputer. Its chareristics are (1): The 8086 has16-bit data bus. So it can read data from or write data to memory and ports either 16-bit or 8-bit at a time (2):The 8086 has 20-bit address bus. So it can address any one of (2^20) memory location. (3):It has17 control/timing,3 power = 56. But 8086 has just 40 pins. 8086 Pins Discription: AD0-AD15 (out): multiplexed address/data bus signals NMI & INTR (in): interrupt request inputs MN/MX* (in): Minimum/maximum operating mode BHE* (out): Bus High Enable - determines if byte or word memory access (with A0) CLK(in):Pin number 19 is System clock INTA* (out): Interrupt acknowledge RD* (out): Read bus cycle in progress WR* (out): Write bus cycle in progress M/IO* (out): memory or I/O transfer occuring over bus DT/R* (out): Data transmit/receive (direction of data transfer through external buffers) A16/S3-A19/S6 (out): Address/status S4-S3: 00-ES, 01-SS, 10-CS, 11-DS S5: INTE flag, S6=0 DEN* (out): Data enable, signals that bus lines are being used to transfer data HOLD (in): Causes 8086 to relinquish bus, used in DMA HLDA (out): Hold acknowledge, signals bus lines have been relinquished TEST* (in): If high, 8086 enters idle mode (for use with other processors, e.g., 8087) READY (in): To generate wait states (for slow memory/I/O devices) RESET(in): Reset processor, terminate current activity, initialize registers Code segment (CS) is a 16-bit register containing address of 64 KB segment with processor instructions. The processor uses CS segment for all accesses to instructions referenced by instruction pointer (IP) register. CS register cannot be changed directly. The CS register is automatically updated during far jump, far call and far return instructions. Stack segment (SS) is a 16-bit register containing address of 64KB segment with program stack. By default, the processor assumes that all data referenced by the stack pointer (SP) and base pointer (BP) registers is located in the stack segment. SS register can be changed directly using POP instruction. Data segment (DS) is a 16-bit register containing address of 64KB segment with program data. By default, the processor assumes that all data referenced by general registers (AX, BX, CX, DX) and index register (SI, DI) is located in the data segment. DS register can be changed directly using POP and LDS instructions. Extra segment (ES) is a 16-bit register containing address of 64KB segment, usually with program data. By default, the processor assumes that the DI register references the ES segment in string manipulation instructions. ES register can be changed directly using POP and LES instructions. It is possible to change default segments used by general and index registers by prefixing instructions with a CS, SS, DS or ES prefix. All general registers of the 8086 microprocessor can be used for arithmetic and logic operations. The general registers are: Accumulator register consists of 2 8-bit registers AL and AH, which can be combined together and used as a 16-bit register AX. AL in this case contains the low-order byte of the word, and AH contains the high-order byte. Accumulator can be used for I/O operations and string manipulation. Flags is a 16-bit register containing 9 1-bit flags: Carry Flag (CF) - set if there was a carry from or borrow to the most significant bit during last result calculation. Auxiliary carry Flag (AF) - set if there was a carry from or borrow to bits 0-3 in the AL register Direction Flag (DF) - if set then string manipulation instructions will auto-decrement index registers. If cleared then the index registers will be auto-incremented. Interrupt-enable Flag (IF) - setting this bit enables maskable interrupts. Single-step Flag (TF) - if set then single-step interrupt will occur after the next instruction. Sign Flag (SF) - set if the most significant bit of the result is set. Zero Flag (ZF) - set if the result is zero. Parity Flag (PF) - set if parity (the number of "1" bits) in the low-order byte of the result is even. Overflow Flag (OF) set if the result is too large positive number, or is too small negative number to fit into destination operand. 8255 Programmable Peripheral Interface (PPI): THE 8255 (PPI :) The 8086 microprocessor has no port to connect input and output devices With it so in order to interface the input and output devices with 8086 microprocessor we use another IC numbered 8255 (ppi). 8255 SPECIFICATIONS;  40 Pins DIP…(DUAL INLINE PACKAGE)  3 8bits ports o PA…port A o PB…port B o PC…port C  Chip select… (CS...active low)  02 input pins (from mp)  Read and write pins  8 data pins (D0-D7)  control register GROUPS OF 8255: The ports of 8255(ppi) are divided in to two (2) groups i.e. group A&B 1. G.A=PA+PC(low) 2. G.B=PB+PC(high) CONTROL REGISTER: Control register contains the control word and on the basis of this control word the ports are configured as input or output port. mod Mod=1 i/o mod !……… ... group A………………!............group B…………..! mod mod PA PCH mod PB PCL CONTENT OF CONTROL REGISTER (IN THIS VERY CASE): 8 bit word: 1 0 PA= input port PB= output port PC= output port 0 1 0 0 0 0 Advantage of this project: Now, I am able to interface any I/O devices with microprocessor by using programmable peripheral. This project helped in a lot in understanding of the interfacing, I hope this project will help me a lot in the future, specially in the final project of Engineering.



No comments: