EEE305 Microcontroller Systems

Download Report

Transcript EEE305 Microcontroller Systems

EEE502 EmbeddedSystems
Introduction to C (L1)
Teaching resources on at www.eej.ulst.ac.uk
My office 5B18, telephone 028 90 366364
My email [email protected]
Computers: hardware and Software



Understanding what computers, microcontrollers and microprocessors can do
What the hardware of these systems are like
What the software (firmware) of these systems
is like

How to make the software

How to make the hardware
Software
How to average 10 numbers?





Get the first number
Add the second number to it
Add the next number to it
Continue until you have added 10 numbers
Divide the total by 10.
Programming

How to average 10 numbers?





Start
Clear TOTAL and Clear COUNT
Get the first number
Add the second number to it
Add the next number to the
sum
Continue until you have added
10 numbers
Divide the total by 10.
Note the slight difference in the
methods. The computer is good at
repetitive stuff so it is good to
make the first step the same as all
The other steps, so the first
number is not treated differently to
Subsequent numbers.
Get INPUT
Add input to TOTAL
Add 1 to COUNT
Is
Total
=10
?
NO
Divide TOTAL by 10
Present the ANSWER
Stop
Star
t
Clear TOTAL and Clear COUNT
Get NUMBER
Add NUMBER to TOTAL
Add 1 to COUNT
Is
Total
=10
?
NO
/******* comments can be made in two ways ***/
#include <stdio.h>
// we use scanf and printf
void main(void)
{
// two slashes produce a comment
int number; // used for input
int total=0; // used for running total
int count=0; /* number of numbers input */
float answer; // compiler must know the type
// of ALL variables in a program
do{
scanf(“%d”,&number); complicated way to I/p
total=total+number;
// '='sign means “will become equal to”
count =count+1; // or use count++
}while(count<10);
answer = total/10; // better to use /count!
Divide TOTAL by 10
printf(“\nThe answer is %f “,answer);
Present the ANSWER
Sto
p
}//--end of main –//
Printf and Scanf – standard I/o library routines –
not in the C language but supplied in libraries with
each compiler often not needed in true embedded
systems
The quoted strings passed to printf can contain three things
Ordinary text, escaped characters and format placeholders.
The backslash followed by a character or characters e.g \n This
is known as an escape sequence, and in this case it causes the
printf function to take a newline after the line of text has been
printed.
The other new device is the %f This is called a place holder
and is used to indicate where the value of a particular variable
should be printed. The fact that an f is used indicates that the
variable is expected to be a floating point number. The values to
be printed, or names of the variables to be printed, follow the
string in a comma-separated list as shown.
Escape sequences
Format Placeholders
Microcontroller

e.g a PIC microcontroller from Microchip

Many versions! (check out their website)

Our boards have 16F877A – 40 pin chip (or PIC32MX256F128D)

5 ports - Port A has 6 bits, B,C,D are 8 bit and E is 3

Each pin can be input or output (just about)

Outputs are roughly 0V or 5V, up to 25mA (typically 3-4 volts)

Has timers built in – can work off system clock

Has an 10 bit ADC – Analogue to Digital convertor on PORTA, but you can
choose to use it or ordinary i/o

Has serial input and output on RC6 and RC7.

Has chip interfacing capabilies on other PORTC lines IIC or SPI protocols.

The PIC32MX256F128C has different capacbilities – including more
memory, we will switch to it in week 9 to experiment with a RTOS
Hardware of PIC supported by Software





There are 4 or 5 C compilers for the PIC; made by CCS inc, or
the HiTec Corporation
HiTec C provides special keywords to manipulate hardware
features as well as a C library of useful functions. It was
recently bought over by microchip and they have rebadged the
compilers as the C8, C16 and C32 products.
Microchip have evolved these into the XC8, XC16 and XC32
compilers, introduced new ways of doing some things but have
kept (for now) compatibility
The Standard C language has only 35 keywords and three or
four basic data types.
Although it also has standard libraries – to calculate cosine for
example or provide input and output through a keyboard and
screen(console) - or a serial interface to a keyboard and
screen.
The Hitec or XC compilers
Star
t
Another program
Get TEMPERATURE


Get the temperature
If it is too high (>25)


Switch heater on
If it is too low (<22)


Switch heater off
Wait a bit

Do it again
NO
NO
Is it
greater than
25?
Is it
greater than
25?
YES
YES
Switch
Heater
ON
Delay_milli_seconds(10)
Switch
Heater
ON
#include <htc.h>
#define _XTAL_FREQ 20000000
// line above needed to make __delay calls work
__CONFIG(WDTDIS & PWRTDIS & BORDIS & UNPROTECT);
//line above needed to set “fuses” in a PIC
Star
t
void main (void)
{
unsigned short int temperature;
Get TEMPERATURE
NO
NO
Is it
greater than
25?
Is it
greater than
22?
YES
Delay_milli_seconds(10)
=
=
=
=
0x00; //
0xFF; // set PORTC to be I/p
0x00;
0xFE;
do
{
Temperature = PORTC;
// assuming PORTC wired up
YES
Switch
Heater
ON
PORTC
TRISC
PORTB
TRISB
Switch
Heater
ON
if(temperature > 25)
{
RB0=1; //predefined in Hitec C
}
// PORTB bit 0
else
{
if(temperature < 22)
{
RB0=0;
}
}
__delay_ms(10); //supplied library
}while(1);
}//-- end of main – never reached!--//
Embedded C vs Ordinary C
Embedded C (running in a single chip microcomputer)
•
•
•
has few bits of input and a few bits of output as a minimum
Perhaps uses timers and special built in peripherals such as an ADC, serial port,
I2C, SPI, USB, PWM outputs.
Might not use “console i/o” (after debugging) and does not have access to an OS.
Ordinary C runs on a full computer
•
•
has access to a disk drive and operating system resources
has access to a sophisticated screen for output and a keyboard and mouse for
input.
• May use “text console” or access the operating system resources – the windowing
system and the various OS library calls to move about a window.
• Interacts with a user in the normal way
Learning C
Simple language of 35 Keywords
Simple structure, can be a single file containing a
collection of functions, it will have a single
function (named main()) and this might call other
functions.
A function is a section of code that does a single
simple thing; it has a defined entry point – a
start, a defined list of incoming data to work on
and a mechanism to send its results
somewhere. (unless it is a beep() function)
The C language
As well as functions you write there are library functions. You can
also “include” other files that contain other functions.
Good to partition or split big problems into a number of small
functions. Top down design…
As well as “WHAT NEEDS DONE” you also need to think about
“WHAT DATA IS BEING MANIPULATED”
(If you focus on this then you have become Object Orientated) –
There is a version of C that is suitable for OOPs programming –
C++
Algorithms + Data Structures =
Programs
Why Use C?
C is a powerful and flexible language.
C is a popular language preferred by professional programmers. As a result, a
wide variety of C compilers and helpful accessories are available.
C is a portable language. Portable means that a C program written for one computer
system (an IBM PC, for example) can be compiled and run on another system
(a DEC VAX system, perhaps) with little or no modification
C is a language of few words, containing only a handful of terms, called keywords,
which serve as the base on which the language’s functionality is built.
C is modular. C code can (and should) be written in routines called functions.
These functions can be reused in other applications or programs. By passing pieces
of information to the functions, you can create useful, reusable code.
Making Programs
Several tool paths exist;
1. Edit a file, give it a .c extension, e.g test.c
2. Compile it, this creates test.obj
3. Link to any previously created .obj files
4. Link it to the standard library (to “bring in”
printf.obj)
5. This creates test.exe
6. Run test.exe.
Making Programs
In practice it is common to use an IDE to automate these steps and
also manage the source files.
An IDE will have an editor window, a project navigation window, a
function list window and a single button/command to create and
run test.exe.
Visual C++ can create C based console programs, the IDE has a
“make” command [F9]
And a run in a window command.
In practice you should add a line to pause the program so you can
read the screen before the window exits.
In the embedded world, microchip provide MPLAB, with similar
capabilities, and also a device programmer/downloader.
Your First C Program
C is case sensitive, C treats all “white space” the same
(spaces, tabs, newlines) unless inside double quotes.
Most C statements end in a semicolon.
#include <stdio.h>
int main(void) {
int i;
printf(“Hello, World!\n”);
scanf(“%d”,&i);
return 0;
}
Line 1 tells the compiler where to find out about
functions that you use and didn’t write yourself (printf)
Line 2 is the start of a block of code – known as a
function. This function is called main, it is passed
nothing and returns a number
Line 3 tells the compiler to allocate a bit of space for a
“variable” that will be a whole number and will be
referred to as i .
Line 4 calls the special library function called printf. The
documentation for printf describes what is passed to it,
what it does and what if anything it returns to the caller.
Line 5 scans the keyboard and awaits input
Line 6 sends the number zero back to whoever called
main, in this case it is the OS.
Line 7 finishes the body of the main function. Most
“blocks” of code have start and end curly brackets
Exercises: start up visual Studio or Codebase, start a
project of type C and windows CONSOLE based.
Enter and compile the following program. What does this program do?
#include <stdio.h>
int radius, area;
int main( void ) {
printf( “Enter radius (i.e. 10): “ );
scanf( “%d”, &radius );
area = (int) (3.14159 * radius * radius);
printf( “\n\nArea = %d\n”, area );
return 0;
}
Enter and compile the following program. What does this program do?
#include <stdio.h>
int x, y;
int main( void ){
for ( x = 0; x < 10; x++, printf( “\n” ) )
for ( y = 0; y < 10; y++ )
printf( “X” );
return 0;
}
Note: Variables declared
outside a function are known
and accessible anywhere in
the file.
Variables declared inside a
function are only visible,
known and accessible inside
the function.
Although you can pass a
variables value to a function
by calling it from within your
own function (that is how
printf knows the value to print)
It is even possible to pass a
reference to a variable, rather
than its value, this is how
scanf works
Exercises: programs with bugs!
BUG BUSTER: The following program has a problem. Enter it in your editor and
compile it. Which lines generate error messages?
#include <stdio.h>
int main( void );
{
printf( “Keep looking!” );
printf( “You\’ll find it!\n” );
return 0;
}
BUG BUSTER: The following program has a problem. Enter it in your editor and
compile it. Which lines generate problems?
#include <stdio.h>
int main( void )
{
printf( “This is a program with a “ );
do_it( “problem!”);
return 0;
}
Draw a flowchart , then write a
program
Find the average of ten numbers
Input your coursework and exam marks for your
semester one subjects and print out your
semester average.
NB; %f is used for floating point in printf’s format
specifier strings.
There are clues in the earlier slides.
Variables in C
A variable is a named data storage location in your computer’s
memory. By using a variable’s name in your program, you are, in
effect, referring to the data stored there.
Variable names can contain a-z, A-Z, digits and the underscore,
the first character must not be a number or one of the C keywords.
Variable names should be meaningful – self documenting code.
The computer works out where to store each variable, what
address to place it and what size (how many bytes to allocate to
store the variable contents.
We must give the compiler clues as to how many bytes – the type
of data to be stored in each variable
Variable sizes in bytes for a typical PC compiler, NB embedded compilers often are
differerent!!!
Although compilers differ; what is always true
To give a compiler information about a variable you
must “declare” your intentions
// to declare a variable, give a type then the variable name (and a semicolon)
int i; /* often worth adding a comment here!... i is used as a loop counter … */
char ch;
Also, you can have multiple declarations within a statement but it makes commenting harder.
int i,j,k;
Also you can initialise a variable when you declare it.
int total=0;
float sum=0.0; // note how you can specify a floating point constant.
C builtin data types
char and int
Along with short, long and unsigned and signed versions
float and double. Some compilers allow long long
There is no builtin “string” data type in C, but library
functions have been written to manipulate arrays of
characters which have an extra null character as
terminators. The compiler will allow use of double
quotes to form a string constant – it is held internally as
an array of characters with a ‘\0’ stored after the last
character.
You can define your own types
The ANSI standard uses this
By including a stdint library in your code you can
access special defined types
int8_t
uint8_t
int16_t
uint16_t
Add the line #include <stdint.h> to your code
before using these
Numbers, characters and strings
Numbers can be whole numbers or floating point numbers of different sizes; signed or
unsigned. For example 42, or 42.0. We can also use HEX numeric constants by using a
0x prefix so 0x42 is actually 66 in decimal (4*16+2)
Programs often deal with text. There is only limited support for this in the actual C
language, though there are many string functions available, you must #include <string.h>
to access them
The data type char is used to hold a single character – actually it just holds an 8 bit
number.
The compiler will convert a single character to its 8 bit numeric value – by using SINGLE
quotes. Thus if i is declared as a char, you can say i = ’a’; and i ends up with the value
65.
The character set is known as the ASCII character set.
A string does not exist in C, we use arrays instead. An array is a collection of data
objects of the same type and given a single collective name. Thus an array of characters
is considered a string and there are a dozen library functions written to use an array of
characters, with the VERY IMPORTANT CONVENTION that an extra byte is out at the
end of the array that contains zero.
The ASCII character set; in binary the symbol ‘A’ is 100
0001 or 0x41 or 65 in decimal
Text strings
Whilst it is true no string variables exist in C, null terminated char
arrays are treated as strings by the functions in the string library.
Also the compiler will convert string constants to a null terminated
char array in memory; this uses the DOUBLE QUOTES to tell the
compiler what to do.
You have already seen this in the parameters passed to printf (and
scanf)
Thus printf(“This is a string”); will work
You cannot assign text to a string or add strings together in C –
without using specially written string functions strcpy() and strcat()
Declaring arrays and strings
//C uses square brackets with arrays. To declare
int mydata[6]; // the compiler sets aside room for 6 ints
char me[6]; // 6 bytes, 5 for chars and one for the zero terminator
// To declare and initialise, the compiler helps a bit here
int mydata[] = {1,2,99,42,55,77}; // you can keep the [6] if you want
char me[] = “james”; // the compiler stores 6 bytes ‘j’,’a’,’m’,’e’,’s’,’\0’
To use an array element as a single data value, use the square
brackets and an index number. x = mydata[2]; makes x=99
NOTE indexing starts at zero mydata[0], mydata[1] then mydata[2] –
the third element of the array
Assignment = a simple statement
You have seen simple assignments; in C these
use the assignment operator, the equal sign.
In the assignment statement values move from
the righthand side to the lefthand side of the
equal sign.
Thus x=10; causes 10 to move into the variable x.
In C we use the double equal combination for an
equality test, no data moves!
If(x==10)printf(“nothing moved”);
Be careful you see the difference between the
assignment operator and the equality test
The IF statement (two versions – the single
staement and the block of startement version)
If (conditional test is true)do this-only if it was true;
… always do this…
If (conditional test is true){
do this-only if it was true;
do that-only if it was true;
}
… now do this (always)
I recommend you always put brackets in – even in the single
statement version – at least when you start C it reduces errors
If (conditional test is true){do this-only if it was true;}
… always do this…
If statements
If (conditional test is true)do this-only if it was true;
… always do this…
e.g, actual C
If(count==10)average=sum/count;
If(count==10) {
average=sum/count;
printf(“average of %d numbers is %f\n”, count, average);
}
// There is a lot going on here, note the use of two format specifiers and one //
escape character in the printf function parameter list.
The other conditional tests are
!=
<
>
<=
>=
If – else statements
If(count<10){
sum=sum+mydata[count];
count=count+1;
}else{
printf(“average is %f\n”,sum/count);
return 0;
}
// Note NO semicolon
// If and if-else are compound
// statements. Only simple
// statements end in
// semicolons
// program defensively – keep your logic flow simple, easy to understand
You can also have nested if and multiple elses – too awkward…
The following code sets a variable c equal to the greater of two
variables a and b, or 0 if a and b are equal.
if(a > b){
c = a;
}
else if(b > a){
c = b;
}
else{
c = 0;
}
Too error prone, find a way to express your code more simply.
(switch-case statements)
The Conditional Expression
You do not often need this, I usually look up the syntax if I am going to use it, it
can give you concise code.
A conditional expression is a way to set values conditionally in a more shorthand
fashion than If Else. The syntax is:
(/* logical expression goes here */) ? (/* if nonzero (true) */) : (/* if 0 (false) */)
The logical expression is evaluated. If it is nonzero (true), the overall conditional
expression evaluates to the expression placed between the ? and :, otherwise, it
evaluates to the expression after
the :
Therefore, the above example (changing its function slightly such that c is set to
b when a and b are equal) becomes:
c = (a > b) ? a : b;
So c = a if the test is true or c = b if the test is false
The Switch Case statement
switch (grade)
{
case 1:
printf("A\n");
break;
case 2:
printf("B\n");
break;
case 3:
printf("C\n");
break;
case ‘q’:
case ‘Q’:
printf("D\n");
break;
default:
printf("F\n");
break;
}
The SwitchCase construct takes a variable, usually an int,
placed after switch, and compares it to the value following
the case keyword, the value can be a char constant ‘x’
If the variable is equal to the value specified after case, the
construct "activates", or begins executing the code after the
case statement. Once the construct has "activated", there
will be no further evaluation of cases.
SwitchCase is syntactically "weird" in that no braces are
required for code associated with a case. Very important:
Typically, the last statement for each case is a break
statement. This causes program execution to jump to the
statement following the closing bracket of the switch
statement, which is what one would normally want to
happen.
However if the break statement is omitted,
program execution continues with the first line of the next
case, if any. This is called a fallthrough.
Loops: there are 3 of these; the FOR loop, the
WHILE loop and the DO loop
int a=1;
int a=1;
while(a<100) {
printf("a is %d \n",a);
a = a*2;
}
// loop is done zero or
// more times.
// Note no semicolons
// the keywords break
// and continue can be
// used inside while
// loops
do{
printf("a is %d \n",a);
a = a*2;
}while(a<100); // note semicolon!
// loop is done once or more times
// again break can be used to exit
// to the statement below the loop
// prematurely and continue can
// be used to jump back up to the
// do (start of loop)
The for loop is handiest when we know how many times around a
loop we want, e.g to execute a loop 100 times. However you can
use it in a variety of ways.
int ix;
for(ix = 1; ix <= 100; ix = ix +1){
// or use ix++ to save typing.
printf("%d ", ix);
}
// the three parts of the FOR loop, initialisation executed once on
// entering the loop the test, done at the TOP of the loop at
// the first } and the loop end statement, the increment done at the
// END of the loop, at the last }
// note that ix++ is shorthand for ix=ix+1, you can also use -- as a //
decrement operator. These can be prepended or appended
// to the variable. i++ or ++i. This sometimes matters. E.g
i = 5;
x = i++; // now x is 5 and I is 6
Functions
Things to know;
How to declare them e.g float sqr(double); or one you have seen
int main(void); // this declaration is in stdio.h! done for us!
// note the semicolon is vital here – to let the compiler see which is
//the declaration and which is the body of the function
How to use them – pass them data and get results
x = sqr(y);
// pass it a number, the VALUE of y
z = sqr(16);
p = sqr(4*y + x); // pass it a number, the value of the expression
How to write them. Note NO SEMICOLON below
float sqr(double dd){ //dd is not a local variable that takes the
return(dd*dd);
// value of the incoming number
}
Directives; not really part of the compiler – the file
is preprocessed before being compiled
#include <string.h> // angle brackets = system
#include part1.c
// no brackets = user folder
Note no semicolons!, the files are just inserted
#define PI 3.1428 // a simple text subsitution
Convention is to use UPPER CASE. (used a lot)
#ifndef GOTLCD
#define “putch(“
#endif
“putch(LCD,”
So if GOTLCD has been previously #defined
Then a text substitution will be carried out
#pragma Some none standard feature that your compiler allows
A different compiler will ignore a #pragma line if it doesn’t
understand it.
Summary
You have seen.
• Basic data types
• Arrays and strings
• simple statements such as assignment expression
• Conditional expression
• Compound statements; if, while, do, for, switch,case, break,
continue
• Function usage
• Preprocessor directives
Still to see;
• casts,
• accessing memory, (pointers)
• passing variable references into functions instead of values.
• Some more library functions, strings and files.
Read the 129 page “C_Programming__WikiBook.pdf” for next week