You are on page 1of 638
Embedded Systems Building Blocks, Second Edition Complete and Ready-to-Use Modules in C Jean J. Labrosse R&D Books Lawrence, KS 66046 R&D Books 1601 West 23rd Street, Suite 200 Lawrence, Kansas 66046 USA Designations used by companies to distinguish their products are often claimed as trademarks. In all instances where R&D Books is aware of a trademark claim, the product name appears in initial capital letters, in all capital leters, or in accordsce with the vendor's capitalization preference, Readers should contact the appropriate companies for more complete information on trademarks and trademark regis- trations. All trademarks and rogistered trademarks in this book are the property of their respective hold- Copyright © 2000 by Miller Freeman, Inc., except where noted otherwise. Published by R&D Books, ‘an imprint of Miller Freeman, Inc. Al rights seserved. Printed in the United States of America. No part of this publication may be reproduced or distributed in any form or by any means, or stored in a data ‘base or retrieval system, without the prior writen permission of the publisher; with the exception that the program listings may be entered, stored, ard executed in a computer system, but they may not be reproduced for publication, ‘The programs in this book are presented for insuctional value, The programs have been carefully tested, but they are not guaranteed for any particuler purpose. The publisher does not offer any warran- ties and does not guarantee the accuracy, adequacy, or completeness of any information herein and is not responsible for any errors or omissions. The publisher assumes no liablilty for damages resulting, from the use of the information in this book or for any infringement of the intellectual property rights of third parties which would result from the use of this information, Cover art created by: Robert Ward. Distributed in the U.S. and Canada by: Publishers Group West 1700 Fourth Street Berkeley, CA 94710 1-800-788-3123 ISBN 0-87930-604-1 Uf Miller Freeman A United News & Media publication To my loving and caring wife and best friend, Manon, and to our two lovely children, James and Sabrina. Table of Contents Preface .........2.655- seteeetetsveeeeeee What's new in the Second Edition? .... Goals Intended Audience . Portability... : ‘What Will You Need to Use this Book?... Acknowledgments... introduction. . Figure, Listing, and Table Conventions. Source Code Conventions Chapter Contents.. Web Site.. Bibliography Chapter 1 Sample Code .. 1.00 Installing Embedded Systems Building Blocks. 1.01 How Each Chapter Is Organized... 1.02 INCLUDES. H, 1.03 Campiter independent Data Types 1.04 CrG.C and CFG.H. 1.05 Global Variables 1.06 0S_ENTER CRITICAL () and OS_EKIT_CRITICAL () . 1.07 ESBB Sample Code... 1.08 Bibtiograpiy .. vi — Embedded Systems Building Blocks, Second Edition Chapter 2 Real-Time Systems Concepts. 2.00 Foreground/Background Systems. 2.01 Critical Section of Code.. 2.02 ReSOUFCE sernnnnn 2.08 Shared Resource. 2.04 Multitasking 63 2.05 Task, 63 2.06 Context Switch (or Task Switch) . 2.07 Kernel 2.08 Scheduler.. 2.09 Non-Preemptive Kernel 2.10 Preemptive Kernel 2.11 Reentraney 2.12 Round-Robin Scheduling. 2.13 Task Priority... 2.14 Static Priorities. 2.15 Dynamic Priorities 2.16 Priority Inversio 2.17 Assigning Task Priorities... 2.18 Mutual Exclusion... 2.19 Deadlock (or Deadly Embrace) .. 2.20 Synchronization 2.21 Bvent Flags. 2.22 Intertask Communication. 2.23 Message Mailboxes. 2.24 Message Queues. 2.25 Interrupts 2.26 Interrupt Latency... 2.27 Intercupt Response 2.28 Interrupt Recovery ... . 2.29 Interrupt Latency, Response, and Recovery 2.30 ISR Processing Time... 2.31 Nonmaskable Interrupts (NMIs) 232. Clock Tick... 2.33 Memory Requirements. 2.34 Advantages and Disadvantages of Real-Time Kernels 2.35 Real-Time Systems Summary... 2.36 Bibliography ... Chapter 3 Chapter 4 Chapter 5 Table of Contents — vit 101 101 Keyboards .. 3.00 Keyboard Basics 3.01 Matrix Keyboard Scanning Algorithm 3.02 Matrix Keyboard Module 3.03 Internals... 3.04 Interface Functions, ReyFlush () . KeyGetkey() KeyGetKeyDownTime ().. KeyHit().. KeyInit {). 3.05 Configuration ... 3.06 How to Use the Matrix Keyboard Module. 3.07 Bibliography . Multiplexed LED Displays. 4,00 LED Displays. 4.01 Multiplexed LED Display Module 4,02 Internals.. 4,03 Interface Function: DispClrSer () DispInit {} DispStatClr() DispStatSet () Dispstr () 4.04 Configuration 4.05 How to Use the Multiplexed LED Display Module: 4.06 Bibliography .. Character LCD Modules 5.00 Liquid Crystal Displays 5.01 Character LCD Modules. 5.02 Character LCD Module, Internals, 5.03 Interface Functions. DispChar () DispClrLine() DispClrScr ().. DispDefChar () DispHorBar ().. DispHorBarInit () Chapter 6 Chapter 7 Embedded Systems Building Blocks, Second Edition DispInit () 176 Dispstr ( 5.04 LCD Module Display, Configuration 178 5.05 LCD Module Manufacturers........ 178 Time-of-Day Clock 191 6.00 Clocks/Calendars .. 191 6.01 Clock/Calendar Module 192 6.02 Internals. 192 6.03 Interface Functions. 195, - 196 198 ClkFormatDate () ClkFormatTime () ClkFormats () 199 Clket Ts () .. 200 clkinit (). 201 ClkMakeTS () 202 ClksetDate ( 203 ClksetDateTime() . ClkSetTime( 205 6.04 Clock/Calendar Module, Configuration 6.05 Bibliography .. . 229 Timer Manager. 7.00 Timer Manager Module 7.01 Timer Manager Moduler, Internals. 7.02 Timer Manager Module, Interface Function: TmeCégPnct (} 24 ‘TrChk () : 236 ‘TmrFormat () ... 237 ‘TorInit (). ‘TmrReset () .. ‘TmrSetMST () ‘TmrsetT( ‘Tmrstart() 230 233 242 ‘tmrStop |)... 243 7.08 Timer Manager Module, Configuration 244 1.04 Bibliography onsen on 244 Chapter 8 Chapter 9 Chapter 10 Table of Contents —ix Discrete I/Os..... 8.00 Discrete Inputs 8.01 Discrete Outputs... 8.02 Discrete /O Module 8.03 Discrete YO Module, Internals 8.04 Discrete /O Module, Interface Functions .. DICEgEdgeDetectFnct () .. DICEgMode() DICLr() Diet (). DIOInit (). DISetBypass () DISetBypassEn () . DOCEgBLink() DOCEgMode () DoGet () .. poset (} DOSet Bypass () DOSetBypassEn() DOSetSyncCtrMax() 8.05 Configuration.. 8.06 How to Use the Discrete /O Module... Fixed-Point Math... 9.06 Fixed-Point Numbers. 9.01 Fixed-Point Addition and Subtraction 9.02 Fixed-Point Mult 9.04 Fixed-Point Comparison 9.05 Using Fixed-Point Arithmetic, Example #1 9.06 Using Fixed-Point Arithmetic, Example #2. 9.07 Using Fixed-Point Arithmetic, Example #3. 9.08 Conclusion... — 9.09 Bibliography Analog I/Os... 10.00 Analog Inputs.. 10.01 Reading an ADC. 10.02 Temperature Measurement Example 10.03 Analog Outputs. 10.04 Temperature Display Example X— Embedded Systems Building Blocks, Second Edition 10.05 Analog /O Module.. 10.06 Internals. 10.07 Interface Functions... AICEgCal () AICEgConv() AICfgScal ing ().. UGE () eee AtoInit() ATSetBypass) AISetBypassEn () AOC£gCal () ... AOCEgConv() aoctgscaling().. noset () AOSetBypass () AOSetBypassEn () 10.08 Analog /O Module, Configuration. 10.09 How to Use the Analog I/O Module. 10.10 Bibliography ... Chapter 11 Asynchronous Serial Communications. 11.00 Asynchronous Communications 11.01 RS-232C. 11.02 RS-485 11.03 Sending and Receiving Duta. 11.04 Serial Ports on a PC 11.05 Low-Level PC Serial 1/0 Module (Cot, 20) ConmcfgPort (). : CommexF Lush () CommRxintDis ( CommxInt En () CommPxIntDis () ConmiPxIntEn () Conmsetintvect () .. CommReLintVect () 11.06 Buffered Serial /O Module (COMMBGND).. ConeietChar () Conminit |) .. CommisEmoty () CommisFull () CommbutChar(). Table of Contents — ai 11.07 Buffered Serial VO Module (COMMRTOS) ....... 442 . CommgetChar () 445 Comminit () .. 447 CommisEmpty () CommIsFul () . CommPutChar () 448, 449. 450 11.08 Configuration 452 11.09 How to.use the COMM_PC and the COMMBGND Module... 452 11.10 How to use the COMM,_PC and the COMMRTOS Module 1 453 11.11 Bibliography 455 Chapter 12 PC Services. emer 495, 12.00 Character Based Displas 12.01 Saving and Restoring DOS's Context. 12.02 Elapsed Time Measurement. 12.03 Miscellaneous 12.04 Interface Functions. PC_Dispchar () PC_DispClrcol ( PC_DispClrRow( PC_DispClrSer() PC_DispStr(). PC_DOSReturn ().. PC_DOSSaveReturn() PC_Elapsedinit () PC_Elapsedstart () PC_Elapseastop() PC_GetDateTime() PC_Getkey () PC_SetTickRat FC_VectGet (}.. PC_VectSet ( 12.05 Bibliography Appendix A. uC/OS-II, The Real-Time Kernel 495 498, 500 500 - 501 - 502 503 504 50S 506 - 508 509 510 Su 513 514. 515 516 517 518 519 535 ostnit ()... 537 ossemCreate (). 538 OsSemPend () 539) oOsSemPost () 541 xii — Embedded Systems Building Blocks, Second Edition Appendix B Appendix C Appendix D Appendix E osstart () OsstatInit() OstaskCreate() OsTaskCreateExt () OsTimeDly () OsTimeDlyHMS Osversion() O$_ENTER_CRITICAL() and (0S_EXTT_CRITTCAL () Programming Conventions. B.00 Directory Structure .. B.O1 C Programming Styl B.02 Bibliography. Acronym, Abbreviation, and Mnemonic Dictionary... HPLISTC and TO.. D.00 HpLrsrc DOI T0..... Companion CD-ROM... E.00 Hardware/Software Requirements E.01 Installation... E02 Directory Structure. E.03 Finding Errors E.04 Licensing .. weeeee 587 Preface ‘This i the second edition of Embedded Systems Building Blocks, Complete and Ready-1o-Use Modules in. This s 9 book of software modiules that you can use to design embedded systems. The modules axe some of the most common building blocks of embedded systems: keyboard scanners, display inter- faces, timers, and YOs. Most ofthe code is written in bighly portable C. Managers will ike this ook because it can reduce the amount of time, and thus money, required for some of the more repetitive aspects of embedded systems design. Each chapter is independent ofthe others, allowing you to use only the module(s) you need. Each chapter describes what the module does, how it works and, what services it provides. This information will help you estimate the resources you'll need to implement your product. What’s new in the Second Edition? 1 made a number of changes from the fist edition, The most notable one is, of couse, the hard Cover Which makes the book more durable. The second major change is that all ofthe code and examples have been revised to use uC/OS-I, pC/OS-Il is a Real-Time Operating System dat f wrote and is fully Keyboard Display ose) BSB EE Discrete Outputs «>| KEY Discrete inputs Limits —>| Lamps Switches py Motors Statuses — >| Fans Etc. | Etc. Analog Inputs Analog Outputs [> Actuators ‘AO [> Valves [> Meters J» Ete. ‘Temperatures —»| Pressures — >| Levels —>| Ete. —+| cLK os. ‘TMR} Se, opie Ta ots, Beane Lie (Kernel) Figure 11 is a block diagram representing the key areas covered by this book. Even though the ‘building blocks shown in the figure interact mostly with hardware, T have carefully isolated hard- ‘ware-dependent code to a few easy-to-change functions or constants. This makes the cade easy to port to your own environment. Also, l avoided using assembly language except when absolutely necessary. Chapter Contents ach chapter describes one ot more of the building blocks shown in the figure, The building blocks are mostly independent of one another, so you can jump to any chapter you need. However, you should read Xx — Embedded Systems Building Blocks, Second Edition at least Chapter 1 to familiarize yourself with some of my conventions. You will also need to understand the material presented in Chapter 9 in order to understand Chapter 10 Chapter 1. tells you how to install the software provided on the CD-ROM. The chapter also tells you about some of the conventions I use and then provides you with an example on how to use some of the ‘modules presented in this book. I decided to include this information early in the book to allow you to start using the code as soon as possible. Chapter 2 introduces real-time systems concepts such as foreground/background systems, critical sections, resources, multitasking, context switching, scheduling, reentrancy, task priorities, mutual exclusion, semaphores, intertask communications, task synchronization, task coordination, interrupts, clock ticks, etc. Chapter 3. describes one of the building blocks shown in Figure I.1, keyboards. Chapter 3 describes “Keyboard basics and provides you with a general purpose module that can scan and decode any key- board matrix from a 3x3 to an 8x8 key arrangement. The keyboard module can buffer keystrokes, repeat the same key if the key is held down for a certain length of time, keep track of how long the key has ‘been pressed, and allow you to define multiple scan codes for each key. The code can be easily ‘expanded to support larger keyboards. Chapter 4 will show you how to control LED (Light Emitting Diode) displays. LED displays can consist of discrete LEDs, seven-segment modules, ot any combination of both. Chapter 4 provides you ‘with a module that can multiplex LEDs from a 3x3 to an 8x8 arrangement. The code can easily be ‘changed to accommodate larger displays. Chapter 5 provides you with a software module that will control Character LCD Modules which are based on the Hitachi HD44780 Dot Matrix LCD Controller & Driver chip. Character LCD (Liquid Crystal Display) modules are display devices that can display alphanumeric data, Chapter 6 describes a software-driven clock/calendar module that keeps track of houts, minutes, sec- ‘onds, days, months, years (including leap years) and day-of-week. The code also provides you with a 32-bit timestamp which can be used to mark the occurrence of events. Chapter 7 describes a module that manages up to 250 countdown timers. Each timer can be preset to timeout after up to 100 hours with 0.1 second resolution. You can define a function that will be executed when the timer expires (one for each timer). Chapter 8 provides a module that can read discrete inputs and contol discrete outputs (up to 250 each), For discrete inputs, the module will tell you whether the input is high, low, transitioned from low to high, high to low or both. When a transition is detected, a user-definable function can be executed (one for each input). Each discrete input can also simulate a toggle action (push-ON, push-OFF). Each discrete output can be turned ON, turned OFF, or made to blink at a user-definable rate. Chapter 9 will give you tools to improve the efficiency of mathematical calculations in embedded processors. The concepts presented in this chapter will be used in Chapter 10. Introduction —xxi Chapter 10 describes how to read and scale analog inputs and how to scale and control analog out- puts. This chapter also provides you with code that will read and scale up to 250 analog inputs and scale and update up éo 250 analog outputs. Chapter 11 discusses asynchronous serial communications and specifically provides you with code that performs buffered serial 1/0 on a PC. There are actually two versions ofthis code, One version ean bbe used by a DOS application while the other assumes the presence of a real-time kemet, Appendix A describes how to use MicroC/OS-II, The Real-Time Kernel. wC/OS-II (for short) is @ portable, ROM-able, preemptive, real-time, multitasking kernel. The internals of wC/OS-IL are fully described in my other book, MicroC/0S-II, The Real-Time Kernel, which is also available (along with a diskette containing the source code) from R&D Books (sce the ad atthe back of the book). Most ofthe code presented in Embedded Systems Building Blocks assurnes the presence of a real-time kernel. Spe- cifically, I make use of semaphores and time delays which are available on most (if not all) commer- cially-available real-time kernels, To allow you to use the code in this book, I have included a compiled version of wC/OS-II (compiled using a Borland C++ v4.51 compiler for an Intel 80x86 Large Model). Appendix B describes some of my programming conventions, Specifically, I describe my directory structures and C programming style, Appendix C_ lists the acronyms, abbreviations, and mnemonics that [used in the code presented in this book. Appendix D presents two DOS utilities that I use: TO and HPLISTC. TO is a utility that T use to quickly move between MS-DOS directories without having to type the CD (change directory) com- mand, HPLISTC is a utility to print C source code in compressed mode (i.c., 17 CPI) and allows you to specify page breaks. The printout is assumed to be to a Hewlett Packard (HP) Laserjet type printer. Appendix E describes how to install the source code provided on the companion CD-ROM included with this book and describes the licensing policy with regards to using the code in commercial applica- tions. Web Site ‘To provide better support to you, I created the uC/OS-IT web site (www -uCOS-ZE..com). You can obtain information about + news on uCIOS, wC/OS-II, and Embedded Systems Builing Blocks, + upgrades, + bug fixes, + answers to frequently asked questions (FAQS), ‘+ application notes, + books, + classes, + links to other web sites, and more. xxii — Embedded Systems Building Blocks, Second Edition Bibliography Ganssle, Jack G. The Art of Programming Embedded Systems ‘San Diego, California ‘Academic Press, Inc. ISBN 0-12-274880-8 MeConnell, Steve Code Complete, A Practical Handbook of Software Construction Redmond, Washington Microsoft Press ISBN 1-55615-484.4 Chapter 1 Sample Code ‘This chapter provides you with an example on how to use some of the embedded systems building blocks described in this book. I decided to include this chapter early in the book to allow you to start using the code as soon as possible. Before getting into the sample code, I will describe some of the con- ventions T use throughout the book. The sample code was compiled using the Borland Intemational (now called Inprise) C/C++ com- piler V4.51 and options were selected to generate code for an Intel/ AMD 80186 processor (large mem- ‘ory model) although the compiler was also instructed to generate floating-point instructions. I realize that the 80186 doesn't have hardware assisted but most PCs nowadays contain at least a 80486 proces- sor which has floating-point hardware. The code was actually run and tested on a 300 MHz Intel Pen- tium-II based PC which can be viewed as a super fast 80186 processor (at least for my purpose). Fehose a PC as my target system for a number of reasons. First and foremost, its alot easier to est code on @ PC than on any other embedded environment (j.c., evaluation board, emulator ete)) ~ there are no EPROMS to burn, no downloads to EPROM emulators, CPU emulators, etc. You simply compile, link, and run, Second, the 80186 abject code (Real Mode, Large Model) generated using the Borland C/C++ ‘compiler is compatible with all 80x86 derivative processors from intel or AMD. Embedded Systems Building Blocks assumes the presence of a real-time kemel. For your conve- rience, I included @ copy (in object form) of sCOS-II, The Real-Time Kernel (see Appendix A for details). 1.00 Installing Embedded Systems Building Blocks R&D Books fas included a companion CD-ROM to Embedded Systems Building Blocks (ESBB). The CD-ROM is in MS-DOS format and contains all the source code provided in this book. It is assumed ‘that you have a DOS, Windows 95, Windows 98, or Windows NT-based computer system running on an 80x86, Pentium, or Pentium-II processor. You will need less than about 10 Mbytes of free disk space to install ESBB and its source files on your system, Before starting the installation, make a backup copy ofthe files found on the companion CD-ROM. “To install the code provided on the CD-ROM, follow these steps: 2 Embedded Systems Building Blocks, Second Eiltion 1, Load DOS (or open a DOS box in Windows 95/98/NT) and specify the C: drive as the default drive Insert the companion CD-ROM in your CD drive 3. Enler : INSPALL [drive] Note that

You might also like