(HOTT) Workshop: Introduction to Microcontroller Programming in C

advertisement
Student name:_______________________
Hands-On Technical Training (HOTT) Workshop:
Introduction to Microcontroller Programming in C
Rev. 10JULY2008
Table of Contents
Hands-On Technical Training (HOTT) Workshop: Introduction to Microcontroller
Programming in C ............................................................................................................... 1
Table of Contents ............................................................................................................ 1
How to Use this Training Material if provided on CD or in Zipped File: ...................... 3
Workshop objectives:...................................................................................................... 3
Prerequisites: ................................................................................................................... 3
What is an Embedded Controller? .................................................................................. 4
What is a Microcontroller? ............................................................................................. 4
Microcontroller Advantages ........................................................................................... 4
Microcontroller Disadvantages ....................................................................................... 4
Microcontroller Architecture Example ........................................................................... 5
Microcontroller Selection Considerations ...................................................................... 5
Lab Setup for this Workshop .......................................................................................... 7
Programming Language Considerations ......................................................................... 7
A Brief Introduction to the C Programming Language .................................................. 8
Data Types .................................................................................................................. 8
Declaring Variables and Assigning an Initial Value................................................... 8
Arithmetic Operators .................................................................................................. 9
Comparison ............................................................................................................... 10
Logical Connectors ................................................................................................... 11
The if else Statement ................................................................................................. 11
Loops......................................................................................................................... 12
The for Loop ............................................................................................................. 13
Functions in C ........................................................................................................... 13
Freescale IDE Software Installation ............................................................................. 16
Hardware Familiarization and Connection to PC ......................................................... 16
Understanding the RS08 I/O ......................................................................................... 17
Launching & Exploring the IDE ................................................................................... 19
Creating a new project .............................................................................................. 19
Configuring the Microcontroller Chip for Proper Operation with the Development
Board ......................................................................................................................... 23
Editing and Downloading a Program ........................................................................ 25
Modifying the Program to Slow Down the LED1 Blink Rate .................................. 28
Debug Tools: Monitoring, I/O, Breakpoints, and Other Neat Stuff ............................. 30
Monitoring the Program & I/O ................................................................................. 30
Using Breakpoints ..................................................................................................... 31
Stand-alone uC Circuit Example: Minimum Circuit Required for the Hello World
Example Program...................................................................................................... 32
Links to Executable Programming Examples Provided with this Training Material (CD
or unzipped directory) ................................................................................................... 33
Additional Resources .................................................................................................... 35
Documents Provided with this Training Material (CD or unzipped directory) ........ 35
Online Resources ...................................................................................................... 35
Support ...................................................................................................................... 35
Purchasing Your Own Demo Kits and Microcontrollers .......................................... 35
533577557
Page 2 of 35
How to Use this Training Material if provided on CD or in Zipped
File:
1. Unzip if necessary and copy entire root directory of all files to your PC hard
drive.
2. Open this document file in your web browser. There are hyperlinks located
throughout that will enrich your user experience.
Workshop objectives:
1.
2.
3.
4.
Learn what a microcontroller is and some typical applications.
Learn some criteria to consider when selecting a microcontroller.
Learn fundamental microcontroller programming in the C language.
Learn how to use a typical C Compiler and IDE (Integrated Development
Environment) for developing microcontroller applications.
5. Learn the basics of C programming by editing various C programs and testing
them on an actual Freescale RS08 microcontroller.
Prerequisites: None, but some programming experience is helpful, especially C,
C++, or C#.
533577557
Page 3 of 35
What is an Embedded Controller?
As stated at http://www.esacademy.com/automation/faq/primer/2.htm:
An embedded controller is basically a controller (typically a microcontroller,
microprocessor, or computer) that is embedded into some [system or] device for
some purpose other than to provide general purpose computing.
This device would be called an Embedded Control System. Some examples might be a
home appliance or toy with a microcontroller inside of it or a factory automation system
that contains a dedicated computer control box.
What is a Microcontroller?
According to wikipedia:
A microcontroller (also MCU or µC) is a computer-on-a-chip. It is a type of
microprocessor emphasizing self-sufficiency and cost-effectiveness, in contrast to
a general-purpose microprocessor (the kind used in a PC). In addition to all
arithmetic and logic elements of a general purpose microprocessor, the
microcontroller usually also integrates additional elements such as read-only and
read-write memory, and input/output interfaces.
Microcontroller Advantages








Highly integrated and powerful – thousands of transistors on a single chip.
Can be used to replace a handful of discrete logic chips.
Relatively easy to learn and implement.
Easier to integrate into a design than discrete logic chips.
Very low hardware cost possible (the RS08KA2 microcontroller chip used in this
lab costs less than $0.50 each in large quantities!).
Many types and manufacturers available.
Architectures and programming languages vary somewhat, but not completely, so
what you learn about one microcontroller (uC) is good knowledge to apply to
another one.
Many different IC packages available (DIP8, SOIC-16, etc.)
Microcontroller Disadvantages


Microcontrollers are IC chips and need to be put onto a custom-designed PC
board. This takes time and money, which may not suit all applications. Contrast
this with an industrial automation PLC, which is a computer-in-a-box that
contains simple screw terminals to connect power, communication, and I/O.
Programming microcontrollers requires a certain amount of skill and training.
533577557
Page 4 of 35

The programming and debugging software can be quite costly.
Microcontroller Architecture Example
An example of a simple microcontroller is shown here embedded in a system:
Embedded Control System
Freescale RS08KA2 Microcontroller Chip
Timers
&
Counters
Interrupt
Control
Subsystem
Memory
Areas
Core
Microprocessor
Analog
Comparator
Input/Output (I/O) Section
To other electronic devices (pushbuttons,
LEDs, speakers, etc.)
Microcontroller Selection Considerations
The following list shows items to be considered when selecting a microcontroller. Each
application will be unique, so some of these considerations may not apply.

I/O count and type
o Digital?
o Analog
 Number of inputs and outputs?
 Resolution?
 Conversion time?
 Voltage range?
o PWM?
533577557
Page 5 of 35
















o Interrupts?
o Output drive current?
o Logic voltage levels?
Amount of on-chip memory?
External memory
o Possible?
o Maximum amount?
Supply voltage range and current required?
Bus speed?
Floating point (real number) math support?
Timers – quantity, resolution, maximum time?
Other special functions needed?
Rated temperature range?
Cost per device?
Manufacturer’s sampling policy?
Development tools
o Cost?
o Features?
o Many types of chips supported or just one or two?
o Additional adapters needed (at what cost?) to use with other chips in same
family?
o Can it be easily connected to in-circuit chips?
Programming software
o Cost?
o IDE (Integrated Development Environment) learning curve?
o Programming language(s) supported – C, Assembly, Java, BASIC, etc.?
o Support – email, online, phone, etc.?
o Does it support different chips by same manufacturer, or might different
versions be needed later for higher end chips?
o Does it have a built-in chip simulator?
Prior experience with chip, manufacturer, or software?
Application notes and reference designs online?
Reputation of manufacturer?
Support
o Email?
o Online?
o Phone?
o Forums?
533577557
Page 6 of 35
Lab Setup for this Workshop
For this workshop, we will be using the following hardware and software:
1. The low-end Freescale RS08 microcontroller,
2. An inexpensive but effective development board called the DEMO9RS08KA2,
3. and the CodeWarrior IDE/C Compiler.
The RS08 chip is simple but effective for learning the basics of microcontrollers. It is
also well documented and suits a variety of end-user applications.
Programming Language Considerations
The C language is currently the most popular programming language for embedded
control using microcontrollers. This language offers a good balance of being relatively
easy to learn yet able to perform powerful low-level functions such as bit-level I/O.
Freescale offers the CodeWarrior C compiler free of charge for use with the RS08 and a
number of other Freescale microcontrollers and microprocessors. Very few other
manufacturers offer a free C compiler, with many costing several hundred dollars or more
per license. Note that Freescale charges a fee for the C compiler required for higher end
microcontrollers. Zilog is another microcontroller manufacturer that offers a free C
compiler, so they may be worth considering for cost conscious applications. One
advantage of the Freescale CodeWarrior IDE compared to Zilog’s IDE is that Freescale
includes a very nice hardware configuration GUI. You’ll see that up close in just a little
while.
533577557
Page 7 of 35
A Brief Introduction to the C Programming Language
(some of this information was borrowed from http://www.imada.sdu.dk)
Copyright Notice and Credits
© The University of Strathclyde, Glasgow, Scotland.
Permission to copy is granted provided that these credits remain intact.
These notes were written by Steve Holmes of the University of Strathclyde Computer Centre. They originally formed the basis of the Computer Centre's
C programming course. Steve no longer works for the University of Strathclyde, and we are unable to answer queries relating to this course. You are
welcome to make links to it however, but please bear in mind that it was written for students within the University and so some parts may not be relevant
to external readers.


C is case sensitive.
C allows programmers to separate the code into “functions”, which are similar to
subroutines but more powerful. More info about that in a little while.
Data Types
Below is a partial list of numeric data types supported by the C language.
Data Type
Abbreviation
Range
Integer
int
-32,768 to 32,767
Short
short
-32,768 to 32,767
Long
long
-2,147,483,648 to 2,147,483,647
Unsigned int
uint
0 to 65,535
Byte
byte
0 to 65,535
Unsigned long
ulong
0 to 4,294,967,295
Floating point
float
10-37 to 1037
Declaring Variables and Assigning an Initial Value
Before a variable may be used in a C program, it must be declared by name (i.e., created)
and given a data type. Here is an example of a variable declaration:
int LoopCount;
In this declaration, the data type is “int” for integer.
The variable name is “LoopCount”. This variable may be used in the program from this
point forward.
Finally, note that the instruction must end with a semicolon. This is generally true of
C instructions.
533577557
Page 8 of 35
While the declaration is not required to assign a value to the variable, it is a very good
idea to do both together. Therefore, this is a better declaration, which also contains an
assignment statement:
int LoopCount = 0;
The variable “LoopCount” is declared and assigned a value of zero.
Arithmetic Operators
Here are the most common arithmetic operators
*, / and % will be performed before + or - in any expression. Brackets can be used to
force a different order of evaluation to this. Where division is performed between two
integers, the result will be an integer, with remainder discarded. Modulo reduction is only
meaningful between integers. If a program is ever required to divide a number by zero,
this will cause an error, usually causing the program to crash.
Here are some arithmetic expressions used within assignment statements:
velocity = distance / time;
force = mass * acceleration;
count = count + 1;
C has some operators which allow abbreviation of certain types of arithmetic assignment
statements.
These operations are usually very efficient. They can be combined with another
expression.
Versions where the operator occurs before the variable name change the value of the
variable before evaluating the expression, so
533577557
Page 9 of 35
These can cause confusion if you try to do too many things on one command line. You
are recommended to restrict your use of ++ and - to ensure that your programs stay
readable.
Another shorthand notation is listed below
Comparison
C has no special type to represent logical or boolean values. It improvises by using any of
the integral types char, int, short, long, unsigned, with a value of 0 representing false and
any other value representing true. It is rare for logical values to be stored in variables.
They are usually generated as required by comparing two numeric values. This is where
the comparison operators are used, they compare two numeric values and produce a
logical result.
Note that == is used in comparisons and = is used in assignments. Comparison operators
are used in expressions like the ones below.
x == y
i > 10
a + b != c
In the last example, all arithmetic is done before any comparison is made.
533577557
Page 10 of 35
These comparisons are most frequently used to control an if statement or a for or a while
loop.
Logical Connectors
These are the usual And, Or and Not operators.
They are frequently used to combine relational operators, for example
x < 20 && x >= 10
In C these logical connectives employ a technique known as lazy evaluation. They
evaluate their left hand operand, and then only evaluate the right hand one if this is
required. Clearly false && anything is always false, true || anything is always true. In
such cases the second test is not evaluated.
Not operates on a single logical value, its effect is to reverse its state. Here is an example
of its use.
ReadyLight = !HeaterActive;
The if else Statement
This is used to decide whether to do something at a special point, or to decide between
two courses of action.
The following test decides whether a student has passed an exam with a pass mark of 45
if (result >= 45)
printf("Pass\n");
else
printf("Fail\n");
It is possible to use the if part without the else.
if (temperature < 0)
print("Frozen\n");
Each version consists of a test, (this is the bracketed statement following the if). If the test
is true then the next statement is obeyed. If it is false then the statement following the else
is obeyed if present. After this, the rest of the program continues as normal.
533577557
Page 11 of 35
If we wish to have more than one statement following the if or the else, they should be
grouped together between curly brackets. Such a grouping is called a compound
statement or a block.
if (result >= 45)
{
printf("Passed\n");
printf("Congratulations\n")
}
else
{
printf("Failed\n");
printf("Good luck in the future!\n");
}
Sometimes we wish to make a multi-way decision based on several conditions. The most
general way of doing this is by using the else if variant on the if statement. This works by
cascading several comparisons. As soon as one of these gives a true result, the following
statement or block is executed, and no further comparisons are performed. In the
following example we are awarding grades depending on the exam result.
if (result >= 75)
printf("Passed: Grade A\n");
else if (result >= 60)
printf("Passed: Grade B\n");
else if (result >= 45)
printf("Passed: Grade C\n");
else
printf("Failed\n");
In this example, all comparisons test a single variable called result. In other cases, each
test may involve a different variable or some combination of tests. The same pattern can
be used with more or fewer else if's, and the final lone else may be left out. It is up to the
programmer to devise the correct structure for each programming problem.
Loops
C gives you a choice of three types of loop, while, do while and for.



The while loop keeps repeating an action until an associated test returns false.
This is useful where the programmer does not know in advance how many times
the loop will be traversed.
The do while loops is similar, but the test occurs after the loop body is executed.
This ensures that the loop body is run at least once.
The for loop is frequently used, usually where the loop will be traversed a fixed
number of times. It is very flexible, and novice programmers should take care not
to abuse the power it offers.
533577557
Page 12 of 35
The for Loop
The for loop works well where the number of iterations of the loop is known before the
loop is entered. The head of the loop consists of three parts separated by semicolons.



The first is run before the loop is entered. This is usually the initialization of the
loop variable.
The second is a test, the loop is exited when this returns false.
The third is a statement to be run every time the loop body is completed. This is
usually an increment of the loop counter.
The example is a function which calculates the average of the numbers stored in an array.
The function takes the array and the number of elements as arguments.
int
count;
for (count = 1; count <= 10; count++)
PTAD_PTAD4 = !PTAD_PTAD4;
The for loop causes the instruction to execute ten times.
The three statements at the head of a for loop usually do just one thing each, however any
of them can be left blank. A blank first or last statement will mean no initialization or
running increment. A blank comparison statement will always be treated as true. This
will cause the loop to run indefinitely unless interrupted by some other means. This might
be a return or a break statement.
The for loop is extremely flexible and allows many types of program behavior to be
specified simply and quickly.
The complete discussion of different types of loops is rather lengthy and has not been
included here. For more information, refer to the following website:
http://www.imada.sdu.dk/~svalle/courses/dm142005/mirror/c/subsection3_8_3.html#SECTION0008300000000000000.
Functions in C
Almost all programming languages have some equivalent of the function. You may have
met them under the alternative names subroutine or procedure.
Some languages distinguish between functions which return variables and those which
don't. C assumes that every function will return a value. If the programmer wants a return
value, this is achieved using the return statement. If no return value is required, none
should be used when calling the function.
533577557
Page 13 of 35
Here is a function which raises a double to the power of an unsigned, and returns the
result.
double power(double val, unsigned pow)
{
double ret_val = 1.0;
unsigned i;
for(i = 0; i < pow; i++)
ret_val *= val;
return(ret_val);
}
The function follows a simple algorithm, multiplying the value by itself pow times. A for
loop is used to control the number of multiplications, and variable ret_val stores the value
to be returned. Careful programming has ensured that the boundary condition is correct
too.
Let us examine the details of this function.
double power(double val, unsigned pow)
This line begins the function definition. It tells us the type of the return value, the name
of the function, and a list of arguments used by the function. The arguments and their
types are enclosed in brackets, each pair separated by commas.
The body of the function is bounded by a set of curly brackets. Any variables declared
here will be treated as local unless specifically declared as static or extern types.
return(ret_val);
On reaching a return statement, control of the program returns to the calling function. The
bracketed value is the value which is returned from the function. If the final closing curly
bracket is reached before any return value, then the function will return automatically,
any return value will then be meaningless.
The example function can be called by a line in another function which looks like this
result = power(val, pow);
This calls the function power assigning the return value to variable result.
Here is an example of a function which does not return a value.
void error_line(int line)
{
fprintf(stderr, "Error in input data: line %d\n", line);
}
The definition uses type void which is optional. It shows that no return value is used.
Otherwise the function is much the same as the previous example, except that there is no
return statement. Some void type functions might use return, but only to force an early
533577557
Page 14 of 35
exit from the function, and not to return any value. This is rather like using break to jump
out of a loop.
This function also demonstrates a new feature.
fprintf(stderr, "Error in input data: line %d\n", line);
This is a variant on the printf statement, fprintf sends its output into a file. In this case,
the file is stderr. stderr is a special UNIX file which serves as the channel for error
messages. It is usually connected to the console of the computer system, so this is a good
way to display error messages from your programs. Messages sent to stderr will appear
on screen even if the normal output of the program has been redirected to a file or a
printer.
The function would be called as follows
error_line(line_number);
533577557
Page 15 of 35
Freescale IDE Software Installation
The necessary software, “Special Edition: CodeWarrior for Microcontrollers”, is already
installed on the computers in this lab, so we won’t be installing it today. However, if you
want to download and install the free IDE/Assembler/C compiler on your own PC, you
should go to www.freescale.com and search for keywords “codewarrior for
microcontrollers special edition download”, then look for the Download link. The
installation process is quite easy, though it may take the better part of an hour.
Note: If you purchased a demonstration board, that package may include a CD or DVD
with an earlier version of the IDE that does not include the C compiler. This should not
be installed.
If you purchase a development board like the one used in this lab, you will also need to
install the USB drivers to enable the PC to communicate with the board.
Hardware Familiarization and Connection to PC
Demo board hardware is described in the demonstration board user’s manual on various
pages. Click the link and/or go to the manual, read the pages listed below, and answer
these questions:
1. Referring to the user’s manual section 1.3, what devices are supported by the
DEMO9RS08KA2 development board?
____________________________________________________
2. From PDF pages 9 & 10 (manual pages 7-8), briefly review the location of the
various items on the demo board, comparing your actual board to the drawing and
description. Note that the programming target microcontroller is a socketed DIP
that may be removed after it is programmed. This is convenient for stand-alone
applications. Also, realize that the majority of the board exists simply to support
communication with the PC and demo I/O (LEDs, pushbuttons, and NTC
resistor). As a side note, Zilog handles this in a different way that some designers
prefer.
3. Section 8 in the manual outlines the various jumper and connector settings.
Review it briefly at this time and locate the connectors on your demo board. If
you are not familiar with this type of jumper, ask your lab instructor to
demonstrate how it works.
4. Read through section 4.1, entitled “First Connection”, and go through the steps to
verify the demo board jumper settings and connect the board to the PC USB port.
Emphasizing again, the microcontroller is one small chip on the development board. The
rest of the board is fairly complex and exists to support USB communication with the
host PC. Without getting too concerned with the abbreviations right now, consider this
example of a simple, stand-alone microcontroller application:
533577557
Page 16 of 35
Freescale RS08KA2
microcontroller in
SMT package is the
embedded controller
in this music box
Understanding the RS08 I/O
Look at Figure 2-2 in the RS08 data sheet. Most of the pins are multi-purpose, described
by terms such as “PTA3/ACMPO/BKGD/MS”. Refer to Table 2-1 and fill in the blanks
below with the functions associated with each of these terms:
PTA3 (Port A, bit 3): ___________________________________
ACMPO: __________________________________
BKGD: ___________________________________
MS: ______________________________________
The data sheet table describes each of the RS08 pins and not just the PTA3 pin. Refer to
this as necessary throughout the lab if you are having problems understanding the pin
names and functions.
While you’re on that page, right above Table 2-1 is a paragraph that says:
533577557
Page 17 of 35
NOTE To avoid extra current drain from floating input pins, the reset
initialization routine in the application program should either enable on-chip
pullup/pulldown devices or change the direction of unused pins to outputs.
Two important points should be made here. First, typical of CMOS integrated circuits
with their high input impedance MOSFETs, the RS08 will possibly oscillate and/or draw
excess current if an input is left floating. Normally this is solved by tying any unused
inputs high or low. However, and this is the second point, the RS08 contains internal
pullup and pulldown resistors (approx. 50-60 kilohms each) that may either be connected
or disconnected, depending upon the configuration (initialization) settings, which will be
examined in more detail shortly. Any pins configured as inputs should have their
internal pullup or pulldown resistors connected unless the external circuitry makes
provision for pullup/pulldown. Remember that when you make configuration
settings in the software.
Section 2.4 in the data sheet provides a detailed explanation of each of the pins on the
chip. Glance through it now.
Statements such as the following may be ignored unless you plan to handle device
initialization yourself through program code: “To use as an output-only port, BKGDPE in
SOPT must be cleared.” This refers to initializing the device, or telling it which pins are
inputs, outputs, etc., which is not normally a concern since device initialization is handled
through a very nice GUI (Graphical User Interface) in the IDE. That tool enables RS08
programmers to easily generate device initialization code, which runs once when the
microcontroller begins program execution.
Refer to the schematic for the demo board, which is in a separate document, and draw
lines in the following table connecting each microcontroller pin listed in the left column
to its corresponding development board component on the right. The first one has been
done for you.
PTA0/KBIP0/ACMP+
PTA1/KBIP1/ACMP
PTA2/KBIP2/TCLK/RESET/VPP
PTA3/BKGD/MS/ACMPO
PTA4/KBIP4
PTA5/KBIP5
SW0
RESET
NTC
LED1
LED2
LED0
The bold items in the list above are the settings required for connection to the devices
listed on the right. These settings would be made using the Device Initialization tool.
533577557
Page 18 of 35
Launching & Exploring the IDE
Creating a new project
1. Launch CodeWarrior IDE from desktop icon. This is the PC application for
programming and debugging the microcontroller.
2. If the Startup window dialog box appears, select Create New Project. If not,
select File > Startup Dialog, then click Create New Project.
3. Refer to the diagram below. In the New Project dialog box, expand the left-side
tree and select the MC9RS08KA2 device. This is the microcontroller you’ll be
programming.
4. Select the SofTec RS08 for the default connection and click Next.
5. Select C as the programming language and no others.
6. For the project name, type in “Hello World.mcp” as shown below, then set the
location to My Documents and click Next.
533577557
Page 19 of 35
7. The next step of the wizard asks you if you want to add existing files to your
project. We don’t need any pre-existing files for this project, so click Next again.
8. Recall that most of the pins on this microcontroller can serve multiple purposes.
The Device Initialization tool (the GUI mentioned earlier) enables you to edit
those pin assignments from within your project. Select Device Initialization as
shown below and click Next.
533577557
Page 20 of 35
9. On the following screen, make sure the selections are set as illustrated below.
This will cause the wizard to generate the necessary program files with code stubs
to make your programming job easier. Also, floating point or real numbers will
not be used in this project, so that option should be deselected. Floats require a
large amount of memory and do not work well on the RS08 because of its very
small memory area.
533577557
Page 21 of 35
10. Click Finish and the wizard will build your project.
533577557
Page 22 of 35
Configuring the Microcontroller Chip for Proper Operation with the
Development Board
1. The right side of the CodeWarrior IDE should display the Device Initialization
tool illustrated below. If not, select from the menu Device Initialization >
Initialize Device.
2. We will now make some basic CPU settings. Click the CPU block in the Device
Initialization GUI, which should open a new window where you will make those
changes.
3. In the window that opens, expand the Internal Peripherals area and verify that
BDM pin support is Enabled. This allows debugging the microcontroller
operation from the PC, which is a very nice programming feature that we’ll be
using. If you look at the development board schematic, you’ll see that the debug
pin is shared with one of the LEDs, so it will blink when the PC is communicating
with the microcontroller. Incidentally, “BKGD” and “BDM” are interchangeable
533577557
Page 23 of 35
terms that both refer to the background debug pin. If the BDM pin support is
Disabled, click the button on that row to enable it.
4. If the Reset pin support is Disabled, click the button on that row to enable it. This
will assign the Reset pin on the development board to recognize the Reset button.
5. Click OK to accept those CPU changes.
6. The CPU contains a special section called a Watchdog or Computer Operating
Properly (COP) that supervises operation of the CPU. It’s a handy feature, but we
will not be using it at this time and so it must be disabled. Select the Device
Initialization block labeled COP and change the Initialization option to Enable
COP no. Click OK.
7. PTA, or Port A, is Freescale’s name for the group of 6 I/O pins. Click the PTA
block to select this port and configure the pins.
8. Under Settings, Port Control, click the button on that row to change the setting
from “Entire I/O port” to “Individual pins”. We will be configuring some pins as
inputs and some pins as outputs.
9. Referring to the information you studied above and/or the demo board schematic,
note that SW0 is connected to microcontroller pin PTA1/KBIP1/ACMP. This pin
can serve three purposes, as alluded to earlier. Since this pin is connected to
switch SW0, set it as Enabled with Direction set to Input. Looking ahead, the
name “PTAD_PTAD1” will be used in the program to refer to this input.
10. Again referring to the previous information, set the appropriate pins as Outputs
for LED1 and LED2. Your settings should appear as below.
533577557
Page 24 of 35
11. Click OK to accept the Port A changes. Notice that the Device Initialization
blocks that have been changed from their default settings now appear aqua in
color.
12. Find and click the Generate Code button.
This step is very
important because it commands the IDE to convert the changes you just made into
programming code that will be sent to the microcontroller. Read the additional
dialog boxes that pop up, accept the defaults for now, and use common sense to
respond.
Editing and Downloading a Program
1. The left side of the IDE shows the overview of your new project. The main
program file is appropriately named “main.c”. Double click main.c to open it for
editing. In this example, you’ll be writing a program to turn LED1 on and off
when switch SW0 is pressed.
533577557
Page 25 of 35
Your main.c program file should appear something like this:
2. In the main.c file, there are several lines you should basically understand but
don’t need to change. First, there are some “#include” statements at the top of the
file. These were inserted automatically when the project was created and direct
the compiler to compile those other files before compiling the main file. These
lines are necessary and should not be modified. Next, the line that begins with
“void MCU_init(void);” is called a “function prototype” and tells the compiler the
“signature” of function MCU_init, which will be invoked soon. This is necessary
because the function has not been compiled yet at this point. Remember that
every line of program code in C must end with a semicolon. The compiler will
not be able to compile the files successfully if you don’t follow this rule.
3. Next in the program is the line “void main (void) { ”. This is the beginning of the
main program routine, or function. The main function ends with a closing curly
brace, “}”.
4. The first line within this main function tells the processor to run the hardware
initialization routine, MCU_init.c. If you’re curious, double click that file name
in the project tree on the left under the folder “Generated Code”. All of the
MCU_init.c code was generated by the Device Initialization tool and would have
to be generated by hand if that tool did not exist!
5. In main.c, find the line that contains the text /* include your code here */. This is
called a comment, which is purely for human benefit and will be ignored by the
compiler. There are two types of comments used in C as shown in these two
examples:
533577557
Page 26 of 35
// This is a comment. Double slashes tell the compiler to ignore
// any text following the slashes on that one line only.
/* This slash-and-asterisk type of comment may cross over multiple lines
because the compiler treats everything within the opening and closing slashand-asterisk comment symbols as comments rather than executable code*/
6.
Delete that “/* include your code here */” comment, then locate the line “for(;;)
{”. This instruction defines the beginning of an infinite loop. Immediately
following that line, insert the following lines of text, which are actual program
code:
if(!PTAD_PTAD1)
PTAD_PTAD4 = !PTAD_PTAD4;
// switch SW0 pressed?
// yes. Reverse the state of LED1
The whole purpose of this little program, as the comments show, is to reverse the
state of LED1 each time SW0 is detected as being pressed – on, off, on, off, etc.
The exclamation point basically says “take the inverse or opposite”.
Recall that switch SW0 is connected to input PTAD_PTAD1 and LED1 is
connected to PTAD_PTAD4. The first line reads if(!PTAD_PTAD1). This means
“if Port A Data Bit 1 is not on” and determines whether the next line of code will
execute or not. If the parenthetical condition is true (i.e., if the pushbutton is
pressed), then PTAD_PTAD4 = !PTAD_PTAD4; will run. If the SW0 button is not
pressed, the “if” condition is false and the PTAD_PTAD4 line will be skipped
over.
You may wonder why pressing the button makes the inverse of the input become
true (input PTAD_PTAD1 = zero or logical FALSE if the button is pressed). If
you look at the schematic, you’ll see that the switch is tied to ground and so it
pulls the input low when it is pressed. Also, pullup resistor R103 pulls the input
high when the button is not pressed. Therefore, !PTAD_PTAD1 is true when the
button is pressed.
Now let’s take a closer look at the PTAD_PTAD4 = !PTAD_PTAD4; statement. This
says “make output PTAD_PTAD4 equal to its inverse”, which reverses the state
of the output bit. So, pressing the button reverses the LED state.
7. Select from the menu Project > Make (or F7 or this little icon:
). This will
compile the project files. No error messages should appear at this time.
Optional: To create an error condition and see how the compiler responds, remove
one of the semicolons in main.c and recompile the project.
8. Select Project > Debug (or F5 or green right arrow icon). Note: Selecting Debug
will automatically compile the project, so step #7 above was not really necessary,
but was included for training purposes.
533577557
Page 27 of 35
9. In the MCU Configuration dialog window that pops up, select Hardware Model
DEMO9RS08KA2 and click OK. This will send your Hello World program to
the microcontroller on the demo board. The term for this is “downloading”.
10. The True-Time Simulator and Real-Time Debugger tool should now open in a
new window. This tool is basically a panel from which to control and monitor
operation of the microcontroller. Once the program download is complete, look
at the toolbar and find the Run button, which is a green right arrow icon. Click
this icon or press the F5 button to start the program execution.
11. Notice that the green Run button icon has become grayed out, indicating that the
program is running. If it has not grayed-out, again click it or press F5.
12. The program should now be running. To test it, press and release the SW0
pushbutton repeatedly while watching LED1. Note that LED1 seems to dim
while SW0 is pressed, then when SW0 is released, LED1 may be either off or on
randomly. LED1 is actually blinking on and off while SW0 is held, but much
more quickly than the human eye can detect. The program isn’t quite right yet, so
in the following steps you’ll modify it.
Modifying the Program to Slow Down the LED1 Blink Rate
1. Close the debugger tool and edit the main.c file in the CodeWarrior IDE.
2. Modify your existing program (use copy & paste from this document if you
prefer) to look like this, with changes shown in bold text and pointed out with left
angle brackets:
#include <hidef.h> /* for EnableInterrupts macro */
#include "derivative.h" /* include peripheral declarations */
void MCU_init(void); /* Device initialization function declaration */
void main(void) {
int LoopCount = 0; // Declare and zero new integer variable
MCU_init(); /* call Device Initialization */
for(;;) {
for(LoopCount=0;LoopCount < 10000; LoopCount++); // delay here
if(!PTAD_PTAD1)
// switch SW0 pressed?
PTAD_PTAD4 = ~PTAD_PTAD4;
// yes. Reverse the state of LED1
} /* loop forever */
/* please make sure that you never leave main */
}
3.
Download and retest your modified program. Note that it may not yet be perfect,
but it works much better now and that LED1 on the development board changes
state each time SW0 is pressed. Also notice that LED1 blinks if SW0 is held
down continuously. Why?
533577557
Page 28 of 35
This program is not quite perfect yet, but it still works well enough for this example.
The LED1 state change is not 100% predictable, but more code could be added to make
it work better. Let’s just keep it simple at this point and enjoy the example for what it is.
4. Modify and test your program again by replacing the “LoopCount < 10000” with
each of the following to see which value works best:
a. “LoopCount < 32767”
b. “LoopCount < 1000”
c. “LoopCount < 100”
These program additions work as follows. First, the new integer variable “LoopCount” is
declared (i.e., created) and initialized or assigned a value zero here:
int LoopCount = 0;
Several important notes about declaring variables:
1. The syntax is very important and must include the data type (“int” for integer in
this example), variable name (e.g., LoopCount), and the ending semicolon. The
initialization (“ = 0 ”) sets the variable equal to some value (zero in this case).
Declarations do not need to include initialization, but many programmers prefer to
always initialize variables at the same time they are declared because this will
avoid certain programming problems later.
2. Any variable declarations must precede any executable code in a function. Notice
that the LoopCount declaration precedes the call to the MCU_init function within
the main function. The order of these lines may not be reversed or the compile
will fail. Try it right now if you’d like.
3. It is necessary to declare a variable before it is used in a program. This new
LoopCount variable is used in the main routine and therefore it needed to be
declared first.
The new line “for(LoopCount=0;LoopCount < 10000; LoopCount++); // delay here” was
added to slow down the program. The “for” instruction works this way:
1. LoopCount=0 sets that variable to an initial value of zero,
2. LoopCount < 10000 checks the value of the variable. If it is less than the target
value (10000), then the next instruction(s) following the for instruction will be
executed. In this case, the for instruction is followed by a semicolon rather than
some instruction to be looped, so this loop does nothing but waste time. When
LoopCount reaches 10000, the processor exits the loop and continues program
execution at the next line following the for loop.
3. LoopCount++ simply increments the LoopCount value by one after each loop is
executed.
4. The net result is that LoopCount starts at zero, counts up to 10000, then the loop
instruction is finished and the program continues.
533577557
Page 29 of 35
Debug Tools: Monitoring, I/O, Breakpoints, and Other Neat Stuff
Monitoring the Program & I/O
1. Press F5 to download and debug the latest version of your Hello World test
program.
2. In the Debugger window, notice the upper left panel is labeled Source and
currently contains the main.c program source code.
3. The panel below that panel is labeled Procedure and is sometimes referred to as
the Call Stack. This panel displays the function currently being executed at the
top of the list and then the path it took to get there. Hold that thought and then
direct your attention back to the panel containing main.c. Press the F11 button
(single step) once. The highlighting in main.c should have moved forward in the
instruction list, indicating that the next instruction to be executed is “MCU_init
();”, which is a “call” to function MCU_init. A call is the same as a JUMP
SUBROUTINE or GOSUB in other programming languages. Think of MCU_init
as a subroutine that runs only once when the uC first begins program execution.
4. Press F11 again and notice how the Source and Procedure panels both change.
The uC is now executing the MCU_init function.
5. Press F11 a few more times, noticing the changes in the Source panel. Also, if
you’re curious about assembly language and register-level debugging, notice the
changes in the Assembly and Register panels.
6. Press Shift + F11 to step out of the current function (MCU_init) and back to the
calling function (main).
7. If the Data:2 panel in the lower left is not currently displaying the LoopCount
variable, right click anywhere in that panel, select Add Expression, and enter
LoopCount. Spell it exactly that way since C is case sensitive. The new variable
should then display in the Data:2 panel.
8. Press the F5 button to put the uC into Run mode rather than single step mode.
The LoopCount value may or may not be visibly changing, depending on how
your PC is set up. This value is actually changing constantly, but the debugger’s
default setting is to update the displayed value of the variable only when the
program stops. Verify by watching the LoopCount value and pressing F5, F6, F5,
F6 a few times to start and stop the uC. Verify that the toolbar Run button (green
right arrow) is changing colors as you go from Run mode to Stop mode.
9. If the uC program is not running, press F5 to start the execution again. Right
mouse click anywhere within the Data:2 panel and select Mode > Periodical,
Rate: 1. This will update the displayed value every 100 mS.
10. In the Data:1 panel, change the Mode to Periodical with an update rate of 100 mS
using the same method as in the Data:2 panel.
11. Expand the _PTAD and Bits areas in Data:1. Watch the PTAD1 line while
repeatedly pressing and releasing button SW0. Notice the value changing from 1
to 0 and back again. Notice also that the number turns red briefly the first time it
has changed state since the last display update. This is a nice feature. Also watch
the PTAD4 entry and notice that it is changing to match the state of LED1.
533577557
Page 30 of 35
Using Breakpoints
1. Press F6 to stop the uC program execution, and then press Ctrl+R to reset the
target (the development board).
2. If the Source panel is not currently displaying the main.c file, right click that
panel and select Open Source File, main.c, OK.
3. Locate the text “LoopCount < 32767;” and right click anywhere on it, then select
Set Breakpoint. A red breakpoint symbol should appear to the left of that
program code.
4. Press F5 to run the program and notice that the lower right Command panel
indicates “STARTED RUNNING Breakpoint”. F5 started the program, it was
running, and then it encountered a breakpoint and stopped. The Source and
Assembly panels indicate the stop point: right at the breakpoint we just set, which
is in the middle of a for instruction that is looping and incrementing LoopCount.
5. Notice the value of the LoopCount variable in the Data:2 panel. Press F11
repeatedly and watch the value increasing. If the value does not change, verify
that you still have the update mode set correctly (right mouse click anywhere
within the Data:2 panel and select Mode > Periodical, Rate: 1).
6. Optional: If you are curious about the assembly language code, watch the
Assembly panel while repeatedly pressing Ctrl+F11 to step through each
assembly language instruction. Also, check out the right click options in the
Assembly panel.
7. You’ve just used an unconditional breakpoint. Now we’ll set a conditional
breakpoint. Ctrl+R to reset the uC again, then open main.c in the Source panel.
Right click anywhere in Source and select Show Breakpoints. This will open a
window in which you can set certain conditions that must be satisfied before the
breakpoint will cause the program to break. In the Condition field, enter the
condition “LoopCount==14” (this says “break at this point when LoopCount is
equal to 14”). Click OK, OK.
8. Press F5 to Run and watch the Source, Data:2, and Command panels.
There are a number of other very nice features in the debugger tool that you may wish to
explore and learn on your own. Have fun!
533577557
Page 31 of 35
Stand-alone uC Circuit Example:
Minimum Circuit Required for the Hello World Example Program
Here is the minimum circuit required for running the Hello World program with a standalone RS08 microcontroller:
If one were to breadboard and test the above circuit, they would have to keep in mind the
following key points:
1. Input PTA1 MUST be set to pullup. This would be done by using the Device
Initialization tool mentioned in the beginning of this lab.
2. Capacitor C1 may not be required in all situations, but the uC may not go into
Run mode without it. More information about operating modes may be found in
the uC data sheet.
3. R1 is sized to limit PTA4 current to a level that will not overload and damage the
uC chip. Do not change the value of R1.
4. It would make sense to develop and test the program on the demo board first.
You would not have the option to test and debug while it is plugged into the
breadboard. It is possible to connect to the uC for debugging, but that connection
is beyond the scope of this lab.
5. Care should be exercised when removing the uC chip from the demo board and
breadboard since the pins are very delicate, plus the chips are static sensitive.
533577557
Page 32 of 35
Links to Executable Programming Examples Provided with this
Training Material (CD or unzipped directory)
Place the RS08 chip back into the demo board and go through the following examples as
you desire.
1. Keyboard Interrupt with STOP (low power mode) Instruction – contains C and
Assembly mixed
This program demonstrates the use of low power “stop” mode and “keyboard
interrupts”, the latter of which basically allows the chip to detect active input
signals.
Open the device initialization tool and notice that some of the blocks are aqua,
indicating that they have been changed from their original settings. Specifically,
the COP feature is turned off, keyboard interrupt requests are enabled, and the
KBIP1 feature is set active for pin 7 to detect low or falling edges. With this
setup, any time pin 7 is pulled low by external circuitry (SW0 on the demo
board), a keyboard interrupt is generated. Hold that thought.
The first thing done is the main function is that the uC is put into low power stop
mode. This may be useful for applications where power consumption must be
minimized, such as battery powered systems. The uC will stay in stop mode until
SW0 is pressed, at which time a keyboard interrupt is generated (because the
KBIP1 input is seen going low) and the uC is automatically taken out of stop
mode and into run mode. The uC then continues running the program after the
STOP command, toggling the output connected to LED1, acknowledging the
interrupt, and then going into stop mode again.
2. Boolean Logic Demo
In this program example, some simple Boolean logic is demonstrated (NOR,
AND, OR functions, etc.). Also, parameter passing with a function is
demonstrated in the NOR function. Nothing fancy is happening with the device
initialization.
3. Chasing Lights Pulse Width Modulation (PWM) Demo
This demo uses the built-in timer module to generate a 34 uS timebase. See
MTIM settings in Device Initialization. Also, KBIP1 is set up again to monitor
the input tied to SW0. This program makes plentiful use of functions and
parameter passing to alternately dim and brighten the lights. This dimming effect
is accomplished through PWM, which basically blinks the LEDs very fast and
controls apparent brightness by varying the duty cycle (percentage of entire cycle
during which LED is on as compared to off).
Pay special attention to the following lines in which the program waits until the
next 34 uS time tick:
while( ! SIP1_MTIM); // wait for overflow interrupt flag from timer
MTIMSC_TRST = 1; // reset timer and acknowledge the interrupt
Also pay attention to this code, which checks to see if the user has pressed the
input button recently:
// look for user-requested cycle change
533577557
Page 33 of 35
if(SIP1_KBI) {
4. Array Size Testing
This example shows how to work with multi-dimensional arrays, a powerful and
commonly used C construct.
In addition, it demonstrates something called “compiler directives” – the
commands beginning with a # sign. If you do not understand these commands,
ask your lab instructor to clarify.
Finally, the program shows how to determine uC memory usage and how constant
arrays and variable arrays are stored in different memory areas. This could be
useful to know when conserving memory is important. Read and follow the
comment instructions provided in the program.
5. Enumeration Demo
This program shows several examples of enumeration, which is a programming
technique for assigning integer values to some words such as LED names &
statuses and musical notes. Since there is no speaker attached, you cannot hear
the musical notes.
6. Comparator Demo
This program will not work with the demo board because there is no variable
analog voltage present. However, following the device initialization and program
logic demonstrates how the analog input comparator could be used. Note that
“SIP1_ACMP” is a bit that gets set when the analog compare condition is true,
that is, the positive compare input is greater than the negative compare input.
7. Real Time Clock (RTC) Interrupt Demo
Look at the device initialization and main function to see how real time clock
interrupts are used. Basically, a clock on the uC running in the background sets
bit “SIP1_RTI” high every 131.072 mS. This is used to blink LED3
approximately once per second and LED2 approximately 8 times per second.
533577557
Page 34 of 35
Additional Resources
Documents Provided with this Training Material (CD or unzipped
directory)
Freescale RS08-related:
DEMO9RS08KA2 Development Board User’s Manual
DEMO9RS08KA2 Development Board Schematic
RS08KA1 & KA2 Microcontroller Data Sheet
RS08 Core Reference Manual (assembly language instruction set, etc.)
RS08 Assembly Language Demos & Quick Reference User's Guide
Application Note on RS Data Structures (not too intense)
C Language-related:
Freescale’s Learn_Programming_with_C
C Language Keywords: C Language Keywords.mht
Online Resources
Review of bits, bytes, etc.: http://www.learn-c.com/data_lines.htm
Tutorial on C programming with microcontrollers: http://www.learn-c.com/alltoget.htm
Online C language reference: http://ccs.ucsd.edu/c/
C Programming:
http://www.imada.sdu.dk/~svalle/courses/dm14-2005/mirror/c/ccourse.html
C Language FAQs: http://c-faq.com/index.html
Developing Embedded Software in C:
http://users.ece.utexas.edu/~valvano/embed/toc1.htm
The GNU C Library - Table of Contents :
http://www.ia.pw.edu.pl/~wujek/dokumentacja/gnu/libc/libc_toc.html
C Reference, Searchable and quite good: http://www.sysprog.net/cplus.html
Free IDE/C compiler for the mid-to-low end Freescale microcontrollers:
www.freescale.com and search for “CWX-HC08-SE”
Support
CodeWarrior website: www.freescale.com/codewarrior
CodeWarrior email support: cw_support@freescale.com
General support for entire Freescale product line: www.freescale.com/support
Purchasing Your Own Demo Kits and Microcontrollers
Various vendors sell microcontrollers and demo kits. The best price ($10 + S&H) for the
DEMO9RS08KA2 may be found here:
www.avnet.com and search for “DEMO9RS08KA2”.
533577557
Page 35 of 35
Download