Файл: Programming Microcontrollers in C, 2-nd edit (Ted Van Sickle, 2001).pdf

ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 15.06.2025

Просмотров: 4024

Скачиваний: 1

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

Introduction to First Edition

xiii

will be programming; however, I could not do it. I needed a careful discussion of the ways peripheral components are used. Appendix C and Appendix E contain detailed descriptions of the MC68HC11 and the MC68HC16 family parts respectively. I am particularly indebted to Motorola Semiconductor Products, Inc. for the contents of Appendix E. This Appendix is a very slightly modified version of the Appendix D found in the MC68HC16Z1 users manual.

Appendix C contains a header file for the MC68HC11Ex series, and Appendix F contains several header files needed to program the MC68HC16 components.

This book has taken entirely too much time to write. As the author, it is my fault, and I have been a burden to those around me while I have labored on this task. The basis for the text comes from about three years of teaching classes on programming microcontrollers in C. This class has been taught as a three or four day course, mainly to Motorola customers. I am amazed that it is possible to learn from every class that I teach. During the time I have been writing, I have learned object oriented programming and the C++ language, and I have also taught classes on this subject. It is difficult to move from one language to another, especially languages with similar roots like C and C++, and not get them mixed up. I am comfort­ able that this book is on C without C++ spilling into the material.

I have received much help in writing this book. My dear wife, who understands nothing about computers, has read most of the book and made comments about the contents. If this text is more readable than usual, it is her contribution. Any problems that you find are my responsibility entirely.

Motorola has provided me much time and support that I appreciate. Most of the photographs found in the book are from Motorola files. My manager, Neil Krohn, has encouraged me at every phase in the preparation of this manuscript. Neil and Motorola deserve my heartfelt thanks.

What’s on the CD-ROM?

Programs

The programs on this CD-ROM will help you learn how to program small embedded control systems. The directory named Programs contains all of the programs from the book. Programs from each chapter are grouped together in directories named Chapter1, Chapter2, etc., where the number corresponds to the book chapter in which the code is found. The subdirectory Header~1, or Header Files, contains a series of directories that contain the specific header files needed to connect your compiled code to the peripherals found on the indicated chips. These header files have been used extensively, but you will probably still find an occasional bug in them. If you do find a bug, please notify me at the email address below.

There are demonstration compilers for the M6805, the M68HC11, and the M68HC16 families of chips. The Byte Craft Limited compiler is placed in directory C6805. Instructions for use of this compiler can be obtained by merely typing \c6805\c6805 with no arguments and the instruction sheet will appear.

The two Intermetrics demonstration compilers are placed in HC11DEMO and HC16DEMO respectively. When using one of these compilers, the directory name should be placed in the system path. Only one of the demo directories should be in the path at a time because the two compilers both use the same function names. Confusion will reign if both directories are in the path at the same time. In the Software directory, you will find files named HC16BOOK.TXT and HC11BOOK.TXT. These files are transcriptions of the books normally shipped with the Demo Kit packages from Intermetrics. There is no convenient means to copy the several figures found in these books into these ASCII files. Therefore, the files are complete with the exception of the figures. The text describes the contents of the figures. I am sorry for any inconvenience caused by these necessary omissions. Also, the contents of these books contain discus­ sions of how you should install the various programs contained in the Demo Kits. These compilers are already installed on the CD-ROM, but the basic programs from which they are installed are found in the directo­ ries HC16 and HC11. You can reinstall these demonstration compilers from the programs in these directories if you wish.

xv


xvi What's on the CD-ROM?

Intermetrics no longer supports the compilers found on the CD-ROM. If you wish continued support with these compilers, you should contact COSMIC Software at

Cosmic Software

400 W. Cummings Park STE6000 Woburn, MA 01801-6512

781 932 2556 x 15

Motorola Reference Manuals and Data Manuals

The CD-ROM contains full copies of several Motorola M68HC11 reference manuals and data manuals, along with similar information for the M68HC05, M68HC08, M68HC12, M68HC16, and M683XX family of chips, and the MCORE family. These reference materials have been provided with the permission of Motorola and are there for your use.

eBook

Also included on the CD-ROM is a full, searchable eBook version of the text in Adobe pdf format. In addition, there are sample chapters of other electronics engineering references available in both eBook and print versions from LLH Technology Publishing.

Good luck on your venture into C.

Ted Van Sickle

e-mail: tvansickle@a-sync.com http://www.a-sync.com/

Chapter 1

Introduction to C

Programming is a contact sport. Programming theory is interest­ ing, but you must sit at a keyboard and write code to become a programmer. The aim of this introductory section is to give you a brief glimpse of C so that you can quickly write simple programs. Later sections will revisit many of the concepts outlined here and provide a more in-depth look at what you are doing. For now, let’s start writing code.

Some Simple Programs

C is a function based language. You will see that C uses far more functions than other procedural languages. In fact, any C program it­ self is merely a function. This function has a name declared by the language. In C, parameters are passed to functions as arguments. A function consists of a name followed by parentheses enclosing argu­ ments, or perhaps an empty pair of parentheses if the function requires no arguments. If there are several arguments to be passed, the argu­ ments are separated by commas.

The mandatory program function name in C is main. Every C pro­ gram must have a function named main, and this function is the one executed when the program is run. Examine the following program:

#include <stdio.h>

int main(void)

{

printf(“Microcontrollers run the world!\n”); return 0;

}

1

2 Chapter 1 Introduction to C

This program contains all of the elements of a C program. Note first that C is a “free form” language. Spaces, carriage returns, tabs, and so forth are for the programmer’s convenience and are ignored by the compiler. The first line of the program

#include <stdio.h>

is called a preprocessor command. Preprocessor commands are iden­ tified by the # at the beginning of the line. In this case, #include tells the preprocessor to open the file stdio.h and read it into the program to be compiled with the remainder of the program. The file name is surrounded by angle brackets < >. These delimiters tell the compiler to search for the file in a region designated by the operating system as SET INCLUDE. Had the file name been delimited by double quotes, “ “, the operating system would have searched only the default directory for the file. The default directory is, of course, the directory from which you are operating.

The next line of the program is a definition for a function named main. In ANSI C, as opposed to classic C, each function definition must inform the compiler of the return type from the function, and the type of the function’s arguments. In this case, the function main has to return an integer and it expects no arguments. The type int preceding the function name indicates that it returns an integer and that no arguments to the function are expected.

The line following the function definition contains an opening brace {. This brace designates the beginning of a block or a com­ pound statement. The next line of the program contains a function call to the function printf(). This function is made available to the program by the inclusion of the header file stdio.h, and it is a function that writes a message to the computer terminal screen. In this case, the message to be sent to the screen is

Microcontrollers run the world!

The escape character ‘\n’ at the end of the message informs the program to insert a new line at that point. The complete message including the new line escape character is enclosed in double quotes. These double quotes identify a string, and the string is the argument to the function printf(). Note that the statement beginning with printf is closed with a semicolon. In C, every statement is termi­ nated with a semicolon.


Some Simple Programs

3

After the message is sent to the screen, there is nothing more for the program to do, so the program is terminated by executing the statement return 0;. This statement returns the value 0 back to the calling program, which is the operating system. Also, execution of the return statement will cause all open files to be closed. If there were no return statement at the end of the program, the normal pro­ cessing at the end of the program would close open files, but there would be no value returned to the calling program.

This is an area where there is much discussion and many dissent­ ing viewpoints. Early C did not require that main return a value to the calling program. When the C89 standard was written, it required that main return an int. Unfortunately, many people, set in their ways, have refused to adhere to the standard nomenclature in this case and they often use void main(void) instead of the form above. Most compilers will ignore this form and allow the void main(void) function call. For some reason, this form angers many code reviewers, so you should use the correct form shown above.

The program is closed by the inclusion of a closing brace, }, at the end. There could be many statements within the block following main() creating a program of any complexity. The closing brace is the terminator of a compound statement. The compound statement is the only case in C where a complete statement closure does not re­ quire a semicolon.

Another program example is as follows:

#include <stdio.h>

int main (void)

{

int a,b,c,d;

a=10;

b=5;

c=2;

d=a*b*c;

printf(“a * b * c = %d\n”, d);

4 Chapter 1 Introduction to C

d=a*b+c;

printf(“a * b + c = %d\n”, d); d=a+b*c;

printf(“a + b * c = %d\n”, d); return 0;

}

Before discussing this bit of code, we need to talk about the num­ bers used in it. Like most high-level languages, C provides for different classes of numbers. These classes can each be variable types. One class is the integer type and a second is the floating point type. We will examine these number classes in more detail later, but for now let us concentrate on the integer types. Integer numbers usually have a numeric range of about ±2 (n-1), where n is the number of bits that contains the integer type. Integers are also called integral types. Inte­ gral types do not “understand” or permit fractions. Any fraction that results from a division operation will be truncated and disappear from the calculation. All variables must be declared or defined to be a specific type prior to their use in a program.

The first line of code in main

int a,b,c,d;

declares the variables a, b, c, and d to be integer types. This par­ ticular statement is both a declaration and a definition statement. A definition statement causes memory to be allocated for each vari­ able, and a label name to be assigned each location. A declaration statement does not cause memory allocation, but rather it merely provides information as to the nature of the variable to the compiler. We will see more of definition and declaration statements later.

The three assignment statements

a=10;

b=5;

c=2;

assign initial values to the variables a, b, and c. The equal sign signifies assignment. The value 10 is placed in the memory location designated as a, etc. The next statement

d=a*b*c;


Some Simple Programs

5

notifies the compiler to generate code that will cause the integer stored in location a to be multiplied by the integer in b and the result of that product to be multiplied by the integer found in c. Usually, the name a, b, or c is used to designate the content of the memory location assigned to the label name. This integer result will be stored in the location identified by d.

The print statement

printf(“a * b * c = %d\n”, d);

is similar to the same statement in the first example. In this case, however, the data string

“a * b * c = %d\n”

contains a printer command character %d. This character notifies the printf function that it is to take the first argument following the data string, convert it to a decimal value, and print it out to the screen. The result of this line of code will be

a * b * c = 100

printed on the screen. The line of code

d=a*b+c;

demonstrates another characteristic of the language. Each operator is assigned a precedence that determines the order in which an ex­ pression is evaluated. The parenthesis operators are of the highest precedence. The precedence of the * operator is higher than that of the + operator, so this expression will be evaluated as

d=(a*b)+c;

In other words, the product indicated by * will be executed prior to the addition indicated by the +. The expression that follows later in the code

d=a+b*c;

will be evaluated as

d=a+(b*c);

causing the result of the third calculation to differ from that of the second.

6 Chapter 1 Introduction to C

The result obtained when running this program is as follows.

a * b * c = 100 a * b + c = 52 a + b * c = 20

Here is another example that demonstrates a primitive looping construct:

#include <stdio.h> int main(void)

{

int i;

i=1;

printf(“\ti\ti\ti\n”); printf(“\t\t Squared Cubed\n\n”); while(i<11)

{

printf(“\t%d\t%d\t%d\n”, i, i*i, i*i*i); i=i+1;

}

return 0;

}

This example was designed to produce a simple table of the val­ ues of the first ten integers, these values squared, and these values cubed. The lines

printf(“\ti\ti\ti\n”); printf(“\t\t Squared Cubed\n\n”);

combine to produce a header that identifies the contents of the three columns generated by the program. The escape character \t is a tab character that causes the screen cursor to skip to the next tab posi­ tion. The default tab value in C is eight spaces.

The command

while(i<11)

.....

causes the argument of the while to be evaluated immediately, and if the argument is TRUE, the statement following the while will be

Some Simple Programs

7

executed. The argument should be read “i is less than 11.” The ini­ tially assigned value for i was 1, so the argument is TRUE. The compound statement

{

printf(“\t%d\t%d\t%d\n”, i, i*i,i*i*i); i=i+1;

}

will start execution with the value of i being equal to 1. Once this statement is evaluated, control is passed back to the while and its argument is evaluated. If the argument is TRUE, the statement fol­ lowing will be evaluated again. This sequence will repeat until the argument evaluates as FALSE.

In this expression, the string argument of the printf function contains three %d commands. Each %d command causes the corre­ sponding argument following the string to be printed to the screen. There are tab characters, \t, to separate the various printed values on the screen. The first %d will cause the value of i to be printed on the screen. The second %d will cause the value i*i, or i2 , to be printed to the screen. The third %d will print the value of i*i*i, or i3 to be printed. When C executes the function call, the values of the arguments are calculated prior to the call, so arguments like i*i are evaluated by the calling program and passed by value to the function.

The statement

i=i+1;

is an example of the use of both precedence and association—the direction in which expressions are evaluated—in C. The equal sign here is an operator just like the + symbol. The + operator is evaluated from left to right, and the = operator is evaluated from right to left. Also, the + operator has higher precedence than the = operator. There­ fore, the above statement will add one to the value stored in i and then assign this new value to the variable i. This expression simply increments the variable i.

The above statement is the terminating statement of the com­ pound statement following the while. Since i had an initial value of 1, control will be returned to the while with a value of 2 for i. 2,