Experiment No. 3 Introduction to Microcontroller Programming

pleasanthopebrothersElectronics - Devices

Nov 2, 2013 (3 years and 7 months ago)

116 views



Universität Stuttgart

Institut für Automatisierungs
-

und Softwaretechnik

Pro
f. Dr.
-
Ing. Dr. h. c. P. Göhner











Laboratory Course

Industrial Automation




Experiment No
. 3


Introduction

t
o


Mic
rocontroller

P
rogrammi
n
g



Experiment Instructions


2

Introduction to Microcontroller Pr
ogramming

Content

1

Introduction

................................
................................
................................
..............................

4

1.1

Microcontrollers for Industrial Automa
tion

................................
................................
.......

4

1.2

The Content and Purpose of the Laboratory

................................
................................
.......

4

2

Microchip MPLAB IDE Development Environment

................................
...........................

5

2.1

Overview

................................
................................
................................
.............................

5

2.2

Setup New Proj
ect

................................
................................
................................
..............

6

2.3

Blend Project Manager

................................
................................
................................
.......

8

2.4

Setup New Source File

................................
................................
................................
.......

9

2.5

Configuration of the Microcontroller

................................
................................
...............

10

2.6

Microcontroller Programmin
g

................................
................................
..........................

11

2.6.1

Selection and Configuration of the Programmer

................................
....................

11

2.6.2

Compiling Program

................................
................................
................................

13

2.6.3

Loading the program onto the microcontroller

................................
......................

14

3

Microchip C30 Toolsuite and C programming language

................................
...................

16

3.1

General Advices

................................
................................
................................
................

16

3.2

Calculations

................................
................................
................................
......................

16

3.3

Logical Operators

................................
................................
................................
.............

17

3.4

Inc
rement / Decrement Operators

................................
................................
.....................

17

3.5

Numeric Values

................................
................................
................................
................

17

3.6

Data Type

................................
................................
................................
..........................

17

3.7

Variables

................................
................................
................................
...........................

17

3.8

Methods

................................
................................
................................
............................

18

3.8
.1

Declaration of a Method

................................
................................
.........................

18

3.8.2

Definition einer Methode

................................
................................
.......................

18

3.9

Branches

................................
................................
................................
...........................

19

3.9.1

if
-
statement

................................
................................
................................
.............

19

3.9.2

Switch
-
statement

................................
................................
................................
....

19

3.10

Loops

................................
................................
................................
................................

20

3.10.1

For
-
Loop

................................
................................
................................
.................

20

3.10.2

While
-
Loop

................................
................................
................................
............

21

3.11

Conversion of Variables to String

................................
................................
....................

21

3.12

Structures an
d Unions

................................
................................
................................
.......

22

3.12.1

Structures

................................
................................
................................
................

22

3.12.2

Unions

................................
................................
................................
....................

23

3.13

Support for programming the microcontroller

................................
................................
.

24

4

Experiment Hardware

................................
................................
................................
...........

25

4.1

Installation

................................
................................
................................
........................

26

4.1.1

Hardware Installation

................................
................................
.............................

26

Introduction to Microcontroller Programming


3


4.1.2

Software Installation

................................
................................
...............................

26

4.2

Start
-
Up

................................
................................
................................
.............................

26

4.2.1

Start
-
Up Ha
rdware

................................
................................
................................
..

26

4.2.2

Start
-
Up Software

................................
................................
................................
...

26

4.3

Overview Subsystem A

................................
................................
................................
.....

27

4.4

Overview Subsystem B

................................
................................
................................
.....

28

4.5

Pinout of the Microcontroller dsPIC30F4
011 (Subsystem A)

................................
..........

29

4.6

Pinout of the Microcontroller dsPIC30F4011 (Subsystem B)

................................
..........

30

5

Launching the Microcontroller (Part 1)

................................
................................
...............

31

5.1

Task

................................
................................
................................
................................
...

31

5.2

Overview of Microchip dsPIC30F4011

................................
................................
............

31

5.3

Setup I/O Ports and Control of PORT
-
LEDs

................................
................................
....

31

5.4

Timer Setup

................................
................................
................................
.......................

33

5.5

Control of the seven
-
segment display

................................
................................
...............

34

5.6

Preparation Exercises (Part 1)

................................
................................
...........................

36

5.7

Implementation Exercises (Part 1)

................................
................................
....................

38

6

Controlling the IAS Light Ticker Display (Part 2)

................................
..............................

40

6.1

Task

................................
................................
................................
................................
...

40

6.2

Design of the IAS Ticker Display

................................
................................
.....................

40

6.3

Structure of the Character Generator

................................
................................
................

42

6.4

Preparing Exercise (Part 2)

................................
................................
...............................

43

6.5

Implementat
ion Exercises (Part 2)

................................
................................
....................

43

7

Analysis of the RGB Colour Sensor and control of the RGB
-
LED
-
Panel (Part 3)

..........

44

7.1

Task

................................
................................
................................
................................
...

44

7.2

Hardware Description

................................
................................
................................
.......

44

7.2.1

How does the RGB Color Sensor work?

................................
................................

44

7.2.2

How does the RGB
-
LED
-
Panel work?

................................
................................
...

44

7.3

Software Describtion

................................
................................
................................
........

45

7.3.1

Use
-
Case
-
Diagram

................................
................................
................................
..

45

7.3.2

Sequence Diagram

................................
................................
................................
..

46

7.3.3

Software Components
................................
................................
.............................

47

7.4

Laboratory Execution

................................
................................
................................
........

52

7.4.1

Completing the main method

................................
................................
.................

52

7
.4.2

Completing the firstline method

................................
................................
.............

54

7.4.3

Completing the secondline methode
................................
................................
.......

54

7.4.4

Completing the interrupt service routine for timer 2/3

................................
...........

54

7.4.5

Completing th
e interrupt service routine for timer 4/5

................................
...........

54

7.5

Preparing Exercises (Part 3)

................................
................................
..............................

55

7.6

Implementation Exercises (Part 3)

................................
................................
....................

60


4

Introduction to Microcontroller Pr
ogramming

1

Introduction

1.1

Microcontrollers for Industri
al Automation

Microcontrollers are

high
-
integrated devices finding their

application

in

mass products.

They
present the

heart

of many household

appliances

such as

coffee machine
,
washing machine
,
televisions.

Mi
crocontrollers have

taken

their place a
lso
in

the automotive

industry
.
There are

used

in control devices

for ABS
, ESP, electric
window regulators,

audio systems and

much
more.

A

microcontroller combines

on a single chip

a standard

microprocessor (
or
even

more)
,
and
various

peripheral devices

such as
internal clock
,
interrupt controllers
, bus
interfaces
, analog
-
digital
converters
, etc.
In
industrial automation

microcontroller
s

work as an automat
ion

computer
on a chip which is integrated in products and systems
,

the so called embedded systems.

Depending

on

requirements

there
is a huge variety

of microcontrollers

on the market available

at

an extremely low

price.

The prices

vary

between

1


for 8
-
bit
microcontroller

that can

be used for
simple

control

tasks
,
up to

10€

for 32
-
bit
microcontroller

with DSP

core

for complex

signal

processing

tasks
.

1.2

The
Content and Purpose of the
Laboratory

The purpose of this
two
-
day
laboratory

is to teach stud
ents the basics
of

microcontroller
programming
in the C

programming language.
Participation

in the laboratory

is

also

possible

for
students without

experience

in

programming the

microcontroller.

It also offers

the students

with
good

prior knowledge
, the
ab
ility to

perform complex

programming tasks.

The laboratory

is

divided

into three

parts
.

The first part

of the laboratory

is to

focus on

the

start
-
up
of the microcontroller

and

its

peripherals
.
Based on simple

tasks
, the students should
gain an insight

into

the

operation

of the
microcontroller.

In the second

part of

the laboratory, the

control of

the IAS

light
ticker

is should be realized
.
This

part should demonstrate students

how

hardware

can

be controlled

by

a microcontroller.

In the third

part

of the

labo
ratory
, the

polling

of a

RGB

color sensor

and

true to original
reproduction

of the
detected

colors

on the RGB

LED panel

should be realized
.
Transmission of
all
relevant information is provided by a
n on
-
board L
CD display so that after the
laboratory

the
exp
eriment
setup

can
run

auto
matically

and without any connection to a
PC
. This point
s

out that
a microcont
roller can work completely
self
-
sufficiently
.


dsPIC30F401 by Microchip is used

as the microcontroller
.
To program

the microcontroller

the
development

e
nvironment

MPLAB

and

the C30

compiler

from

Microchip
are

used
.

The

first two

parts

are

to be done
on the first

afternoon

of the laboratory,
the third part

on the
second afternoon.

For a successful

participation

the labor
a
tory

must be

prepare
d

well
.
This in
cludes deep reading
of this instructions and the written elaboration of the preparing exercises before the experiment.
Results are to be recorded reasonably.

Introduction to Microcontroller Programming


5


2

Microchip
MPLAB IDE

Development Environment

2.1

Overview

MPLAB I
D
E
(Integrated Development Environment
) is a
free of cost

development environment
provided by the company Microchip to develop embedded systems using
PIC®

and
dsPIC®
microcontrollers. The MPLAB IDE's most significant components are:



graphical projec
t

manager

to create and open source files



t
ex
t

editor

to edit and create source code



output window

including all relevant information on the compilation process


Figure

1
: MPLAB IDE
Overview

Output Window

Text Editor

Project Manager

6

Introduction to Microcontroller Pr
ogramming

2.2

Setup

New Project

To set up a new project click on


Project



Project Wizard…


Figure

2
: Project Wizard #1

The following welcom
e

dialog has to be
confirmed with
Weiter
:


Figure

3
: Project Wizard #2

Step One:
Select "dsPIC30F4011
" as device:



Figure

4
: Project Wizard #3

Introduction to Microcontroller Programming


7


Step Two:
Select “Microchip

C30 Toolsuite”
as Active Toolsuite:



Figure

5
: Project Wizard #4

Step Three:

Define project name and store
location
:


Figure

6
: Project Wizar
d #5

Step Four:
Simply confirm with
Weiter
.
Source files will be added later
:


Figure

7
: Project Wizard #6

8

Introduction to Microcontroller Pr
ogramming

The final summary offers all parameters of the
project:


Figure

8
: Project Wizard #7

2.3

Ble
nd P
roje
c
t

M
anager

Click on
View


Project

to
show

the project
manager
:


Figure

9
:

Proje
c
t

M
anager

#1

After that the project manager is shown
:


Figure

10
:

Project Manager

#
2

Introduction to Microcontroller Programming


9


2.4

Setup

New Source File

Create a new file with

File



Ne
w

to set up a
source file and add it to the current project:


Figure

11
:
Add

Source File

#1

A new
f
ile called “Untitled” is opened in the
text editor after that
:


Figure

12
:
Add Source File
#2

With

File



Save As…
the new text file can
be saved in the requested directory
:



Figure

13
:
Add Source File
#3

10

Introduction to Microcontroller Pr
ogramming

The file extension has to be set to
".c"

by
hand
:


Figure

14
:
Add Source File
#4

To add the new file to the project right
-
click
on
Source Files
in the project manager and
select
Add Files…


c楧u牥



䅤搠卯畲Ae⁆i汥l


2.5

Configuration of the Microcontroller

T
o get a correct exec
ution of the program on the dsPIC30F4011
, t
he microcontroller needs to be
configured
. This includes, for example, choosing the source of the clock signal, reset settings of
the microcontroller, switching the pulse
-
width modul of the microcontroller on and
off or the
protection of the source code. More detailed information of co
nfiguration can be found in the
corresponding data sheet.

For

the laboratory
, the
configuration

of the microcontroller

is given.

The easiest way to
set

up
the
configuration is
via

me
nu which is accessed by
Configure


Configuration Bits…
:


Figure

16
:

Mi
c
rocontrollers

Configuration

#1


First you need to remove the check mark on
„Configuration Bits set in Code“
. After that you can
set the parameters correctl
y as it is shown in the figure 17 for the first and in figure 18 for the
second day:


Introduction to Microcontroller Programming


11



Figure

17
:

Configuration of

the Subsystem

A


Figure

18
:
Configuration of the Subsystem
B

2.6

Microcontroller Progra
mming

The

dsPIC30F4011

microcontroller

supports

In
-
Circuit Serial
Programming

(
ICSP).
The
programming

of the microcontroller

is done using

a programming device

via a communication

channel

of the microcontroller
,
consisting of

a line

for serial

data

transm
ission, and

a clock line
.
The programmer

used

in the laboratory course is
MPLAB

ICD

2 by

Microchip.

The necessary
steps on programming the microcontroller are shown below.

2.6.1

Selection and Configuration of the Programmer

The program
mer

i
s selected via
Program
mer → Select Programmer → MPLAB ICD
2:

12

Introduction to Microcontroller Pr
ogramming


Figure

19
:
Select Programmer

After that the output window shows a new
tab

which
returns

the status of the ICD 2 program
mer
:


Figure

20
: Status

Message of the

Programm
er

Via

Programmer



Settings…


Figure

21
:

Configuration of the Programmer
#1

you get access to tab
Program2

where you are able to do settings concerning automatic loading
and starting of the program after successful com
pilation:

Introduction to Microcontroller Programming


13



Figure

22
:

Configuration of the Programmer #2

You need to select
„Program after successful build“
to load the program automatically and
„Run after
successful

program“
to start the program automatically.


2.6.2

Compiling Pr
ogram

A program is compiled via
Project → Build All
or via the shortcut
Ctrl +F10
:



Figure

23
:

Compiling the Program

The tab
Build
in the output window shows information on the compiling process and its result. In
case the pr
ogram contains any errors which can be recognized by the compiler, it will show the
associated error messages including information on the code

line and the cause of error. You can
switch the outlook including the cursor to the associated section of the co
de with a double
-
click
on the corresponding error message. If no errors have been found the successful compilation is
confirmed with „BUILD SUCCEEDED“:

14

Introduction to Microcontroller Pr
ogramming


Figure

24
:

Status Message of the

Compile Proc
ess

2.6.3

Loading the program onto
the microcontroller

The
successful

compiled program is
transferred

to the microcontroller with the command
Programmer → Program
or the symbol „
Program target advice“


in the command line up
right:


Figure

25
:

Loading the prog
ram onto the microcontroller

Again you are getting feedback via the output window:


Figure

26
:

Status Message of the Programmer

Introduction to Microcontroller Programming


15


In case you have chosen the corresponding function in
Programmer → Settings...
as told in
2.6.1, pr
ogram execution starts automatically. Otherwise you have to put the programmer
MPLAB ICD 2 in reset status using the command
Programmer → Hold in Reset.


16

Introduction to Microcontroller Pr
ogramming

3

Microchip
C30

Toolsuite

and

C programming language

C is an imperative programming language developed b
y the computer scientist Dennis Ritchie in
the early 70's at Bell Laboratories
for the operating
system

Unix
. Since then it has been used on
many computer systems and it is a programming language which is available
for

nearly all
computer systems. It is on
e of the so called procedural programming languages. C is mainly used
for system programming including the
design

of
operating

systems and embedded system
programming. This is because of the combination of
desired
characteristics

as portability and
efficie
ncy with the possibility to
address

h
ardware directly. A C

p
rogram is linked
from
the
object code
to the
executable

computer program by a
so called
linker. In doing so several object
code
files

can be put together to one program. The object code
files

are

generated

by the
compiler using text
files

which contain a number of function and variable definitions.

Microchip C30 Tool suite units the C
-
Compiler and the linker and offers that way all tools which
are needed to produce the machine code. The C30 Compile
r is an ANSI compatible
c
ompiler
equipped with standard, mathematical, storage and data conversion libraries. C30 Compiler also
supports periphery libraries which can be used for the utilization of different periphery modules
of the microcontroller. There
is an evaluation version available for the C30 without time limits
for free usage. More detailed information on the C30 Compiler can be found in the document
„MPLAB® C Compiler for PIC24 MCUs and dsPIC® DSCs User’s Guide“

(download

at
www.microchip.com
).

You find a quick overview of the necessary knowledge on the programming language C in the
following subsections.

3.1

General Advices



all commands end with semicolon



local variables exist just as long as the method in
which they were declared exists



insert command
b
locks
using tabulator due to better overview



logical command blocks, as for example an If


Condition's statement is always surrounded
by curly brackets
{ }



single spaced comments start with
//

Example:

//
it

is

a comment



multiline comments have to be put into /*
comment

*/

Example:

/***********************
***
*


* it is a comment
*


*************************
*
*/

3.2

Calculations

Operator

Meaning

Example

+

addition

7 + 8

-

subtraction

7


4

*

multiplica
tion

3 * 5

/

division

21 / 2

%

m
odulo

21 % 5


Introduction to Microcontroller Programming


17


3.3

Logical

Operator
s

Operator

Meaning

Example

==

equal

x == 3

!=

unequal

x != 3

< , >

l
ower than, greater than

x < 3, x > 3

<=, =>

l
ess or equal
,
greater or equal

x <= 3, x => 3

&&

and

(x > 3) && (x < 7)

||

or

(x > 3) || (x < 7)

3.4

Increment
/
Decrement
Operator
s

Operator

Meaning

x++

x = x + 1


//
increment

(postfix)

x
--

x = x


1


//
decrement

(postfix)

++x

x = x + 1


//
increment
(prefix)

--
x

x = x


1


//
decrement
(prefix)

3.5

Numeric Values

Numerical
values can be stated in different ways. Depending on their purpose (value of a
variable, value of a register, …) it is suggested to take the most adequate mode for reasons of
overview.

Mode

Example

Usage

dec
imal

100

counter variable
,
value variable

hexad
ec
imal

0x100

register value
,
command

binary

0b01010101

register value

3.6

Data T
ype

Declaration Tokens

Bits

Min

Value

Max Value


char, signed char

8

-
128

127

unsigned char

8

0

255

short, signed short

16

-
32768

32767

unsigned short

16

0

65
535

int, signed int

16

-
32768

32767

unsigned int

16

0

65535

long, signed long

32

-
2
31


2
31



1

unsigned long

32

0

2
32



1

3.7

Variabl
es

A variable can be local. It exists only as long as the method in which it was declared exists and
can

only be read and changed within this method.

A variable can be global. It exists during the program's whole operating time and can be read and
changed by all methods of the program.

A variable first needs to be declared. Thereupon the micro controller res
erves memo
ry capacity.
Therefor the micro
controller needs to be told what kind of type the variable is. The declaration of
all used global variables should succeed collective at the start of the method for reasons of
overview.

Examples
:

int x;


// v
ariable

x
t
yp
e

int

18

Introduction to Microcontroller Pr
ogramming

The initialization succeeds via the sign „=“ .

Examples
:

x = 10;


//
the v
ariable x
is allocated with






//
the value 10

x = y + z;

// the variable x is allocated with





// the result of a calculation

x = get_red();

// the variable x is all
ocated with





// the return value of the function





// get_red()


3.8

Method
s

A method is a summary of several consecutive commands. If a method is called, the
microprocessor jumps to the place in the program where the called method is defined.

Calling a m
ethod parameters can be
transfe
rr
ed

(
t
ransfer parameter) which are needed to carry
out the instructions. A method can also return a value (return value). Transfer and return value
s

are defined at the declaration of the method.

In case a certain control seq
uence is used several times it is suggested to summarize this control
sequence in a function for reasons of memory capacity. This also supports a better structure of
the program.

3.8.1

Declaration of a m
ethod

The methods X, Y, Z which are used in the program fir
st need to be declared. Declaration of the
methods is done at the start of the source code. They show the compiler that the functions X, Y,
Z exist.

Syntax:

[return type] [method name] ([parameters separated by commas]);

Example
:

int multiplic
ation(int a,

int b);

If the method is not to return a value it is marked with
void


Example
:


void setpwm(int onvalue, unsigned int colour);

Is the method not given a parameter it is also marked with
void


Example
:

unsigned int get_red(void);

3.8.2

Definition
of a method

Af
ter the declaration the definition of the method is done. The control sequence which should be
carried out by the method is retained.

Syntax:

[return type] [method name] ([parameters separated by commas])
{



statement
;


… ;



return
[return value]
;

}


Introduction to Microcontroller Programming


19


Exam
ple
:


int multiplic
ation(int a, int b)



{




int c;




c = a*b;




return c;



}

If the
m
ethod does not contain a return value, there is no return statement.

3.9

Branches

3.9.1

if
-
statement



if
“condition” is accomplished
,
than

“statementA”,
else

“statementB



Synta
x:

if(
condition
)




{




statementA
;




… ;



}



else



{




statementB
;






;



}



Example
:


if(pressed(1) =
= true)



{




firstline(
"
button

1
"
);



}



else



{




firstline("
no button
");



}

3.9.2

Switch
-
statement



Sequence of if
-
statements, which differentiat
es between several valid conditions



Syntax:


switch(v
ariable)



//

sequence of if
-
statements
:

{






//

case A:




//

if (v
ariable == A)

{





//

{

statementA
;


//


statementA
;

… ;




//


… ;

}





//

}

break;




//






20

Introduction to Microcontroller Pr
ogramming

case B:




//

if (v
ariable == B)

{





//

{

statementB
;


//


statementB
;

… ;




//


… ;

}





//

}

break;




//

.





//

.

.





//

.

.





//

.

default:




//

{





//

s
tatementX
;


//

… ;




//

}





//

break;




//

}






//



The break
-
statement at the end of each case
-
statement is needed
to exit the switch
-
statement.
If the break
-
statement is forgotten, than the next case
-
statement is executed.



If no of the previous condition is accomplished, the default
-
statement is executed.

3.10

Loops

3.10.1

For
-
Loop



Needs an integer value as counter



Syntax:


for(
s
tart condition
;
end condition
;
step statement
)

{



statement
;



… ;

}



The speed depends on the processor cycle and on the length of the statement inside the loop.



Example
:

int i;


for(i=0; i<=10; i++)

{


lcd_command(0x01);

}

The command
lcd_command(0x01)i
s
executed ten times in the displayed example.



A for
-
loop without any condition corresponds an infinite loop.

for(;;)

{


statement
;


… ;

}

Introduction to Microcontroller Programming


21


3.10.2

While
-
Loop



while
“condition” is accomplished,
execute

“statement”



Syntax:

while
(
condition
)

{


statement
;


… ;

}



V
ali
d

compare operators

for conditions are
:

>= , <= , = = , !=

3.11

Conversion of Variables to String

To be able to produce
single

signs in the programming language C, you need to declare a
variable of the data type
char
. Subsequently you can allot a sign put int
o single quotation marks
to the variable.

Example
:

char x = 'A'

//
the sign A is stored in the variable






//
variable x

The signs are coded according to the ASCII
-
Code and in that form depos
i
t
ed

in a variable. The
letter A corresponds to the number 65

in the ASCII
-
Code.

To be able to produce and convert strings you need to establish an array of the data type
char[]
. Then you can allot a text in double quotation marks to this array. Thereby it is not
necessary to state the
length

of the array because i
t is defined automatically on the basis of the
text. Each sign in the text is conform
ed

to one byte. The array's length matches the text's length
plus one more byte in which the so called „zero character“ sign is saved. „Zero Character“
symbolizes the end
of the text and informs the compiler that there is no more sign
s

after that one.

Example
:

char text[] = "
this is a s
tring"

To convert a variable of the type integer into a string, a little effort in C is needed. With the help
of the method
sprintf
, which i
s part of the library
stdio.h y
ou can convert the integer
variable in a string.

Syntax
:


sprintf(
output variable
, "
placeholder for the output
",
sources
)

This demonstrated best with an
example
:

The values as the sums of the two integer variables x and y are

to be issued in a string which
points out the arithmetic operation of the addition.

The

instruction sequence

for that is
:


int x;

int y;

char text[];

x = 10;

y = 20;

sprintf(text, "%d + %d = %d", x , y , x+y);


The v
ariable
text[]

now contains the s
tring

"
10 + 20 = 30
"


22

Introduction to Microcontroller Pr
ogramming

It always has to be indicated a string (corresponds to an array consisting of characters) as output
variable. Valid placeholders are shown in the following table:

Placeholders

Type of Source

C

character

D

signed decimal integer

U

unsign
ed decimal integer

S

string of characters

A placeholder is marked through a preceded % sign.
The order of the placeholders corresponds
to the order of the sources.

3.12

Struc
ture
s a
nd Unions

3.12.1

Structures

Structures are used to summarize several components whic
h belong together of simple data
types. This way new and complex variables can come into existence. All components are saved
one after another.

To define a structure you use the code word
struct
. After the code word the related
components are put together

in curly brackets. In case you do not want to use the whole number
range of a component, you can state by the number of bits, how many bits of a component
should be used.
If all bits of a component are o
f interest there is no need to state the number of
b
its. The names of the new variables, which consist in structure components, have to been stated
directly after the curly brackets.

Syntax:

struct



{




data type componentname1


:Bit
-
count
;

data type componentname2


:Bit
-
count
;








:Bit
-
count
;

}
variab
lenname1, v
ariablenname2, … ;

This is best explained with an example. We want to
produce a 16
-
bit variable named

w
ord
,
which is composed by two 8
-
bit components (High
-
Byte and Low
-
Byte). The variable is
produced the following way:

struct

{

unsigned char hi
ghbyte;

unsigned char lowbyte;

}
word
;

The access to the individual components of a structure is done via the component name. For
example, if you want to put down the value 10 in the component
highbyte

of the variable a
from the data type
TWord

, you need t
o select the following command:

word.highbyte = 10;




Introduction to Microcontroller Programming


23


If you wa
nt to produce a variable called

bitwise
, in which you have access to individual bits,
the following structure is requested:


struct


{



char b0


:1;



char b1


:1;



char b2


:1;



char b3


:
1;



char b4 :1;



char b5 :1;



char b6 :1;



char b7 :1;


}bitwise;

The structure is composed by eight 8
-
bit components of which, however, only one is getting used
in each case. For example, if you want to convert bit 5 of th
e variable
bitwise
, you need to
select the following command:



bitwise.b5 = 1;

3.12.2

Unions

Unions are also used to produce complex variables. In contrast to the structures the components
are not saved one after another but put in the same storage place. Union
s unite, basically,
different identifiers to access the same storage place.

Syntax:

u
nion

{




data type componentname1;

data type componentname2;

…;

}variablename1, variable
name2, … ;


For the processing of the experiment the following union is of intere
st:

u
nion

{


char bytewise;




struct


{



char b0


:1;



char b1


:1;



char b2


:1;



char b3


:1;



char b4 :1;



char b5 :1;



char b6 :1;



char b7 :1;


}bitwise;

}
display
;

A variable called display

is produced, which puts
two components
bytewise

and
bitwise

in
one storage place. The component bitwise is, in this case, a structure which makes it possible to
24

Introduction to Microcontroller Pr
ogramming

access individual bits. For example, if you want to allot the value 10 to the variable
display

(bytewise, what means al
l 8 bit at one time) you need to select the following command:

display
.bytewise = 10;

For example, if you only want to allot the value 1 to the fi
f
th bit of the variable you need to
select the following command:


display
.bitwise.b5 = 1;

3.13

Support for progra
mming the microcontroller

To support the programming of the micro controller there is a corresponding header data for each
micro controller. It needs to be included in the project and makes it possible to access the so
called Special Function Register (S
FR) of the micro controller. Access to this register is
necessary to configurate the peripherical functions of the micro controller.

To describe the whole SFR the following command is requested:

name of SFRs = value

Example:


T1CON = 0;

// T1CON SFR is se
t to 0

To describe individual bits of a SFR you need add
bits.

to the name of the SFR and
subsequently to state the name of the bit which is to be converted.

Example:

T1CONbits.TON;

// TON
-
Bit of the SFRs T1CON is set to 1


Introduction to Microcontroller Programming


25


4

Experiment Hardware


The
e
xper
iment
h
ardware, which is described in detail in the following, is connected to the
laboratory computer and is
powered by an

AC adapter with the

necessary voltage
.
The
connection of the

experimental
hardware to the

laboratory

PC via the

programmer

MPLAB

ICD

2

allows programming

and

monitoring of the complete system.


Figure

27
:
Overview

The experiment hardware consists of five components.
T
he

m
ainboard
,
consisting

of two
subsystems
, forms
the core of

th
is

arrangement
.
Each subsystem

has its own

microcontroller

and
is a unit in itself
.
Both

subsystems

are located on

one board.

Subsystem A is getting used during
the first two parts of the
laboratory

and subsystem B for the third part.

The component "
IAS
ti
cker
"
is

connected

via cable to

the

subsystem A
.
The components "
RGB
LED

Panel", "
RGB
color sensor
" and
"analog

voltage display
" can be connected
via cable to

the

subsystem B
.
The block

diagram of the whole

experimental hardware

is shown

in Figure 28.


Figure

28
:
Block diagram

of the
experiment h
ardware

26

Introduction to Microcontroller Pr
ogramming

4.1

Installation

4.1.1

Hardware
i
nstallation

Before you start using the experiment hardware, make sure that the mainboard is placed
on a
nonconductive

surface. K
eep experiment hardware away
from moisture
!

Connect the IAS ticker display to the subsystem A using the designated
cable
. Connect the
programming device ICD

2 by the company Microchip to the subsystem A using the RJ25

cable

and to the laboratory computer u
sing a USB
cable
.

Connect the RGB
-
LED
-
Panel, the analog display and the RGB color sensor to the subsystem B
using the designated
cables
.

4.1.2

Software
Installation

The developing environment MPLAB, the C30 compiler and the driver for the program
mer

ICD

2 by the

company Microchip have
been
already installed on the laboratory PC.

4.2

Start
-
Up

4.2.1

Start
-
Up
Hardware

To start
-
up the experiment hardware, connect the subsystems A and B to a 24 V power supply.
The status LEDs „24V Power On“ and „5V Power On“ are illuminated now

on both subsystems.

4.2.2

Start
-
Up
Software

The development environment is opened with a double
-
click on the symbol „MPLAB DIE
v8.10“.

Introduction to Microcontroller Programming


27


4.3

Overview

Sub
system A


Figure

29
:
Overview

Sub
system A

Element

Func
tion

+24V

e
xternal

power supply

ICD

ICD

i
nterface
for programming und debugging

RS232

s
eri
al

RS232

i
nterface

for communication with

Labor
atory
-
PC

(
not needed for this experiment
!)

CAN

CAN

i
nterface for communication and
controlling systems
supporting the C
AN b
us

(not needed for this experiment!)

Mikrocontroller

Mic
rocontrollers dsPIC30F4011
by

Microchip

Prototyping Area

e
xpansion for subsystem A

(not needed for this experiment!)

I
2
C LCD Display

alphanumer
ic

LCD Display (2
lines

à 16
signs
)
with

I
2
C

i
nter
face

for information output

(not needed for this experiment!)

Sieben
-
Seg
ment
-
Anzeige

two
-
digit

7
-
segment displays

for
displaying

numbers

from
00
to

99

IAS
-
Laufschriftanzeige

i
nterface to connect to the IAS
-
Ticker

PORT
-
LEDs

9 LEDs
to visualize the

Port
-
Outputs

of the microcontroller

Variable Analoge Spannung

t
he variable analog voltage can be adjusted by moving the
potentiometer in the range of 0V to 5V.

(not needed for this experiment!)

RESET

b
utton to reset the subsystem A

28

Introduction to Microcontroller Pr
ogramming

4.4

Overview

Sub
system

B


Figure

30
:
Overview Subsystem B

Element

Fun
c
tion

+24V

external power supply

ICD

ICD

i
nterface for programming und debugging

RS232

serial RS232

i
nterface for communication with Laboratory
-
PC

(not needed

for this experiment!)

CAN

CAN
-
Interface for communication and
controlling

systems
supporting the CAN

b
us

(not needed for this experiment!)

Mikrocontroller

Microcontrollers dsPIC30F4011 by Microchip

Prototyping Area

Expansion for subsystem B

(not needed

for this experiment!)

LCD Display

alphanumeric LCD Display (2 lines à 16 signs) with
parallel
i
nterface for information output

RGB
-
Sensor

i
nterface to connect
to
the RGB

color sensor
, which captures the
basic colors red, green and blue

RGB
-
LED
-
Panel

i
n
terface to connect to the RGB

LED p
anel consisting of LEDs
in the basic colors red, green and blue for a
true to original
reproduction

of the colors
captured by the RGB

color sensor

Analoge Anzeige

i
nterface to connect to the analog display consisting of
three
moving
-
coil instruments for capturing the voltages given by the
RGB

color sensor

4 Taster

4
buttons for user interaction with subs
ystem B

RESET

b
utton to reset the subsystem B

Introduction to Microcontroller Programming


29


4.5

Pinout

of the

Mi
c
rocontroller dsPIC30F4
011 (Sub
system A)

Figure

31
:
Pinout of the Microcontroller dsPIC30F4011 (Subsystem A)

30

Introduction to Microcontroller Pr
ogramming

4.6

Pinout of the Microcontroller dsPIC30F4011 (Subsystem B)

Figure

32
:
Pinout of the Microcon
troller dsPIC30F4011 (Subsystem B)

Introduction to Microcontroller Programming


31


5

Launching the
Mi
c
rocontroller

(
Part

1)

5.1

Task

The first part of the experiment deals mainly with launching the microcontroller and its
peripher
al

functions. The aim of this part
of the experiment
is
the control of

a

two
-
dig
it

seven
-
segment
-
display in multiplex
mode
. To realize the
control
,

launch
ing and configuration of

the
I/O Port
s,

the timer unit and a timer

overflow

interrupt

is required
.

5.2

Overview of
Microchip
dsPIC30F4011



16 Bit
architecture



30 MIPS (Million Instructi
ons Per Second)



48 KB F
lash

Memory



2.048 Byte R
AM



2
internal Osc
illator
s
: 7.37 MHz, 512 kHz



7
several

Timer: 5 x 16
-
bit
and

2 x 32
-
bit



2 x UART, 1 x SPI
and

1 x I
2
C
Interfaces



1 x CAN
Interface



Opportunity

to convert up to 9 analog values to corresponding
10
-
bit digital values



3
-
way PWM already provided and very simple to implement



30 I

/

O

pins provide

many

opportunities

to use

the microcontroller

in

various



The microcontroller

is commercially

available

for about



5
,
but can also be

ordered directly

from

Microchip

as a free sample

for
students.

5.3

Setup

I/O Ports

and

Control of

PORT
-
LEDs

The microcontroller

dsPIC30F4011

has 30

pins that

are used by the

peripherals

of the
microcontroller,

or they can be configured as digital

inputs or

outputs.

The single

pins

are

assigned to the

so
-
called I

/

O

ports.

Three registers belong
T
o
each

I /

O

port

belongs three
registers which determine

its

functionality
.
These

are:



TRISx
-
Register



PORTx
-
Register



LATx
-
Register


The letter x
identifies a particular
I

/

O Port.
Each I

/ O Pin is assigned in each

register
by one

bit.

The single

bits of the

TRIS

register

determine

whether the

associated I

/

O pin

is

configured

as
digital input

or output.

If the value

of the

TRIS

bit

set to 1
, the I
/

O

pin is configured

as digital
input
.

If the value

of the

TRIS

bit

set to

0, then

the I

/

O

pin is configured

as a digital

output
.

Examples:


TRISEbits.TRISE0 = 0;


// Pin RE0
as output



TRISEbits.TRISE0 = 1;


// Pin RE0
as input

32

Introduction to Microcontroller Pr
ogramming

If

the I

/

O pin

configured

as digital input
,
you can

check
via

the PORT

register
,
if

the

input

signal is

a HIGH

or LOW

signal.

If the value

of the PORT

bit

is

1,

the input is

a HIGH

signal
.
If
the value

of the PORT

bit

is

0,

the input is

a LOW

signal
.

Examples:


if(PORTEbits.PORTE0 == 1)

// Pin RE0
is requested

{

statement
;

… ;

}

If

the I

/

O pin

configured

as digital output
,
you can determine via LAT

register
,
whether

generated

signal
at the output

is
a HIGH

or LOW

signal.

If the value

of the LAT

bit is

set to

1,
then

at the output

a HIGH

signal

is generated
.
If
the value

of the LAT

bit

is
set to

0, then

at the
output

a LOW

signal

is generated
.

Examples
:


LATEbits.LATE0 = 1;


// Pin RE0
on

HIGH

LATE
bits.LATE0 = 0;


// Pin RE0 on

LOW

To visualize
the
state of the
outputs of
microcontroller
,
light emitting diodes

are used
. If there is
a HIGH

s
ignal at the
output

the LED lights up. In case there is a LOW
-
Signal it does not.

According to the data sheet,
the outputs of the micro
controller dsPIC30F4011 can only deliver
in
normal mode
the
current

I
OH

= 3mA (Output High
Voltage). To guarantee the required light
int
ensity
of LEDs,
the outputs of the micro
controller are buffered. To do
this,

the eight channel
High Side Driver UDN2981A by the company Allegro Micro Systems is used. It can deliver up
to 500mA

output current
. T
he resistors are used for current limiting and are dimensioned in such
a way that the current
through

the LEDs is about 6mA.

The circuit diagram for driving the PORT
-
LED
is shown in Figure

33.


Figure

33
: PORT
-
LEDs
Sub
sy
s
tems
A

Introduction to Microcontroller Programming


33


5.4

Timer Setup

A timer

is

a

configurable

counter that

increases

its value

with

every clock

cycle
. When the

timer
reaches

its final value
, it overflows
and

activates
a timer

overflow interrupt
.
In this case a
method which is responsible for the treatment of
the interrupt, the so called Interrupt Service
Routine (ISR) is
called

automatically.

ISR

is in
general just

a normal

method, however, not executed by defined

call in

p
rogram code
,
but

only

upon the occurrence

of a defined event
.
It does not matter at what

point microcontroller
executes the program. If the event for an ISR occurs, the running program is interrupted and the
instructions of the ISR are executed.

Events

that lead to

trigger an interrupt

are
,
for example,

changes to

digital

inputs

or
,
as
menti
oned

above
, timer
overflows
.

Timers are

used to

implement

cyclical processes
.
If you for example to poll a

sensor

every
millisecond
, then the
timer

unit can be

configured in that way that every

millisecond

an overflow

occurs

and a

timer overflow

interrupt
is

triggered.

Then a

timer

ISR

is called,

in

which the sensor
can

be

polled
.

dsPIC30F4011

microcontroller
has

16
-
bit and
32
-
bit
wide

timer.

If a timer overflows, it starts
again with the value 0 in the next clock cycle and counts up
un
til

the next overflow
.
You

can

also

set the timer

so that it

counts up

to a certain

value
.
If this value

is reached,

an interrupt

is
triggered and the

timer

starts again

at 0.

In this way

various

time

intervals

between the

two timer

overflows
can be realized.

The configuration

of the timer succeeds via three register which are the followings:



TMRx



PRx



TxCON

The letter x stands for the timer number.

TxCON

is

the configuration register

of the timer.

By setting the

TON

bit

to 1
, the
timer unit

is

turned on.

There are more timer se
ttings which can be arranged
,
such as

the choice

of the clock
signal

or the behavior

of the microcontroller

in sleep mode
,
which are irrelevant in this
laboratory

and

therefore
not discussed

in detail
.
For more

information

on configuring the

timer

unit

of
the microcontroller,

refer

to

the datasheet of the

microcontroller by interest
.

The register

is

TMRx

the count
ing

register

of the timer.

In this register
, the current value
of the
timer is

stored.

The count is

compared

with the

value stored

in the

PRx

regi
ster.

If the

value
stored

in the

PRx

reached,

the timer

generates an interrupt.

Each timer

also has

corresponding

bits

for configuration and control

of the

interrupts.

These

are
the following:



TxIE
-
Bit

(Interrupt Enable Control Bit)



TxIF
-
Bit

(Interrupt F
lag Status Bit)



TxIP
-
Bits

(Interrupt Priority Control Bits)

The Timer1
-
bits belong to the
IEC0

and
IFS0

register (compare to example).

To allow the

timer

to trigger

an interrupt
,
the

corresponding

interrupt

enable bit

(
TxIE
-
bit) is to
be set
to 1.

Whether

an interrupt

is triggered is checked by

the microcontroller with the help of
the
interrupt

flags (
TXIF).
If

the interrupt

event

has occurred
,
the interrupt

flag is

set to 1.

AT
THE END

OF

ISR

YOU
MUST

NOT FORGET

THAT

THE

INTERRUPT

FLAG

MUST BE
34

Introduction to Microcontroller Pr
ogramming

RESETTED,
O
THERWISE THE

ISR WLL BE EXECUTED I
NFINITELY

LONG
!

If there are several sources for an interrupt in a system, there is a
priority

order applied to the
single

events
.

For each event,

you can adjust the

priority.

This ensures

that

an interrupt

can

be

interru
pted by
another

interrupt,

if it has
the higher

priority.

The priority

of the timer interrupt

is set
by

writing
the

TxIP

bits.

The used microcontroller also offers the possibility to use 32
-
bit wide timer. The 32
-
bit timer is
made
up of two 16
-
bit timers

composed

together
.

O
ne
of the
16
-
bit timer
s

represents the high 16
bits of 32
-
bit timer,
and
the other
represents
the lower 16 bits. The interrupt controller of the 32
-
bit timer is rea
l
ized via the control bits of the 16
-
bit timer
, which represents the high 16 bits.

Example for
initializing

a 32
-
Bit timer (Timer 4/5):

T4CONbits.T32 = 1;


// 32
-
Bit Timer
out of

Timer4 und Timer5

PR4 = 0x25A0;



//
lower

16 Bit

PR5 = 0x0050;



//
higher

16 Bit

IEC1bits.T5IE = 1;


// Interrupt
-
Enable
Bit

IFS1bits.T5IF = 0;


// Interrupt
-
Flag



T4CONbits.TON = 0;


// Timer
disable

5.5

Control

of the

seven
-
segment display

To control the

two
-
digit seven
-
segment display a

BCD
-
to
-
seven
-
segment driver
CD4511B

by

the
company Texas

Instruments

is used.

The

BCD sig
nal

is generated by

four lines

of the
microcontroller.

The

truth

table of the

BCD
-
to
-
seven
-
segment
driver

is shown below
:


Figure

34
:
Truth
-
table

CD4011B



Introduction to Microcontroller Programming


35



As a seven
-
segment
elements

HDSP
-
5551
seven
-
segment displays by the co
mpany
Avago

Technologies are

used
. These are seven
-
segment displays with
common

cathode.

The resistors

R3

to R8

(see

Figure

35)

are each

dimensioned

with

470Ω

to limit

the current through the

individual

segments

to about

7 mA
.
At this current
, the
light

intensity of each single

segment

is
typically

2800μcd
.

Both seven
-
segment

elements are
controlled

by the
same
BCD
-
t
o
-
s
even
-
s
egment
d
river in the
multiplex m
ode
,

for which two more lines of the microcontroller are needed.

The

seven
-
segment
displays
are

alternately

turned on and off

by using
digital

NPN

transistors BCR523 by the

company

Infine
on

(see

Figure

35).

The switching frequency
should be at 100Hz to pre
vent the
display from flickering
, so
that the human eye

can

no longer perform

the switching.

The circuit diagram

for driving the

seven
-
segment display is
shown in

Figure 35.


Figure

35
:
7
-
segment display of

Subsystem

A














36

Introduction to Microcontroller Pr
ogramming

5.6

Preparation
E
xercises (Part 1)

Preparation exercises are to be done before the
laboratory
.

Exercise V1.1

Arrange in a table which pins of the microcontroller
for

control

of

PORT
-
LEDs

are needed
.
Consider using
schematic in Figure 33
, whether the pins
need to be configured as digital
inputs

or outputs. Which bits in which r
egisters of the microcontroller

need to be set
in
which way?
Write down a
n

instruction

sequence which configures the corresponding pins of the
microcontroller.

Exercise V1.2

Think abo
ut which bits in which registers of the microcontroller need to be set
in
which way so
that the PORT
-
LEDs light or do not light up. Write down a
n

instruction

sequence which makes a
PORT
-
LED
to
light up.

Advice:

It is a one line code!

Exercise V1.3

The mi
crocontroller

uses the

system clock frequency

FOSC

(system

clock source
),
which
depends on

the quartz and

the

configuration

of the microcontroller.

To execute a

command

four
system

clock

cycles are required
.
The

frequency with which

the microcontroller

exe
cutes

a
command

called

FCY

(Internal

instruction

cycle

clock)
.
FCY

can be determined using

the

following

formula
:


For

each value

this will be:




Determine the

internal

clock

frequency FCY
of the microcontroller
.
What value

would

you

write
to
the

PR1

register of Timer1, so that

Timer1

triggers

an interrupt

every millisecond
?

Exercise V1.4

What steps

are

necessary to

configure
Timer1 and

Timer1

interrupt

of

the microcontroller
?
Write

down
an

instruction sequence

that performs

these steps.

Advice:

It is a code of four lines!

Exercise V1.5

To check the

correct setting

of the

Timer1

the duration

between two

consecutive calls of the

ISR

should be
measured

using

an oscilloscope.

The easiest way to

measure

this

is
using a

pin
-
toggle
function

which

is called

at the beginning

of the

ISR.

Each time the

pin

toggle

function called, the
pin

of the microcontroller

(co
nfigured

as digital output
) changes
its value (
...
0 →

1 →

0 →

1
...)
.
The time interval

between

two such

changes

can be easily

measured

with

an oscilloscope.

For that reason it is suggested to provide at least one free pin (the so called test pin) on the
microcontroller when designing a system.

Think about how a pin
-
tog
g
le
-
function can be reali
z
ed. Write down a
n

instruction

sequence
which reali
z
es this function.


Introduction to Microcontroller Programming


37


Exercise V1.6

The duration

of an ISR

should

be as short

as possible
,
so th
ere

is

enough time

l
eft
for the main
application
.

To measure the
execution time
of a method
you can

use a test pin. At the start of a
method you set the test pin to High and at the end of the method to Low.
The duration

of the
high phase

corresponds to the

duration of executi
on

of the method and

can be easily

measured

using

an oscilloscope.

Write down two control sequences which process the setting and resetting of a test pin.

Exercise V1.7

Arrange in a table which pins of the microcontroller
to control

the seven
-
segment

displ
ay

are
required
.
Consider using the schematic in Figure 35,

whether the pins

needed to

control

the
seven
-
segment display

are
to be configured as digital
inputs

or outputs. Which bits in which
registers of the microcontroller need to be set
in
which way? Wh
ich
initializing

values are
reasonable
? Write down a control subsequence which configures the corresponding pins of the
microcontroller.

Exercise V1.8

Think about

how

the timing of the

both

control lines

for the realization

of multiplex

mode of
seven
-
segme
nt display should look like.
Make

a little sketch
.
How long should each seven
-
segment
-
element remain turned

on, so that a
switch

frequency of 100Hz is reached? Write down
a control sequence which reali
z
es the desired
behavior
.

Advice:

The control sequence

should be
called in the ISR of T
imer1!

Exercise V1.9

Think about how you can convert a decimal number in the range from 0 to 99 into a BCD
-
number. Write down a control
sequence which realiz
es this conversion.

Advice:

A possible

transformation would be

po
ssible

by splitting the

two
-
digit
decimal
number into

tens and

ones and

by subsequent

combination

of

their

BCD values
!

Exercise V1.10

Think about how you can put the BCD coded number now onto a seven
-
segment
-
display. Write
down a control subsequence which processes this task.

Advice:

Use the in paragraph 3.12.2 described union!












38

Introduction to Microcontroller Pr
ogramming

5.7

Implementation

Exercises (Par
t 1)

The
implementation

exercises are discussed and answered during the
laboratory
.

Exercise D1.1

Start the development environment MPLAB. Set up a new project and save it under a clear
name.

Exercise D1.2

Set up a
new source data „main_a.c“ and add

it
to

the project.
Add also

the header
file

„p30f4011.h“
to

the project
. Configur
e the microcontroller according to
Figure

17.

Exercise D1.3

Implement a method which configu
r
es and
initializes

the pins of the microcontroller for the
control

of the PORT
-
LEDs. Doi
ng this think about
reasonable

initializing

values.
Use your
results from

the preparation exercises V1.1 and V1.2.

Exercise D1.4

Implement a method which makes all PORT
-
LEDs
to
light up. Implement another method which
switches the
all

PORT
-
LEDs off.
U
se yo
ur results
from

the preparation exercises V1.1 and V1.2.

Exercise D1.5

Implement a
main method where you
configur
e

the pins of the microcontroller for
controlling

the PORT
-
LEDs and switch
on
a
ll PORT
-
LEDs
.

Exercise D1.6

Check if the program
mer

ICD

2 is c
onnected to the laboratory PC by the USB