Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (9.59 MB, 687 trang )
Microprocessors
char c;
c = 0x41;
printf("%c
%d
A
65
As an
ASCII
character
(a) Some format specifications.
Replace %d with %u for unsigned int
types. Replace %d with %ld for
long types, and %d with %lu for
unsigned long types.
%x", c, c, c);
41
In
decimal
In
hex
printf("A:%10d B:%-10d C:%04x \n",c,c,c);
C:0041
Field width is
10 digits, right
justified
float q;
{
65 B:65
{
{
A:
Field width is
10 digits,
left justified
Field width is 4 characters,
pad with ‘0’ digits
(b) Floating point format specifications
q= 0.001234;
0.001
C:%e\n",q, q, q);
B: 0.001234
Field width is 6 digits, with three
digits to right of decimal point
C:1.234000e-03
{
A:
B: %f
{
printf ("A: %6.3f
{
558
No field width
Scientific notation
or precision specified
char c, buf[20];
c = 0x41;
sprintf(buf,"%c %d %x", c, c, c);
(c) print to an in-memory buffer
after execution, buf contains
A 65 41
FIGURE D.1 printf() examples.
A %c formats an argument as a single ASCII character, %d specifies an ASCII
decimal format, and %x is used to format an ASCII hex number. The field width is
specified as a number before the format character; %10d specifies a field width of 10
digits. Left justification is the default; a negative sign in the field width (e.g., %-10d)
performs right justification. A leading zero can be specified in the field width as in
%04x to pad the number with leading zeros. A leading l (letter l) is used in the format specification if the argument is a long rather than an int (i.e., %ld instead of %d).
A %u can be specified in place of a %d for an unsigned data type. Floating-point
(float or double) format specifications use %f or %e as shown in Figure D.1b. A format specification of the form %n.mf specifies a field width of n digits, with m digits
Appendix D: Notes on the C Language
559
of precision to the right of the decimal point. The %e specification causes the floatingpoint number to be printed in scientific notation. The sprintf() function is used to
print the string to an in-memory buffer; the first argument to sprintf() is the char
buffer for the output string as shown in Figure D.1c.
The scanf() function is used for formatted ASCII input; within the PICC-18 C
compiler environment the scanf() library function calls the getche() function (get
character and echo) to input each ASCII byte. The getche() function is assumed to
echo its character using the putch() function. The scanf() function expects pointers to the variables in the parameter list; hence, the & operator (address-of operator)
is placed in front of any variables that are passed to scanf(). Figure D.2 shows examples of scanf() with %d (decimal), %x (hex), and %f (float) numbers. The leading
0x on the hex number input is optional. The scanf() function skips over any white
space (space characters, tabs, etc.) it encounters when scanning the input for a
match to the format specification. The sscanf() (string scanf()) function can be
used to read values from an in-memory buffer; the first argument to sscanf() is the
char buffer to scan.
unsigned char c;
float q;
printf("Enter decimal number: ");
scanf("%d",&c);
printf("The number is %d\n", c);
Enter decimal number: 49
The number is 49
printf("\nEnter hex number: ");
scanf("%x",&c);
printf("The hex number is %x\n", c);
Enter hex number: 0xEC
The hex number is ec
printf("\nEnter a float number: ");
scanf("%f",&q);
printf("The float number is %f\n",q);
Enter a float number: 1.239202
The float number is 1.239202
FIGURE D.2 scanf() examples.
D.2 FOR C++ PROGRAMMERS
A simple, but common error made by C++ programmers when adjusting to C is
variable declarations. In C++, variable declarations can be placed anywhere within
a function as shown in Listing D.1.
560
Microprocessors
LISTING D.1 C++ Variable declarations.
main() {
// compiled with a C++ compiler
char c;
c = 0x41;
c++;
int i;
i++;
//variable declaration
}
However, in C the second variable declaration int i must either go at the top
of the function with the char c declaration or be enclosed in a block using {} as
shown in Listing D.2. However, be careful—variables declared within a block {} are
not visible to statements outside of that block.
LISTING D.2 C Variable declarations.
main() {
//compiled with C compiler
char c;
c = 0x41;
c++;
{ // be careful, ‘i’ scope is limited to within brackets!
int i;
//variable declaration
i++;
}
}
D.3 FOR NEW PROGRAMMERS
If you don’t have much programming experience, the number of syntax errors reported by the C compiler after compiling your first program may overwhelm you.
A useful tip relevant to almost any programming language is to fix only the first
syntax error; many of the remaining errors are most probably side effects of that
first syntax error. Do not be intimidated by a listing of 100+ errors; concentrate on
fixing the first one and many of the remaining errors will vanish on the next compile.
D.4 FOR EXPERIENCED C PROGRAMMERS
This book’s usage of the C language is kept fairly simple to aid the new C programmer’s understanding of the example programs. If you are comfortable with the C
language, you are encouraged to modify the book’s examples to make use of the
more powerful features of the language. For example, macros can be employed to
Appendix D: Notes on the C Language
561
automatically compute the numbers for the serial port baud rate, I2C bus speed,
timer interrupt periods, and so forth to make the examples independent of a particular FOSC value. In some of the more complex examples, use of struct data
types for related variables may be appropriate.
If you are an experienced C programmer (perhaps from an X86 platform),
there are many shortcuts for certain code segments discussed in book examples. For
example, the code in Chapter 10, “Interrupts and a First Look at Timers,” for placing data into a software FIFO is written as:
head = head + 1;
if (head == BUFMAX) head = 0;
ibuf[head] = RCREG
Here, BUFMAX is a power of 2, and head is a char variable. An experienced C
programmer might write instead:
ibuf[(++head)%BUFMAX] = RCREG;
This works because % is the C modulo operator and BUFMAX is a power of 2,
meaning that it is evenly divisible into 256, which is the number of possible code
values for the head variable. While the number of C statements is reduced from 3 to
1, the amount of assembly code generated is much higher as the modulo operation
requires a division operation, an expensive operation in terms of machine code and
instruction cycles on the PIC18. So, be careful when writing “tight” C code—it
might not translate into “tight” machine code once it is compiled.
This page intentionally left blank
Appendix
E
Suggested Laboratory
Exercises
his appendix contains the laboratory exercises for a semester-length course
taught at Mississippi State University since summer 2004. We first began
teaching a PIC-based introductory microprocessor course in fall 2003 using
the PIC16F873, and switched to the PIC18F242 in summer 2004.
T
E.1 LAB SETUP
Table E.1 lists the lab equipment assumed by these experiments. Each lab station
should have an oscilloscope and a multimeter. In addition, if each student does not
have a portable PC, every lab station must have a desktop PC. Each lab station
should either have a LAN connection or the lab should be wireless enabled.
TABLE E.1 Suggested Lab Equipment
Equipment
Comment
Networked PC
Lab station only needs a LAN connection if student has a
portable PC.
Multimeter
Basic instrumentation.
Oscilloscope
Basic instrumentation.
PICSTART
Programmer
This is used for programming PICs with the serial
bootloader and initial test programs; it can be shared
among multiple stations.
Soldering and wire
wrap tools/supplies
Either soldering or wire wrap is used for external
connectors; multiple stations can share this.
Universal remote control
Used by Experiment 12 for IR waveform decoding.
563
564
Microprocessors
Because a serial bootloader is used to program the PIC18F242 in a majority of
the hardware labs, each PC must either have a serial port or a USB-to-serial port
adapter. The lab also must have some method of programming a PIC18F242 without a serial bootloader; we use a Microchip PICSTART Plus programmer (Appendix F, “The Jolt/Colt Serial Bootloaders”) shared among 10 lab stations. Software
installed on each PC to support the PIC18F242 experiments are MPLAB, the HITECH PICC-18 compiler, and the Jolt/Colt bootloaders (Appendix F). The lab experiments consist of 13 experiments: one digital-logic based, four assembly
language based, and eight hardware based. In the last week of the semester we hold
a lab practicum to evaluate student skills for ABET assessment purposes. The hardware experiments use a parts kit and a prototyping board purchased by each student. Through the eight hardware experiments, a student builds a PIC18F242
system that has an external I2C serial EEPROM, I2C DAC, asynchronous serial interface, a potentiometer, a mini-jack for audio input/output, and an IR receiver.
Wire wrap is used for external connectors like the DB9 required for the serial port;
the lab has wire wrap supplies (tools/wire) shared by the students. The lab also has
a couple of soldering irons for creating reliable connections to external connectors
if students prefer that over wire wrap. Figure E.1 shows a picture of the prototyping
board at the end of the semester after all experiments have been added to the board.
DB9
IR Receiver
MAX202
Fuse
CD4053
7805
10K SIP
Pwr Switch
240Ω SIP
PIC18F242
MAX517
24LC515
Reset sw.
LM386
Crystal
Audio
Mini-jack
Modular Connector
for ICD2 (optional)
FIGURE E.1 Protoboard at semester end.
10K Pot
Pwr Conn
Appendix E: Suggested Laboratory Exercises
565
The parts kit list used during the fall 2004 semester is shown in Figure E.2 along
with supplier part numbers. We purchase the part kits pre-assembled from Electronix Express (www.elexp.com) at a substantially reduced price over what can be ordered by students in single quantities from parts suppliers. The protoboard and
wiring kit are usually purchased in a previous digital logic course. The modular connector was previously included to support in-circuit programming via the Microchip
ICD2 programmer (Appendix F), but this has been dropped and is now optional.
FIGURE E.2 Parts kit list.
Based on MSU experience, the following points are key for a successful lab
course using this approach:
566
Microprocessors
It is best if students have had some previous experience with protoboards before this lab. In the MSU ECE/CSE curriculum, students are required to take a
digital logic course as a prerequisite with the digital lab experience providing
them with some protoboard experience in wiring 74XX logic. This gives them
an introduction to DIP packages, how protoboard wiring works, an introduction to an oscilloscope and a multimeter, and some basic circuit debugging
(which is greatly increased in this course!). A circuits course is not a prerequisite except for circuit fundamentals as presented in a physics course; we have
majors from electrical engineering, computer engineering, computer science,
and software engineering who take this lab so a circuits prerequisite is not possible.
The teaching assistants (TAs) for the lab must be talented, knowledgeable, dedicated, patient, and have had previous microcontroller experience to assist students in the inevitable hardware debugging problems. We recruit our TAs from
the graduates of this course; the first TAs came from a traditional microcontroller course that has since been replaced by our second course in embedded
systems. We limit enrollment in each lab section to 10 students because the
hardware labs dramatically increase the “help me!” load on the TA. The first
two hardware labs are the worst from a TA load perspective when students are
bringing their initial PIC18F242 setup to life; our labs are open so students can
work on their protoboards outside of normal lab hours if needed.
The TA must have a reference board built for demo purposes and for checking
bad part problems by plugging the part into the reference board.
A spare parts supply is an absolute necessity, as students demonstrate an amazing talent for destroying ICs. The TA, course instructor, IEEE/HKN, or some
central shop can sell these. Fuses have been our top sellers.
ON THE CD
It is rewarding to watch students with near-zero prototyping skills gain confidence as the semester progresses, and show pride in their board as they build it up
from a collection of ICs and wires to something that records and plays audio in the
final experiment.
In the following experiment descriptions, the prelab activity should be completed before the student enters the lab. All of the files and zip archives referenced
in the lab descriptions are contained in the code/labs directory on the companion
CD-ROM.
E.2 EXPERIMENT 1: A STORED PROGRAM MACHINE (CHAPTERS 1, 2)
This experiment has the students implement the Number Sequencing Computer
from Chapter 2 using the digital logic simulation package from a previous digital
Appendix E: Suggested Laboratory Exercises
567
logic course. At MSU, this is the Altera Maxplus package. We give the students the
design already entered in Altera Maxplus and have them write a program that outputs their own student ID number or phone number. The ROM module in Altera
MAXPLUS reads its initial contents from an external file; the students must assemble their program and modify the ROM file that specifies the machine code for their
program. Students also step through the logic simulation within Altera MAXPLUS
and determine how many clock cycles it takes to output the two number sequences
based on the LOC input. The nsc.zip archive on the books’s supplemental lab Web
site (www.reesemicro.com) contains the Altera Maxplus design for the number sequencing computer in Chapter 2. In this lab, the TAs also assists the students in installing MPLAB, the Jolt Bootloader, and the PICC18 compiler on their portable PCs.
E.3 EXPERIMENT 2: PIC18XX2 INTRODUCTION (CHAPTER 3)
This experiment introduces the student to the PIC18Fxx2 instructions covered in
Chapter 3 and the MPLAB environment.
Prelab
1. Assemble and simulate the “Simple” example in Listing 3.9 within MPLAB
(filename is mptst.asm). Verify that the final value of k (location 0x02) contains the expected value of 0xC9 when the goto here statement is reached.
2. Change the value of the avalue symbol to be the decimal equivalent of the
last two digits of your student ID. If the last two digits of your student ID
are “00”, use the first two digits. Compute the new expected value of k
when the goto here statement is reached; verify this value by assembling
and simulating the program. Capture a screen shot that shows the program
memory and file register contents when the goto here statement is reached.
Lab Activity
Exploring Data Memory Storage
1. Modify the mptst.asm file so that the CBLOCK starting location is 0x80. Re-assemble and re-execute the program. Verify that the i, j, k variables are updated at locations 0x80-0x82. When the program memory is viewed, the
instruction at program location 0x202 is now different from the original