Sie sind auf Seite 1von 56

Embedded Controller Lab Manual 15ECL67

ACHARYA INSTITUTE OF TECHNOLOGY

Dept of Electronics & Communication Engineering.

Embedded Controller Lab Manual


[15ECL67]
VI- SEMESTER ECE/TCE

A.C:."HA'·~ll'
JU:,·A··.

N arne of Student:

USN:

Dept of ECE, Acharya Institute of Technology


Course Title Course Code Core/Elective Credits Semester Year

Embedded Controller Lab 15ECL67 CORE 2 6 2017-18


Even
Contact Hours/ week Lecture Tutorials Practical
3 1 o 2
Name of the faculty RAGHUNATH.B.H
Designation and mail ID Assistant Professor
raghunath acharya.ac.in
Department ECE

B) Course Related Specifics

Prerequisites for the Course (exemption


from the prerequisites is provided only in
exceptional circumstance

l.Understand the architecture of~ Cortex M3- LPC1768


Course Objectives Microcontroller and assembly programming of ARM.
2. Learn to design:, construct, program, verify, analyze and troubleshoot
ARM assembly and ~ language programs and supporting hardware.

Syllabus:

PART-A: Conduct the following Study eXRerimentsto learn ALP using ARM Cortex M3 Registers using an
Evaluation board and the required s0fiware tool.
1. ALP to multiply two 16 bit binary nunlbers.
2. ALP to find the sum g£first 10 inte{er numbers.

PART-B: Conduct tli'efollowing experiments on an ARM CORTEX M3 evaluation board using evaluation
version of Embedded '6:' & Keil Uvision-4 tool/compiler.

1. Display "Hello World" message using Internal UART.


2.
3. Interface a Stepper motor and rotate it in clockwise and anti-clockwise direction.
Determine Digital output for a given Analog input using Internal
~BC of ARM controller.
Ihterface a DAC and generate Triangular and Square waveforms.
6. Interface a 4x4 keyboard and display the key code on an LCD.
7. Using the Internal PWM module of ARM controller generate
PWM and vary its duty cycle.
8. Demonstrate the use of an external interrupt to toggle an LED On/Off.
9. Display the Hex digits 0 to F on a 7-segment LED interface, with an appropriate delay in between.
10. Interface a simple Switch and display its status through Relay, Buzzer and LED.
11. Measure Ambient temperature using a sensor and SPI ADC Ie.
Cycle 1:
I. Differentiate between Microprocessor and Microcontroller.
II. Introduction to Cortex M3 Controller-
1. Features of Cortex M3 Controller.
ii. GPIO Operations - Selection and Configuration
III. Usage of Keil Microvision Tool.
i. Creating Project - selection of target controller and setting environment
ii. Creating Embedded C code.
iii. Compilation and Execution of Embedded C Code
IV. Interface of Cortex M3 Evaluation board with PC.
i. Connection of Cortex M3 board to host PC
ii. Usage of Flash magic to download Embedded C code to Cortex M3 board.

Embedded C Codes
1. Interfacing of "LED" - 8 no's to a GPIO of Cortex M3 Controller
i. To blink a single LED bit by bit.
ii. To scroll a LED from bottom to top and top to bottom.
2. Interface of toggle switch to a GPIO of Cortex M3 Controller.
i. Switch Status to be displayed on LED.
ii. Switch Status to be displayed on Buzzer. iii. Switch status to be disRlayed on Relay.
Cycle 2:
3. Usage of an external interrupt to toggle an LED onl off.
4. Usage ofInternal UAR T.
i. To transmit a single character data from Host to UART.
ii. To receive a single character data from UART to Host
iii. To transmit a string of character data from Host to UART

5. Usage of internal DAC of Cortex M3 controller


iTo generate Square waveform. ~
ii. To generate Triangular waveform.

6. Interface a Stepper motor to a GPIO of Cortex M3 Controller


1. Rotate stepper motor. in clockwise direction
11. Rotate stepper motor in an anti-clockwise direction

Cycle 3:

7. Usage of Internal PWM to generate.PWlvl and vary its duty cycle


8. Interface a DC Motor 'to GPIO of cortex M3 controller and perform it's control
operation using switches.
9. Interface of Seven segment module to Cortex M3 Controller-
1.
K
To display hexa digits €l to F with suitable delay.
~o display hexa digits 00 to FF with suitable delay

Cycle 4:, X~
10. Interface ot'LCD module to Cortex M3 controller -
i. To display single line message.
ii. '1'0 display two line messages.
11. Usage of Internal ADC -
t To determine Digital output for a given Analog input and display digital data on to LCD.
12. Interface a 4x4 keyboard to Cortex M3 controller and display the key code on a LCD.
13. Measurement of ambient temperature using a sensor and SPI ADC IC.
Keil Micro Vision® 5 IDE tool Step by step Tutorial
Open Kei15 IDE tool

Capfrigllt © 2010-2.016 ARM ltd. All lights reserved ARMKEIL


Thi!i proclLJct10;; protected by us mel inf:ern..ntic::JiIW Paws. Mi<rorontroll.rT-oals

Step 1. Open IDE, under


main menu goto "Project -> New uVision Project ... " and a window prompt will open askmg-jrname to save the
new project. Type your desired project name and save.

e jJViisi:mll
Ifilile' Edlilit Vilew I Prroj1e'ct I Ifl!alsnl De'D-!lJlgl iPe'rrilp,nle'rr,allls lioo,lls S,VCS: WilnJdio'!.i'i.i' IHle'llp'

rNlew M!lJlliliil-iPrrojle'dWt

o,rri(s.p'i3I(e", Op e'n, iPrrojledt.. ,

Close Proje'di

fm Create New Project x


~l' 111« Local Disk t., ) Keil5_pr-ojedt V· Co Search Keil5_project

Orrgi3!Iil.iiSe ....

Name Date modified Type


• D'esihop; No items match your search,
... D'o-wnlo;
~ D'ol(um~;tI

I!;l Pictu res;


V < >

A Hide ~olde" II Save III Cancell

Step 2.. After that, a new window will appear as shown below. Make sure "Software Packs" is selected for the 1st
drof down. In the search box below it, type "lpc1768" and then select the device from list below. Finally click
"OK".
x
Device ~

II Software IPadks

Vendor: NXP
Device: LPC1768
Toolset: ARM

I
I-
Searcm pc1768 l'
~----------------------------.
I 2
DescM~ion:

EJ ..·Q INXP'
EJ ..fl$ ILp'Cl700 'Serbes

- Quadrature Encoder interface,


- Motor -corrtrcl PW M for three-phase motor
- 2-'ifilpLrt plus 2-oLrtpl..!lt 12S-bus irrterface
<Code Read Pectectrcm (CRP) with -dfffererrt aecurtty Ievela ..
- Urncme device serial rurmber

4 l_o~_1 Cancel

Step 3. Now, inside the "Manage Run-Time Environment Window" select the check boxes for "CORE" under
"CMSIS" and "Startup" under "Device". If you want to select any other li15fariesyou can do so by selecting the
respective checkboxes. Selecting "Startup" will automatically added all the necessa[YJstartup/boot files required
for LPCl7xx device, so we don't have to import them from external sources. The selection of libraries can be
changed any time later. ~

x
Sofuv_i:llrre -Ooerup-om.enut
Sell" Valiliaillliit Veli'SI;OIill IChescrriiptilOIfl
Ei=1"~ Bc-aedl 'Sunp.p.o.rt MC1B1700 1,0,_()
s··? eMLSIS Cortex Mlucrrocolill"ltlJollllerr So1Ttrwalli"e lmnerfac e Co.impc
!··I·Q CORE I ~,0,,1 CMiSIS- CORE fo-r Cortex- M SOOOO SC3<OO ARM'v,(
! DSp r 1,~,,1 CMiSIS-!D<SP' lLiih,r.alry for Cc.mtex- Ml .50000 .aa-uclSl C3,
$~ RliOS(API) 1,0,,0 CM,SIS- RTOS AP'I fo-r Coeftex- M SOOOO andl SC3100
~ ~ Rli052 (API) 2,1,,0 CMeSIS- RTOS AP'I fo-r Cortex- M SOOOO andl SC3100
[$1 -~ 'CMrSIS Orr'jlve.,.
$-.~ ·Comlpiilelr ARM 'Compiil!err 1,2,.0 COli""Ji"lpiillelErrKttensiions forr ARMI COnfl'P'iller 5. .aJndAl R
8··~ Devi.ce
L..... Q GP'[}MlA
r 1,2,,0

i
Q
Q
Gp'IO
PIN
r 1,1,,0
1,0,,0
L.I·Q Sta,rt'lJP
$..~ Fil.e
I 1,0,0
MDK-p,o 6,9,,4
Sy.st.erm,
$-.~ G".i3lphiics ~,35,16 Us err IntelrlT.alceon QlrralphiicadllLel[) dliispllary.s
$"~ Nenwo.sjc 7.4,,0 IPv4/1 Pv5 INlettwOlrkiililiQI.l!..Ilsiina Ethernet orr Ser! a.1p1ile
i±l..~ USIB 6,10,,0

Resolve I I Select Packs, I I Detetls.


II OK
I CarTIGeI

Step 4. No.x;:ic?:'n "Options for Target" button as shown below:

El-'~
B"~ la,rr'g:e1t 1
SO!IJm'~e Grro!IJlp 1

~&
I····~CrloASIS
Ii"\, ..::_,_
x
Device. Target. l0citpuit I Lli;rtil"lgI User I CJC++ I Asrn Lirnlcer I DebLllg I Ultilities I
INXP 'L'PC11763
CodreGellleratioFil---;===========:::::;;l
)(tal ~MHz]: 112.0 AR M Compiler: I Use·defau'tt e,ampJler ",·e:rslo:rn 3
Operating syStem: IIN"",e

SyStemVi.e..e.r. Ale: r Use OF<>ss.~MocilcOileptimizatioru


I LPC 1 78<,5:..;svd rUse Micm'LI B r Big E ndian

rUse CLlI;rtom File

r-' Read/Vll'MritemoAryreas,------------,
ReadllO"M,iyem"rAyreas'--------
----,
default off-ctnp Start Startup .aefaui~ of"f-ehip Start Size N"lnit

r IROM11: I r: r 'RAM1: r
r ROM2:
I r: r RAM2: I r
r ROM.3:
I r: r RAM3rl :---
r
.""-<o"'i" ,,,,-<'hi,,
II P IROM1: 1Ih'o
r IROM2 I I r: r IRAM2 11h2007C0!J![I 11h13O!JO r

OK I I Cerncel I I lDefaui~s, Help

~
Step 5. Now, click on the "Output" tab. If you want to generate hex file then you can check "Create HEX File".

iii 'OptiicmlS; for 'lj;alr,g:e1t 'lj;alr'g:e1t 1'


l, eUck.Dill this; tab
lDeVice I Targt I
OlJl1:plJit LlitinQ! I User I c;c....1. Asm IUFTiker IlDebug! I Utilities
I
IName·of IBlecLitab'le: 11.pc17fu~pj"

r Greate IBatch lFile

IP Create HEX ,Ale I :2.ethlecktiltl~Sif you want to generate hex file


P IBm,,",,e'I",f,.rmati"",

r Create Library: .\Objecl".\!Jpc176':<~pi"Jib

Step 6. Then click on the "LinKer"tab and Under that tab check the checkbox option which says "Use Memory
Layout from Target Dialog".
!Device I Target I Outpuit I Ustin~ I lJser I C!C++ I Asm
I Lltil~ies I

ae'bU~I
i9 Options TImTalrget 'lalrget l' t Clic1k on this tab x

117 Use IMemory lLayouit from large! lDialo~ Xfl) IBase: r-------

t
r Make RW SectionsP' osition 'IFldeperndent. IRIO' Base: 11h00'l}l}[HHH)
r Make· R,D S..ed.ions ! RIW IBase I
Ih 100Il00I}[)
P'OS~i.nO,In.dependent
r Dont SearchStsndard Ltibranes r------------:
17 Report lmighitfail' COFild~ioFialSs, Errors, disable W'amirngjs,:

2. Check this box

Scatter Edit ...


Step 7.Now, under the "Debug" tab, change the values for "Dialog DLL" and "Parameter" under both simulation
and hardware debugger settings group. You can select "Use Simulator" to debug your code using simulator itself. If
you are using JTAG programmer or any other hardware debugger supported by KEIL then you can select it from
top-right drop down box. We will see flashing and debugger options in detail in an upcoming post. Finally to click
"OK" to apply settings and close window.
~~Pd:ebSJYgOiOr ~Tp~:Ui~'~snligm To deblJlgyolUlr appl uS~FI1dgebug HIW
»:
Dete I uarget I Ollitpllit I Listing I User I CIC ......I I Iu;t,.:r De'blilg IlLItilitieS I
Asrn
r. Use Simulator' with restrictions, Settings, I r: IlJ'se,:I.!I-UINK/,.!i-llR.A.CIECoITe'l< =:J Settings,
r Umit Speed to Real-Time

1'7 Load Applicatiom at Startup 1'7 Load Applicatio.Fialt 1'7 RUlFt1ol mai",O
Imit,ializ'aticmhile: Startup
l",itiali2aticmRle:

I ~ Edit., I I d Edit.,
- Rest.oreDetmg Sessi"", Settirngs,------------, "Restore, Debug Session Settings ------------,
1'7 Breakipoims 1'7 u(mlba:>:' 1'7 IBreakpoims, 1'7 Toolbox
1'7W'atch Wimdo...s.. 8, Performance 1'7 \"ilatch Wi"'do ...s.
Analy;zer
1'7 MemQIJfDisplay 1'7 System Vie...e..r
1'7 MemGlryDisplay 1'7 System
Vie...e..r

CPU DLL: Parameter: Driver DLL: Parameter:


SAJRMCIM3,1LDL I-M PU SAJRMCIM3,IOULIr'--IM--P---U---,------

Dialog DLL: Parameter: Dialo!'llDLL: Parameter:


IDA!RMP1.DLL 1"1;p-,,::"",L=P=C-::-:1=70=63-:----------- ITAiRlMP1.IDUL 1"1~;Up-=' P-::C-:-::,:---
l-=--7-6--3----::,'

Manage Cornponem Vie...e..r Description


FIles;,

I OK
II Cancel Defaults. Help

Step 8. Now, in the source navigation pane on the left area, right cli~k'on "Source Group 1" and select "Add New
Item to Group 'Source Group 1'''. A.
~' "
~raj.ect r;tEl
E.I<.t$ ~mjecIpt:c17Dx_'9Pi:o
EHb larget1
! ~ SourceGrnua.L,, j-'- --"

i t@> eMSIS J{f:, Opti0m TIm Grra~~, 'Samce GIT~W,~1' '...


~,:@> DevicIe,------------------- .,.
I ..,D RliE Add New lte'm to Gro~p '50orce Group 1'..'_~ _:::::::]I
, Ad~ Exis1ti:ngfil'es, to Gmwp, ':S~mce Gwwp' , ....
', ..1[] start
Remo~e 'Group 'Source Gm~p,,' ,a~dl its Filles
~~ SY5t -
Open
~,uI::idll.egl
1::tII J:;!f"hLI i:llfi ,;:lUfI arrret filfL':;

Add Nevv Item to Gu,oup 's.oUlrcee G,-.Ol!.JlP'

Create a ne....C..-+--t- soun::efile and add i't to <theproj


'~ CIFile{.c)

e~~ C+-o-File (_cpp) I L Sele t C+... Filoe (or C File)


~ Asrn FUeo£.s)

~ Header File ( j-n )


[jjjiJ Terl IFile-(.t:rl)

~ Image 'File(:'")

~ User Code Template

D:: \KE:il.5_projec.1:
Step 10. Now you can write your code in the editor. To compile your program Press "F7" key or in the main menu
goto "Project->Build Target". To check for any compilation errors you can have a look at the build output at the
bottom of main window. A screenshot of the Keil MDK uVision 5 is given below. The top red box shows the
Source Tree Navigation and the bottom red box shows the build output.

Step 11. To initiate a debug session using simulator or debug hardware/probe click "Debug->StartiStop Debug
Session" or you can hit "Ctrl+F5" as shown below:

II~ I ~

Project

Now open the flash magic software and follow the below steps. ~

1. Select the Device as LPC 1768 from Select Menu.


2. Select the COM Port. Check the device manager for detected COM port.
3. Select the Baud rate from 9600-115200. Ex: Set as 115200 ~
4. Select None ISP Option.
5. Oscillator Freq in Mhz. Type 12. i.e l2Mhz
6. Check the Erase all Flash + Code Rd Prot
7. Browse and Select the desired hex file. [project.hex file] ~
8. Press the Start Button to flash the hex file. ~

.• Flash Magic - NON ~RODUC1l0N USE ONLY


Beg~nby
selectlng the Slep 2 Erase
LPC1768f.rom th e
Erase block 0 (O<OOOooO-O<OOOFFF)
0 ptto ns Erase block 1 (0<001000-0<001 FFF) []
Erase block 2 (0<002oo0-0<002FFF)
Erase block 3 (0<003OO0-0<003FFF)
Erase block 4 (0<004oo0-0<004FFF)
Thenselectthe GOM Erase block 5 rO<005OO0-0<005FFFI
portthat the mbed
Oscillalor Hz): '----- -----'
isconnectedto

I Set up the baUJdr.ate

I
Hex File: C:\Users\vicmarIWFlash.he< I[ 8rowse ...
Modified: Tuesdey. November 28. 2011. 17:31 :48 more info
setectthe deslred
progr,am (hex file Slep 4 Options Slep 5 -
Slarll
- notbm fi~e!)
Statt
~ Verif~ sfter programming
IDFill unused Flash
D Gee block checksums
D E<ecule

www.esacademy.comhoftware}flashmaqic

Pr'es, start to begin


programrntng

CJleck COM port number from Device manager. Right click my computer, then click manage. Double
click device manger
.;1". Com Ruter Management

~ Computer Management (Local ...t


RDLmini-PC Actions
..011 ij'~ System Tools
I> ''liY Computer
t> (.5l TaskScheduler
t> G Event Viewer
p '"B Disk drives
t> !Yj Shared Folders I> ,..:"... Display adapters
t- Local Users and: Groups; I> 'q IDEATA/ATAPI controllers
t> ® Perforrnanc e I>'~ Keyboards
~ceManager ~'·B Mice and other pointing devices
... ~ Storage [> Monitors
~ Disk Management ~ ,.~ Network adapters
t> i'1: Services and Applications •T Port (COM & LPn
I··,··T Communications Port (COM1)

I> rocessors
[> ,.~ Sound, video and game controllers
I> yg System devices
~i Universal Serial Bus controllers

Register Configuration
~
LPC1768 has its GPIOs divided into five ports PORTO - PORT4, although many of them are not physically 32bit
wide. Refer the data sheet for more info. The Below registers will be used fQl1 Configuring and using the GPIOs
registers for sending and receiving the Digital signals. A structure LPC_GBIQn(n= 0,1,2,3) contains all the
registers for required for GPIO operation. Refer Ipcl7xx.h file for more info on ~ registers.
LPC1768 GPIO

PINSEL FIODIR II FIOSET, FIOCLR, FIOPIN I


~================tT==~
Selects Pin Function Configure Pin Direction II Access the Port Pin I

PINSEL: GPIO Pins Select Register Almost all the LPC1768 pms are multiplexed to support
more than 1 function. Every GPIO pin has a minimum of one function and max of four functions. The
required function can be selected IJ}( configuring the PINSEL register. As there can be up to 4 functions
associated with a GPIO pin, two bits for e'_'chpin are available to select the function. This implies that we need
two PINSEL registers to configure a RG>RTpins. By this the first 16(PO.0-PO.16)pin functions of PORTO can
be selected by 32 bits of RINSELO register. The remaining 16 bits(PO.16-PO.32) are configured using 32bits
of PINSELI register. A'!smentidned earlier every pin has max of four functions. Below table shows how to select
the function for a particular pin using two bits of the PINSEL register.

~ Value IFI unction IIEnumeration


'~OO IIprimary(default) function, typically GPIO port IlpINSEL FUNC 0
1\ , I' 01 IIFirstalternate function IlpINSEL_FUNC_1
y
10 IISecond alternate function IlpINSEL FUNC 2
11 IIThirdalternate function IlpINSEL FUNC 3

FJ0DIR:Fast GPIO Direction Control Register.

This register individually controls the direction of each port pin.

I Val ues II Direc tion


0 I Inp ut
1 Output
I I
FIOSET:Fast Port Output Set Register.

This register controls the state of output pins. Writing Is produces highs at the corresponding port pins. Writing Os
has no effect. Reading this register returns the current contents of the port output register not the physical port
value.

IValues IIFIOSET
~=====:
10 IINoEffect
~=====:
11 IISetsHigh on Pin

FIOCLR:Fast Port Output Clear Register.

This register controls the state of output pins. Writing Is produces lows at the corresponding ,0it pins. Writing Os
has no effect.

IValues IIFIOCLR
~=====:
10 IINoEffect
~==~
11 IISetsLow on Pi;;:

FIOPIN:Fast Port Pin Value Register

This register IS used for reading and writing data from/to the PORT.
Output: Writing to this register places cmresponding values in all bits of the particular PORT pins.
Input: The current state of digital port pins can be read from this register, regardless of pin direction or alternate
function selection (as long as pins are not configured as an input to ADC).
Note:lt is recommended to configure the PORT direction and pin function before using it.

GPIO Registers in LPC1768

Registers on LPC1768 are present on peripheral AHB bus(Advanced High performance Bus) for fast read/write
timing. So, these are Basically Fast 110 or Enhanced 110 and hence the naming convention in datasheet uses a
prefix of "FlO" instead of'something like "GIO" for all the registers related to GPIO. Lets go through these as
given below.

1) FIODIR : This is the GPIO direction control register. Setting a bit to 0 in this register will configure the
corresponMingpin to be used as an Input while setting it to 1 will configure it as Output.

2) FIOMASK : This gives masking mechanism for any pin i.e. it is used for Pin access control. Setting a bit to 0
means that tHe corresponding pin will be affected by changes to other registers like FIOPIN, FIOSET, FIOCLR.
Writing a 1 means that the corresponding pin won't be affected by other registers.

3) FIOPIN : This register can be used to Read or Write values directly to the pins. Regardless of the direction set
f0r the particular pins it gives the current start of the GPIO pin when read.

4) FIOSET : It is used to drive an 'output' configured pin to Logic 1 i.e HIGH. Writing Zero does NOT have any
effect and hence it cannot be used to drive a pin to Logic 0 i.e LOW. For driving pins LOW FIOCLR is used which
is explained below.

5) FIOCLR : It is used to drive an 'output' configured pin to Logic 0 i.e LOW. Writing Zero does NOT have any
effect and hence it cannot be used to drive a pin to Logic 1.
Most of the PINS of LPC 176x MCV are Multiplexed i.e. these pins can be configured to provide up to 4
different functions. By default, after Power-On or Reset: all pins of all ports are set as GPIO so we can
directly use them when learning GPIO usage. The different functions that any particular pin provides can be
selected by setting appropriate value in the PINSEL register for the corresponding pin. Each pin on any
port has 2 corresponding bits in PINSEL register. The first 16 pins (0-15) on a given port will have a
corresponding 32 bit PINSEL register and the rest 16 bits will have another register. For example bits 0 & 1 in
PINSELO are used to select function for Pin 1 of Port 0, bits 2 & 3 in PINSELOare used to select function for PIN
2 of port 0 and so on. The same is applicable for PINMODE register which will go through in last section of this
article. Have a look at the diagram given below.

PINSELORegister

31

PINSELl
...
31 1 30 29 1 28 27 1 26 25 1 24 23 1 22 21 1 20 19 118 17 116 15 114 13 112 11 110 9 18 7 16 5 14 3 12 1 10
PO.31 PO.30 PO.29 PO.28 PO.27 PO.26 PO.25 PO.24 PO.23 PO.22 PO.21 ""P~Q~ PO.19 PO.18 PO.17 PO.16

Example' Port 00 pin's function is decided by contents ofEINSELO register bit 0 and bit 1
~.

PO.O function decided by Pfl-J) Function as


PINSELO.l PINSELO.O V
0 0 when PINSELO.l=,...01P,.INSELO.O=0 Then PO.OFunction as General Purpose
110
0 1 when PINSELO;/p=O,"BINSELO.O=1 Then PO.OFunction as RDI
1 0 when PINSEL0.1~.J, PlNSELO.O=0 Then PO.Ofunction as TXD3
1 1 when PINSELO.l~~PIN;SELO.O= 1 Then PO.Ofunction as SDAI
Pili'lllFunctioli'lll Seifect registell" Ill) (PIIINSEIL,O_' ,Dx4DD2 COUD)
lIIf11,ePI NSIEIUJI' reg iste,lI oon1ilrols tlile ru IIlctions of tl1l,elowell half of Port: (iI'. lIIh,e' d i li'eotio III
oomtrol bit im IF I 'CHl IDI R. !",eglis1Jeis1'"elffeG1liveom'ly whelll tlile 'GPIO if1.ll1l1lc1iilsi:osmelectedl
1(:]11a'" pin. 1P,;;"!c!1I"olhe.lI 'fUIf1.C1iiOIllS, 1lh e d i li'eotio III is co nlrolled aUlwmaliica.llry.

IPiINSELO P.1~n F":ndIClOn _hen Flun.clll:lion 'when 0 1 IF-u,netlan F'u,netlo:n Reset


ftiB.l"rne IDOl _IIeftl'll'lllli 'wille.,. '11'11 v,aJ:Llle

1 ~O jp'(]I_(D G~F'il'OPort 0_0 RDl TXID3 SDAl 00


.3;(:2: PO_ 1 GPil G! P>DIiI: 0_ 1 TDl SOIL 1
:5c4., IPO_2: GPil'G! Port 0_2 TXICJ'[)' ADO..? 00
A DO ..6 00
CAP.2_!!} QeO

TlD2 00
13: '112 P{!1_I6 G~F'lDl PClrl!. 0_6 11.2E1RX;_SID.A r...tA.lI2f :.0 00
.sOlKl r...tA.lI2f :. 1 00
MISOl r...tA.T2:.2: 00
IMOiSJll 00

:2:'1:120 PO_ 10 GPil D PorIi: 0_ '110 TXIDQ SDA.2 '00


:23:22 PO_ 1 '11 GPll D PorIi: 0_ '1111 IRXD.2 SOIL2:
29:24 IReserved Reserved!
IPO_lei !G~F'\GI ! Port 0_ 15 TXDl

Since by default all pins are configured as GPIOs we don't need to explicitly assign a '0' value to PINSEL
register in Programming examples.
Example #1)

To configure Pin 4 of Port 0 i.e PO.4 as Output and want to make it High(Logic 1)

LPC_GPIOO->FIODIR = (1« 4); II Configure PO.4 as Ouput


LPC_GPIOO->FIOSET = (1« 4); II Make ouput High for PO.4
Alternate way is
LPC_GPIO->FIODIR = II in 32 bit form 0000000000000000000000000001 0000; 4th is 1
OxOOOO0010;

LPC_GPIO->FIODIR = OxIO; II Configure PO.4 as Ouput


LPC _ GPIO->FIOSET=OxIO; IIConfigure PO.4 as Ouput

Example #2

Making output configured Pin 17 High of Port 1 i.e P 1.17 and then Low can be does as follow)"

LPC_GPIOI->FIODIR = (1«17);
LPC_GPIOI->FIOSET = (1«17);
LPC_GPIOI->FIOCLR= (1«17);

Example #3)
Configuring PO.5 and PO.11 as Ouput and Setting them High:

LPC_GPIOO->FIODIR=(1«5) I (1«11); .c ~ II Config PO.5 and PO.11 as Ouput


LPC_GPIOO->FIOSET = (1«5) I (1«11);~ II Make ouput High for PO.5 and PO.11

Example #4)

LPC _ GPIOO->FIODIR = OxOOOOOOFF; II Config PO.0 to PO.7 as Ouput


LPC _ GPIOO->FIOSET = II Make output High for PO.0 to PO.7
OXOOOOOOFF;

Example #5)

Configuring Pins of Port 0 (PO.4 to PO.II) as Ouput and Setting them High: and Low

LPC _ GPIOOvFIODIR = OxFFO; II Config PO.0 to PO.7 as Ouput


hPC _ GPIOO->FIOSET = OxFFO; II 1111 1111 0000 Make output High for PO.4 to PO.ll
~pe_ffiPIOO->FIOCLR = II Make output LOW for PO.4 to PO.11
OxFFO;

Example #6)

Configuring Pins of Port 1 (P1.14 to PO.2I) as Input:


LPC GPIO I->FIODIR &= ~(OxFFO); II Config P 1.14 to P 1.21 as Input
LPC_GPIOI->FIODIR &=~(1«I4); I I only Pin p 1.14 is configured as input
Note: On reset by default all registers are zero. So all port's all the pins acts as input. We can skip
setting i/p lines

P 0_4

P112:1

Blink a LED

#include <Ipc 17xx.h>


int main( void)
{
LPC_GPIOO->FIODIR 1=(1« 4); II Configuring PO.4as ~
LPC_GPIOl->FIODIR &= ~ «(1« 21)); II explicitly making PO.21 as Input . we can skip this line

l/by default all pon pins are i/p


while(l)
{
if( I (LPC GPIOO->FIOPIN & (l«2I~ l!ifkey P1.21 pressed
{
LPC_GPIOO~SEq; 1=(1« 4); II SET PO.4 High LED ->ON
}
else
LPC_(iPIOO->FI~LR= (1« 4); II PO.4 low LED-> OFF
}
}
r
Lab Program # 1. Interfacing of "bE]}" _ 8 no's to a GPIO of Cortex M3 Controller

a. To blink LEDs

#include <LPC 17xx.n>:>


int maint)

{ ~->FIODIR~OXOFFO; IIPO.4-PO.ll pins as alp.


while(l) I!infinite loop
{
int i;
LPC _ GPIOO - >FIOSET = OxOFFO; II SET po.4 to pO.11 LEDS Turns ON
for (i=IOOOOO;i >0; i- -); II delay
LPC _ GPIOO - >FIOCLR = OxOFFO; Ilclear PO.4 to P.ll LEDS Turns OFF
for (i=IOOOOO;i>Oi;--); Iidelay
}
}
l.b to Scroll LEDs (Ring Counter)
#include <lpc I 7xx.h>
unsigned int x, y, z;
int main( void)
{
LPC _ GPIOO->FIODIR = II Configure PO.4 to pO.11 as Output
OxOFFO;
I!infinite loop
while(l)
{
z = Ox0800;
for (x=8; x> 0; x - - )
{
LPC_GPIOO - > FIOPIN = z;
for (y=1000000; y> 0; y- -);
z=z»I;
}
}
}

Lab Program # 2.a Interface a simple Switch and display its status through LED.

#include <LPC 17xx.h>


int maint)
{
II port PO.4 pin is configured as alp
I I port P 1.21 pin is configured as i/p

while (1) I I infinite loop


{
I I if switch P2.1 is pressed?

LPC_GPIOO->FIOSET = (1« 4); II if Yes, SET the Port PO.4 pin

LPC_GPIOO->FIOCLR= (1« 4); II Else Clear Port PO.4

}
}
}
2.b. Interface a simple Switch and display its status through Buzzer.

#include <LPC 17xx.h>

int maint)
{
LPC_GPI03->FIODIR = 1« 25; II port 3.25 pin is configured as alp
LPC_GPIOl->FIODIR & = ~ (1« 21); II port P 1.21 pin is configured as i/p

while(l)
{
if(! (LPC GPIOl->FIOPIN & (1« 21))) II if switch P .21 pressed
{

LPC_GPI03->FIOSET = (1« 25); II Port 3.25 pin is set [High]

}
else

{
~
LPC_GPI03->FIOCLR= (1« 25); II ~Pin is Clear fLowl

-.
}

}
}
2.c. Interface a simple Switch and display its status through Buzzer-,Relay and LED.

#inc1udc<LPCI7xx.h> ~
int maint)
{
LPC GPIOO->FIODIR = (1«4) I (l-t::<25); II port PO.4-PO.ll[LEDS] & PO.25[Relay] config as alp
LPC_GPI03->FIODIR = (1«25); II port 3.25[Buzzer] configured as alp
LPC_GPIOl->FIODIR &= ~(1«21); I I port P 1.21[Switch KEY] configured as i/p

while(l)
{
& (1«21))) I I if switch P 1.21 pressed

{
LPCt_GPIOO->FIOSET= (1«4) I (1«25); II tum on LED, RELAY

Iitum on Buzzer
}

LPC_GPIOO->FIOCLR= (1« 4) I (1« 25); II tum OFF LED, Relay


LPC_GPI03->FIOCLR= (1« 25); IItum OFF Buzzer
}
}

Normally
Open (NO)
Embedded Controller Lab Manual 15ECL67

Applications of Relay

• Commonly used in used in switching circuits.


• For Home Automation projects to switch AC loads
• To Control (On/Off) Heavy loads at a pre-determined time/condition
• Used in safety circuits to disconnect the load from supply in event of failure
• Used in Automobiles electronics for controlling indicators glass motors etc.
An_O_de_--Ir)1:» c_a_thode

n1)) l))
Vss

Buzzer Symbol Light Emitting DiQoe

LPC1768: External Interrupts _ ~


EINTxPins ~

LPCl768 has four external interrupts EINTO,EINTI, EINT2, EIN~I:3.


As LPCl768 pins are multi functional, these four interrupts are avJlable on multiple pins.
Below table shows mapping ofEINTx pins.~

LPC1768External Interrupts
'Table 83,. Pin .undlon select regisler',4 (PINS'EILAa·ddress IOdOO:2 CD1:'Ob'!Ill d'escllilp!I'on
I"IINSEU I"Iln Functionwhen F'lInctlonwll.enD1 FlinGiion when 1D FunGllonw,hen Resel
"arne DO 1t ·..;.li:lle
1:0 P2.0 GPIO Port .2.0 PWM1j
J,:2 P2.1 GPIO Port .2.1 PWM1.2
5:4 P2.2 GPIO Port .2.2 PWM1.3
7:6 P2.3 GPIO Port .2.3 PWM1,4
9:1l P2.4 GPIO Port 2.4 PWM1.5
11:10 P2.5 GPIO Port .2.5 PWM1.6
13:12 P2.6 GPIO ,PtJrt.2:6 PCAPUJ
15:14 PL7 GPIO Port .2.7 RD2
17:16 P2.8 GPIO PtJrt.2.8 TD2
19:18 P2.9 GPIO Port 2.9 USB_<cONNECT
2.1:20 P2.W GPIO Port 2.10 EINiO
23:22 PZ.11!.:!] GPIO Port2.11 EINi1
25:24 P2.tzl!:!.l GPIO Port 2.12: EINI2:
2:7:26 P2.131:!.1GPIO Port2.1J, EINI1l,
'1I.'1I-"JJ:I! IJ:;IIoI:!iC'.£:Io'''''i'.i:.,M ~~.·l:ki:orIjr.:uri

EINT Registers

The registers associated with LPC1768 external interrupts,

I Register II Description I

IpINSELX ITo configure the pins as External I~ruPts Y

~ External Interrupt Flag Regist~tai~terruPt flags for EINTO,EINTl, EINT2 &


L j EINT3, '-I
IEXTMODE IExternal InterruPt;g.d~ister(Level/Edge Triggered)

IEXTPOLARIExternal Interrupt P0\~~'a1l1ng/RiSing Edge, Active LowlHigh)

I EXTINT I

I 31:4 II 3 II 2 II 1 II ° I
~,k~==RE=giFE=R=V;=E=D======IE~1=IN=T=3=~11 EINT2 II EINTI I~=I =EIN=T=o=~I'

A~" Bits will be set whenever the interrupt is detected on the particular interrupt pin.
I~l1e interrupts are enabled then the control goes to ISR.
Writing one to specific bit will clear the corresponding interrupt.
EXTMODE
I I
131:4 112 III 11°
113 I
IRESERVED IIEXTMODE3 IIEXTMODE2 IIEXTMODE1 IIEXTMODEo
I

D~n~ 17
EXTMODEx: This bits is used to select whether the EINTx pin is level or edge Triggered
0: EINTx is Level Triggered.
1: EINTx is Edge Triggered.

EXTPOLAR

31:4 3 2 1 o

IRESERVED IIEXTPOLAR3 IIEXTPOLAR2 IIEXTPOLARI IIEXTPOLARO

EXTPOLARx: This bits is used to select polarity(LOWIHIGH, FALLING/RISING) of the EINTx interrupt
depending on the EXTMODE register.

0: EINTx is Active Low or Falling Edge (depending on EXTMODEx).


1: EINTx is Active High or Rising Edge (depending on EXTMODEx).

Steps to Configure Interrupts

1. Configure the pins as external interrupts in PINSELx register. ~


2. Clear any pending interrupts in EXTINT.
3. Configure the EINTx as Edge/Level triggered in EXTMQDE register.
4. Select the polarity(Falling/Rising Edge, Active Low/1::Iigh) of the interrupt in EXTPOLAR register.
5. Finally enable the interrputs by calling NVIC_EnableIRQO witl1 IRQ number.

3. a.Demonstrate the use of an external inte ;r~EINTO to toggle an LED -ON/OFF.


#include <lpc 17xx.h>
void EINTO IRQHandler(void)

r:
{
LPC_SC->EXTINT = 1; /* Clear Interrupt Flag ext int 0 */
} LPC_GPIO A ~ (1¥<4); /* Toggle the LEDI everytime INTRO is generated */

int main( ) '-.)'


{
/* Clear Pending interrupts */
/* Configure P2 _l 0 as EINTO */
/* Configure EINTx as Edge Triggered*/
LPC SC->EXTPOLAR = 1; /* Configure EINTx as Falling Edge */
LPC_GPIOO->FIODIR = (1«4); /*configure LED pins as OUTPUT */
LPC _ GPIOO->FIOPIN =

OxOO; NVIC _ EnableIRQ(EINTO /* Enable the EINTO interrupts */


_IRQn); while(l)
{ // any main program running
}
}
3. b.Demonstrate the use of an external interrupt EINTI to toggle an LED On/Off

#include <lpc I 7xx.h>


void EINTI IRQHandler(void)
{
LPC_SC->EXTINT = 2; /* Clear Interrupt Flag ext int I */
LPC_GPIOO->FIOPIN 1\ = (1«11); /* Toggle the LEDI everytime INTRI is generated */
}
int main()
{
LPC_SC->EXTINT = 2; /* Clear Pending interrupts */
LPC_PINCON->PINSEL4 = (1« 22);
LPC SC->EXTMODE = I ;
LPC SC->EXTPOLAR = I; /* Configure EINTx as Falling Edge "'£/
LPC_GPIOO->FIODIR = (1«11);
LPC _ GPIOO->FIOPIN =

OxOO; NVIC _
EnableIRQ(EINTI_IRQn); whilet l )
{
}
}

#include <lpc I 7xx.h>


void EINTO IRQHandler(void)
{
/* Clear Interrupt Flag ext int I */
/* Toggle the LEDI everytime INTRI is generated */
}

{
/* Clear Interrupt Flag ext int I */
LPC GPIOO->FIOPIN 1\ = (1« II); /* Toggle the LEDI everytime INTRI is generated */

int main()
{
LPC_SC->EXTINT = 3; /* Clear Pending interrupts */
LPC_PINCON->PINSEL4 = (1« 20) I (1« 22); /* Configure P2 _I 0 as EINTO I */
LPC SC->EXTMODE = I ; /* Configure EINTx as Edge Triggered*/
LPC SC->EXTPOLAR = I; /* Configure EINTx as Falling Edge */
LPC_GPIOO->FIODIR = (1« 4) I (1« 11);
/*configure LED pins as OUTPUT */
LPC _ GPIOO->FIOPIN = OxOO;
NVIC _ EnableIRQ (EINTO_IRQn); /* Enable the EINTO interrupt */
NVIC_EnableIRQ (EINTl_IRQn); while(l) /* Enable the EINTI interrupt */
{
} // any main program running
}

UART module

UART module and registers. LPC1768 has 4-UARTs numbering 0-3, similarly the pins are als0 named as RXDO
RXD3 and TXDO-TXD3.As the LPC1768 pins are multiplexed for multiple functionalities, first they have to be
configured as UART pins.
Below table shows the multiplexed UARTs pins.

~
UART Registers ~

The below table shows the registers associated with LPC1768 UAR yT
IRegister IIDescriPtion

lI:contains the recently re;e~~ ~~


II~

II~ II:contains th~at~~.~ transmitted!

IFCR FIFO
II t... contro~~e.e
;-r
~ ..
,
Controls the UART frame formatting(~umber of Data Bits, Stop bits)]
II~ II" A

IDLL 0e~cant Byte of the UART baud rate generator value.

IDLM Most Significant Byte of the UART baud rate generator value.
~
JI

Now lets see how to configure the individual registers for UART communication.

FCR (FIFO Control Register)

LPC1768 has inbuilt 16byte FIFO for Receiver/Transmitter. Thus it can store 16-bytes of data received on UART
without overwriting. If the data is not read before the Queue(FIFO) is filled then the new data will be lost and the
OVERRUN error bit will be set.
FCR
I 31:8 II 7:6 II 5:4 II 3 II 2 II 1 II 0 I
IRESERVEDIIRXTRlGGERJIRESERVEDIIDMAMODEIITXFIFO RESETIIRXFIFO
RESETIIFIFOENABLEI

Bit 0- FIFO:
This bit is used to enable/disable the FIFO for the data received/transmitted.
O--FIFOis Disabled.
I--FIFO is Enabled for both Rx and Tx.

Bit 1-RX FIFO:


This is used to clear the 16-byte Rx FIFO.
O--Noimpact.
l--CLears the 16-byte Rx FIFO and the resets the FIFO pointer.

Bit 2 - Tx FIFO:
This is used to clear the 16-byte Tx FIFO.
O--Noimpact.
l--Clears the 16-byte Tx FIFO and the resets the FIFO pointer.

Bit 3 - DMA MODE: ~


This is used f~r EnablinglDisabling DMA mode.
O--Disablesthe DMA.
l--Enables DMA only when the FIFO(bit-O)bit is SET. ~

Bit 7:6 - Rx TRIGGER:


This bit is used to select the number of bytes of the receiver data to be written so as to enable the interruptiDMA.
00-- Trigger level 0 (l character or OxO1)
01-- Trigger level 1 (4 characters or Ox04) ~
10-- Trigger level 2 (8 characters or Ox08)
11-- Trigger level 3 (14 characters or OxOE)

LCR (Line Control Register)

LCR

Word Length
IReserved Select
ISetas->

Bit 1:0 - WIJS>: WordLenghtSelect


Il'hesetwo bits are used to select the character length
0,0--5-bit character length
Q 1-- 6-oit character length
10-~7-bit character length
1-- 8-bit character length

Bit 2 - Stop Bit Selection:


This bit is used to select the number(1I2) of stop bits
0-- 1 Sto bit
1-- 2 Stop Bits

Bit 3 - Parity Enable:


This bit is used to Enable or Disable the Parity generation and checking.
0-- Disable p-arity generation and checking.
1-- Enable parity generation and checking.

Bit 5:4 - Parity Selection:


These two bits will be used to select the type of parity.
00-- Odd p'arit . Number of Is in the transmitted character and the attached parity bit will be odd.
01-- Even Parity. Number of Is in the transmitted character and the attached parity bit will be even.
10-- Forced "1" stick parity.
11-- Forced "0" stick parity

Bit 6 - Break Control


0-- Disable break transmission.
1-- Enable break transmission. Output pin UARTn TXD is forced to logic 0

Bit 8 - DLAB: Divisor Latch Access Bit


This bit is used to enable the access to divisor latch.
0-- Disable access to divisor latch
1-- Enable access to diviso~ latch

~
LSR (Line Statns Register) ~
The is a read-only register that provides status information of the U~RT TX and RX blocks.

LSR

1 31:8 IDDDDDDDD
IReserved JIRXFjNITEMT IITHRE 1~~lpE I[Q[J~

Bit 0 _ RDR: Receive Data Ready V ~

This bit will be set when there is a received data in RBR register. This bit will be automatically cleared when RBR
is empty.
0-- The UARTn receiver FIFO is emg:ty.
1-- The UARTn receiver FIFO is not emp-ty.

The overrun error condition is set when the UART Rx FIFO is full and a new character is received. In this case, the
UARTn RBR FIFO will not b€ overwritten and the character in the UARTn RSR will be lost.
0-- No overrun
1-- Buffer over run

Bit 3 - FE: Framing Error


T1iisbit
;'
is set. when there is error in the STOP bit(LOGIC 0)
0-- No Frammg Error
1-- Framing Error

Bit 4 - BI: Break Interrupt


This bit is set when the RXDn is held in the spacing state (all zeroes) for one full character transmission
0-- No Break interrupt
1-- Break Interrupt detected.
Bit 5 _ THRE: Transmitter Holding Register Empty
THRE is set immediately upon detection of an empty THR. It is automatically cleared when the THR is written.
0-- THR register is Empty
1-- THR has valid data t-o"-.o:b-e-t-ra-n-sm--:"-itt-e-:i(j

Bit 6 _ TEMT: Transmitter Empty


TEMT is set when both UnTHR and UnTSR are empty; TEMT is cleared when any of them contain valid data.
0-- THR and/or the TSR contains valid data.
1-- THR and the TSR are empty.

Bit 7 _ RXFE: Error in Rx FIFO


This bit is set when the received data is affected by Framing Error/Parity Error/Break Error.
0-- RBR contains no UARTn RX errors.
1-- RBR contains at least one RX error.

TER (Transmitter Enable register)


This register is use d t o Ena bl eID'isa bl e th e t
ransrmssion
~
TER

31:8 7 6-0
I II II
Reserved TXEN ~~served
I II II
, I

B;t 7 - TXEN: Trsnamitter Enable ~


When this bit is 1, the data written to the THR is Qutput on the TXD pin.
If this bit is cleared to 0 while a character is being sent, the transmission of that character is completed, but no
further characters are sent until this bit is set again.
In other words, a 0 in this bit blocks the transfer of characters .

Baudrate calcularc' '\.

LPCl768 generates the baud rate depending on the values ofDLM,DLL.


Baudrate = PCLKI (16 * (256 * DLM + DLL) * (1+ Divaddval/Mulval)

Getting tHe ~eL;K value.


PCLKSELx registers contains the PCLK info for all the clock dependent peripherals in which Bit6,Bit7 contains
the Uart ClocF(le.UART_PCLK) information.
The UART_PCLK and the actual Peripheral Clock(PCLK) is calculated as below.
~Refer data sheet for more info)

UART PCLK PCLK

o System Freqj4

1 System Freq

2 System Freqj2

3 System Freqj8
DivAddVal/MulVal == 0

Using the above parameters, DLLlDLM is calculated as below.


(256 * DLL + DLM) = PCLK / (16* Baudrate).

'SiillTIltgjlleUAlRT .P.arcke·tt

X X X
(0
..
'Stalritt iB itt
IDJlata IB·i·ts5: -8

IOpt i'I!!J'1aiIlii IIP'aniit:y'


Bi-itt
f
P

StOlP
'ill)

*B"":

Steps for Configuring UARTO

Below are the steps for configuring the UARTO. ~

1. Stepl: Configure the GPIO pin for UARTOfunction using PINSEL register.
2. Step2: Configure the FCR for enabling the FIXO and Reste both the RxlTx FIFO.
3. Step3: Configure LCR for 8-data bits, 1 Stop bit, Disable Parity and Enable DLAB.
4. Step4: Get the PCLK from PCLKSELx register 7-6 bits.
5. Step5: Calculate the DLM,DLL vaues for required baudrate from PCL\. ~
6. Step6: Updtae the DLM,DLL with the calculated values. y
7. Step6: Finally clear DLAB to disable the access to DLM,DbL.

After this the UART will be ready to Transmit/Receive Data at t~e-i£ied baudrate.

'1iallle 1!1. 1',11111 'fLlI1lc:1Jlo:nselect re>lJls~eli' III (PIINSEIl.:IlI ~ a.dllllllellS !i!liK41l111C1O2 IllIII. bill: d'e'SiCli',lp~IDClIiII
IPiINSELO III'n FuncUo:n whenl FilincOlon 'li!II.en Oil FuniCtlo:n Funetlo:n Reset
n:ame '001 wll.enl iNI '1i!IIIl:in'fit '1'81:"1:(
1:01 IPOJ) G!PiIO IPc!rit 00.0 RD1 TXD3 8DA.1
31:2: IPR1 GPIIO IPc!rit '0.1 TID1 R.XIDG 8QU 00
,5::4 IPR:2: GPIIO IPc!rit 112 IXID!) ADO.l Reserved
1:6 IPR~ GlPlIO IPc!ri,t 113 IRXD!) ADO ..6 Reserved
9r:tli PR«!J G!PlIO IPc!rit 114 112'SiRX_CILJIK RU2 GAIP.2,Q
111:10 IPO.,5[!] G!PIIO IPc!ri,t 0.5 11.2'S!RX_WS Tn2 GA1P.2.'1
13:~2 IPO.6 G!PIIO PcirI: 116 112BIRX_SnA .s8EL~ MAI2:,O
15:14 IPR7 G:PlIO POOl: 0.1 112SIX,_(::lK SOIK1 MAlIi.2~1
l1:Ui IPIJI.~ G:PlIO IPc!ri t 1JI.8
,
112SIX_WB MI801 MAiIi.2~2:
19:18 IPIJI.9' G!P,IO PcirlIl9 112:8:rX,-,~mA 'MOO111 MAT2:.,~

:2:1:20 PO. 1II] G!PIIO PcirI 0.10 IXID!2 .sDA2 MAI3 ..0
23:22 IPo.H GPIIO PcirI 0.11 1R'KD.2 S012 MA:ra.1
:29:24 Reserved IRes'eFVl8d iR.eseNed Reserved
3~:30 IPO.i5 G!PlIO IPc!rit 0.15 IXm SOIKO SOIK

4 .Usage ofInternal UART.

I. To transmit a single character data from Host to UART.


II. To receive a single character data from UART to Host.
Ill. To transmit a string of character data from Host to UART
#inelude "LPC l Zxx.h''

void UARTO Init (void)


{
LPC_PINCON->PINSELO 1=(l «4)1 (l «6); 1* Pin PO.2 used as TXDO & Pin PO.3 used as RXDO I
LPC_UARTO->LCR = Ox83; 1* 8 bits, no polarity, lstop bit *1
LPC_UARTO->DLM = 0;
LPC_UARTO->DLL = 9; II 115200 baus rate @25MHz elk
LPC_UARTO->LCR = Ox03; 1* Lock the baud rate *I
LPC_UARTO->FDR = Ox21; IIMULVAL=2,DIVADDval=1
}

int UARTO SendChar (int Data)


{
while (!(LPC UARTO->LSR & Ox20)); llifLSR5th bit =0 wait for valid data.
return (LPC UARTO->THR = Data); II LSR5th bit = I ,THR has valid data to bel....t-ra-n-sm---:-itt-e-:l

int UARTO GetChar (void) IILSR line statu, register ~


{
while (!(LPC UARTO->LSR & OxOI));

return (LPC UARTO->RBR); IIIfLSRO bit=l tlART receiver not empty. Send it to RBR
}

vOidUARTO _ SendString (unsigned char ,s~

while (*s != 0) II if content of string is not 0


UARTO SendChar(*s++); Iisend char and auto increment i.e
}

int main( void)


{
char ch;
SystemInit( ~
UARTO Init(); llinitialize UARTO
UARTO_SendString("hello world! "); Iistring=hello world!
while(l){
Cfi=UARTO GetChar(); I I read character into ch.
U~R.?fO SendChar(ch); Iisend to uart terminal
} ~_~

L
Tl!
11iCfO C ontrollcr M.AJ( r--IL--
Rl UJ..RT
232
LPC 1768 r--BL--

_[
LPC1768 PWM Module

LPC1768 has 6 PWM output pins which can be used as 6-Single edged or 3-Double edged. There as seven match
registers to support these 6 PWM output signals. Below block diagram shows the PWM pins and the associated
Match(Duty Cycle) registers.

E:JI I
Associated Corresponding
PWM Channel Pin Functions
PINSEL Register Match Register

Ec:J
~
0,1 bits of
O-GPIO, I-PWMl[l], 2-TXD1, 3- MRI ~

I~
PINSEL4

Ec:J
~

O-GPIO, I-PWMl[2], 2-RXD1, 3-


2,3 bits of <\
PINSEL4 f\-MR2

Ec:J O-GPIO, I-PWMI [3], 2-CTS 1, 3-


TRACEDATA[3]
4~ bits of
Prnyl'i4
MR3

Ec:J O-GPIO, I-PWMl[4],


TRACEDATA[2]
2-DCD1, 3~
~
6,7 biiirof
I~PINSEL4
MR4

Ec:J
Bc:J .
O-GPIO, I-PWMI [5], 2-DSR1, 3)
TRACEDATA[l]JI(

O-GPIO, I-P~C1RI'
TRACEDATA[0]~
3-
8,9 bits of
PINSEL4

10,11 bits of
PINSEL4
MR6

LPC7168 PWM Registers ;~

The below table shows the registers associated with LPC1768 PWM.

D
j,.._

I Register II Description
I
Interrupt ROg'lster,Jn,e IR can be read to identify which of eight possible interrupt sources arc pending.
Writing Logic-l will clear the corresponding interrupt.
~
~ \('e~ontrol Register: The TCR is used to control the Timer Counter functions(enable/disable/reset).

~ ~ Tiliier Counter: The 32 -bit TC is incremented every PR +1 cycles of PCLK. The TC is controlled
A through the TCR.
~
~ Prescalar Register: This is used to specify the Prescalar value for incrementing the TC.

D
Prescale Counter: The 32-bit PC is a counter which is incremented to the value stored in PR. When the
value in PR is reached, the TC is incremented.

EJ
Match Control Register: The MCR is used to control the reseting ofTC and generating of interrupt
whenever a Match occurs.

D~n~ ')t:;:
~ Match Register: This register hold the max cycle Time(Ton+ Toff).

~ Match Registers: These registers holds the Match value(PWM Duty) for corresponding PWM
L:: j channels(PWM1-PWM6).

EJ
PWM Control Register: PWM Control Register. Enables PWM outputs and selects PWM channel types
as either single edge or double edge controlled.

~ Load Enable Register: Enables use of new PWM values once the match occurs.

Register Configuration

The below table shows the registers associated with LPC1768 PWM.

TCR

31:4 3 2 1 o

Reserved PWM Enable Reserved Counter Enable

Bit 0 - Counter Enable


This bit is used to Enable or Disable the PWM Timer and PWM Prescalar Counters
0- Disable the Counters ~
1- Enable the Counter incrementing.

Bit 1- Counter reset


This bit is used to clear the PWM Timer and PWM Prescalar Counter values.
0- Do not Clear.
1- The PWM Timer Counter and the PWM Prescale Counter are synchronously reset on the next positive edge of
PCLK.

Bit 3 - PWM Enable

l'-l'
~
Used to Enable or Disable the PWM Block.
0- PWM Disabled
1- PWM Enabled

MCR

PWMMRxI
This bit is used to Enable or Disable the PWM interrupts when the PWMTC matches PWMMRx (x:0-6)
0- Disable the PWM Match interrupt
1- Enable the PWM Match interrupt.

PWMMRxR
This bit is used to Reset PWMTC whenever it Matches PWMRx(x:0-6)
0- Do not Clear.
1- Reset the PWMTC counter value whenever it matches PWMRx.

PWMMRxS
This bit is used to Stop the PWMTC,PWMPC whenever the PWMTC matches PWMMRx(x:0-6).
0- Disable the PWM stop 0 match feature
1- Enable the PWM Stop feature. This will stop the PWM whenever the PWMTC reaches the Match register value.

I I
peR

I 31: 15
II
PWMENAI
14-9
I~I 6-2

PWMSEL2
I~
E
PWMENA6- PWMSEL6-
I Unused lunusedl

PWMSELx "
This bit is used to select the single edged and double edge mode form PWMlX (x:2-6)
0- Single Edge mode for PWMx
1- Double Edge Mode for PWMx.

PWMENAx
This bit is used to enable/disable the PWM output for PWMx(;x: 1-6)
0- PWMx Disable.
1- PWMx Enabled.

A
LER

31-7

Unused

LENx
This bit is used EnablelDisable the loading of new Match value whenever the PWMTC is reset(x:0-6)
PWMTC will be continously incrementing whenever it reaches the PWMMRO, timer will be reset depeding on
PWMTCR configuratcn, Once the Timer is reset the New Match values will be loaded from MRO-MR6 depending
on bits set in this register.
0- Disable the loading of new Match Values
1- Load tl1e new Match values from MRx when the timer is reset.

The TC is continuously incremented and once it matches the MRl(Duty Cycle) the PWM pin is pulled Low. TC
still continues to increment and once it reaches the Cycle time(Ton+ Toff) the PWM module does the following
things:

• Reset the TC value.


• Pull the PWM pin High.
• Loads the new Match register values.
Summary ofPWM operations for the above image:

• Slidel: The TC is being incremented as per the Pre-scalar configuration. The PWM output is high as the
TC is still less that duty cycle.
• Slide2: TC is incremented to 40 and still the PWM pin as HIGH.
• Slide3: TC is incremented to 60 and it matches the Duty Cycle(MRl =60).
• Slide4: Now the Comparatorl(Green) will trigger the R of SR latch and Pulls the PWM output to
Zero(Q=O).TC still continues to increment.
• Slide5: TC is incremented to 80 and PWM pin is low as TC > Duty Cycle.
• Slide6: Now TC is 100 and it matches the Cycle time(MRO==lOO).
• Slide7: Now the Comparator2(Red) will trigger the S of SR latch and pulls the PWM output to
ONE(Q==l). It also resets the TC to zero. It updates Shadow buffers with new Match values from
MRO,MRI.

Steps to Configure PWM

1. Configure the GPIO pins for PWM operation in respective PINSEL register.
2. Configure TCR to enable the Counter for incrementing the TC, and Enable the PWM li1ock.
3. Set the required pre-scalar value in PR. In our case it will be zero.
4. Configure MCR to reset the TC whenever it matches MRO. ~
5. Update the Cycle time in MRO. In our case it will be 100. L. ~

6. Load the Duty cycles for required PWMx channels in respective match registers MRx(x: 1-6).
7. Enable the bits in LER register to load and latch the new <matchvalues.
8. Enable the required pwm channels in PCR register.

Tallile 8:4,.
~
..~ ......
P,ln 'Iu,nctlo:n select Fell Isler l' (PI,NiBE,n·· 3,dillll'e~iSO!!l400r.C! O~iiI:t)I!1 d escrilpUon
IP,INSEU Plnl F:undf:onl 'whe,n ,Fu,nlrtlo:n Fu,nc:ilcm F'lIn.dflOnl Reset
nlame 01) when, '011 wh,en'110 when 11 valu;e
17:0 IReserved Resel'!led Rle>served IRese'rved

19:18 P:l25l!.l GPIO Port.3.2. 5


PWM1.2 011
Resell1ed
MAiI'O.1 IPWM1.3 011
21:20 PJ.26l!l GPIO Port~I.26 STCLJK
Reserved
:,j,1:22 Reserved Re·sel'led

IIProgram PWM Demo on Scop.€

5. Usage ofInternal PWM to generate PWM and vary its duty cycle

#include <lPC17xx.h()'
int main(void)
{
int j,DutyCycle;
LPC_PINCON->PINSEL7 = 3« 20; 1* Cofigure pin P3.26 for PWM mode.
LPC_PWMJ->TCR = (1« 0) I (1« 2); *1 lienable counter and PWM
LPC_P,\~l-::;;MCR= (1« 1); I*Reset on PWMMRO,reset TC if it matches MRO *1
LPC PWM1-)!MRO= 100; 1* set PWM cycle(Ton+Toff)=lOO) *1
LPC__PWMv t>PCR = 1 « 11,' 1* Enable the PWM output pin for PWM_3 *1

}
}
duty cycle =
tON + tOFF
tON = ON time
tOFF = OFF time 25% duty cyde
tON + tOFF = Time period

LPC1768 DAC Programming Tutorial

VREFP---- ......
VREFN---""". ~
b0 ~~--~
bl--Jtr.
bz--.... DAC
bn -- .... '----- _/

Tabh: 80,; Pin function seleGt rellisler11 (PINJ!EU· ad.dress 01l40D2 COMI b11 descrlpUon
PINSEL1 Pin n'ame Fllllltiion when IFunctlon Fu!ncllon Fundlon Reset
00 wilen. 011 wilen to when 11 value
to PO.16 GPIOPortl).16 RXD1 SSELO SSEL QlD

12 PO.H GPIO Port I). 17 CTSl MISO() MISO OlD

54 PO.18 GPIO Portl).lB DCm MOSI(j MOSI OlD

76 PO.19l!1 GPIO Port 1).19 DSRl Res8IVed SDM iJlD

9:8 PO.2ol!l GPIO Port (1.20 DTR1 R:es8IVed scu QlD

(131
11:10 p(J.21'ill GPIO Port (1.21 Rll Reserved 'RDl OlD

P(J.22 GPIOPort022 Rm1 Reserved TD1 (lID

15:14 flO.23L!1 GPIO PortO.23 ADQI.O 128RX_GLK CAlfl3.0 OlD

17:16 flO ..24ill GPIO Port (1.24 AOO.l 12SRX_WS GA1fl3.1 OlD
19:18 PO.25 GPIO Port 0.25 ADO.2 128RX,-SDA TXm 00
21:20 flO.26 GPIO Port 0.26 AO!JlT RXID3 00
AD·O.3I.
23:22 PO.27L!Jlgj GPIO Port 0.27 SDAO 'USB_SnA Reserlied OlD

25:24 PO.2aL!Jlgj GPIO Port 0.28 SOLO 'USB_SeL Reserlied OlD


~
LPC1768/LPC1769 DAC Block

ARM Cortex-M3 LPC176x MCUs incorporate a 10 bit DAC and provide buffered analog output. As per the
datasheet, it is implemented as a string DAC which is the most simplest form of DAC consisting of 2Nresistors in
series where N = no. of bits which simply forms a Kelvin-Varley Divider. LPC176x DAC has only 1 output pin,
referred to as AOUT. The Analog voltage at the output of this pin is given as:

VAOUT = VALUE * (VREFP-


VREF1N0)2/4

When we have VREFN= 0, the equation boils down


to:
VAOUT = (VALUE * VREFP)1l024

Where VALUE is the 10-bit digital value which is to be converted into its Analog counterpart and VREFis the
input reference voltage.

Pins relating to LPC1768 DAC block:


Pin Description
AOUT Analog Output pin. Provides the converted Analog signal which is referenced to "¥sSA: i.e. tn€
(PO.26) Analog GND. Set Bits[2l:20] in PlNSELl register to [10] to enable this function.

These are reference voltage input pins used for both ADC and DAC. VREEP is positive
VREFPV, REFNreference voltage and VREFNis negative reference voltage pin. In example shown
below we will use VREFN=OV(GND).

VDDA is Analog Power pin and V SSA is Ground pin used to power the ADC module. These are
generally same as Vee and GND but with additional filtering to reduce noise.

DAC Registers in ARM Cortex-M3 LPC176x

The DAC module in ARM LPC1768/LPC1769 has 3 register~iz. BitCR, DACCTRL, DACCNTVAL. In this
tutorial we will only go through to DACR register since the other 'two are related with DMA operation, explaining
which is not in the scope of this tutorial. Just note that DMA is used to update new values to DACR from memory
without the intervention of CPU. This is particqlarly useful when generation different types of waveforms using
DAC. We will cover this in another tutorial.

Also note that the DAC doesn't have a power control it in PCONP register. Simply select the AOUT alternate
function for pin PO.26using PlNSELl register to enable DAC ouput.

The DACR register in LPC1748

The field containing bits [15:6] is used ro feed a digital value which needs to be converted and bit 16 is used
to select settling time. The bit significance is as shown below:

1. Bit[S:O]: Reserved.
2. Bit[lS:6] - VA~UE starts from bit 6 [ In programming we use Value «6; ]
3. Bit[16] - BIAS: Setting this bit to 0 selects settling time of Ius max with max current consumption of
7D'OuAat max l Mhz update rate. Setting it to 1 will select settling time of 2.5us but with reduce

[)!:
max current consumption of 300uA at max 400Khz update rate.
4. Bits Fl]: Reserved

,
!VRHP
!VREFN

PO.26 (AOUT)

lPC176x [OSO]
Embedded Controller Lab Manual 15ECL67

6a.lnterface a DAC and generate Triangular and Square waveforms.

#include <LPC 17xx.H


int main (void)
{
int i, m;
LPC_PINCON->PINSELl = (1« 21); IISelect AOUT function for P0.26
while(l)
{
for (i = 0; i <= 1023; i++) Iisend value start from 0 to 1023 insteps of' 1
{
LPC_DAC->DACR = (i « 6); II DACR register valne sncmldplaced in 15:6
for(m = 10,' m> l', m--)', Iidelay to vary freq
}
For(i=1023; i>O; i--)
{
LPC_DAC->DACR = (i « 6);
for(m = 10,' m> l', m--)',
}
}

6.h. Interface a DAC and generate Square w~s.

#include <LPC 17xx.H>

int main (void)


{
int i;

IISelect AOUT function for P0.26

while (1)
{
LPC_DAC -> DACR= (1024« 6); II l Obit= 1024 Vmax = 3.3 V
for (i = 120000; i > 1; i--); II maintain this value for some delay

LPC_DAC -> DACR = (512« 6); II for VmaX/2= 1.74V


for (i = 120000; i > 1; i--); II delay
}
STEPPPER MOTOR INTERFACE
P1I22 iC'i1 out 1

LPC 1",62 P1I_,23' it:'.l:2 out:2


P1_24 1.3 (lut3
P1_25 1.4 0...14
IJll>J2SQ3A
106 outti

Stepper Motor Configuration: ~

A stepper motor is a special type of electric motor that moves in increments, or steps, rather than turning
smoothly as a conventional motor does. Typical increments are 0.9 or l.8 degrees, with 400 or 200 increments
thus representing a full circle. The speed of the motor is determined by the time delay between each incremental
movement.

U8 is a Driver Buffer (ULN2003) device connected to LPC-176!./3Device and can be used for driving
Stepper Motor. On the LPC-1768, P 1.22 to P 1.25 is used to generate the pulse sequence required to run the
stepper Motor. Also, the Stepper Motor is powered by its elwn power supply pin (COM), which is connected to
a l2V supply.
Table shows connections for stepper Motor.
Stepper Motor Pin connectio
n~lp"
~ Stepper LPC-1768 LPC-1768
Motor Coil Pin No Port No
I'
A 39 Pl.22
B 37 Pl.23
C 38 Pl.24
D 39 Pl.25

P1.25 P1.24 P1.23 P1.22 Stepper motor


1 0 0 0 rotates Clockwise
0
0
0
1 1
0
0
0
1
0
0
0
1

P1.25 P1.24 P1.23 P1.22 Stepper motor rotates


1 0 Anti 0
Clockwise
0
0
0
1
0
1
0
1
0
0
0
0
0
1
7.a. Interface a Stepper motor and rotate it in clockwise direction.

#include <LPC 17xx.H>

int main (void)


{
unsigned int k, z;
LPC_GPIOl->FIODIR = (1« 22)1(1« 23)1(1« 24)1(1« 25); liP 1.22 to P 1.25 CONFIG AS
OIP
while (1)
{
k = Ox02000000; I!initially P .25 = 1 [ 1000 ]
for(z=O;z<4; z++) I I four coils to be made high one by one
{
LPC_GPIOl->FIOPIN =k;
for ( i= 120000; i >0 ; i-- )
; k==k>»L;
}
}
}

~
7.b. Interface a Stepper motor and rotate it in anti-clockwise direction.

#include<LPC17xx.H> ~

int main (void) ~


{
unsigned int i k, z;
LPC_GPIO l->FIODIR = Ox03COOOGO; II alternate way. To make P1.22 to P1.25 config. as o/p,

I I initialize p 1.22 as high [0001]


I I executes 4 times

Ilport 1 pins assigned with k value


Iidelay
II rotate left shift by 1 [0010], [0100], [1000]

}
}

~
8.Interface and Control a DC Motor.
a. Clock wise Direction

#include <Ipc 17xx.h>


int maint)
{
LPC _ GPI02->FIODIR = (1«8); IIConfigure the PORT2 pins as OUTPUT
LPC _ GPI04->FIODIR = (1«28)1(1 Ilconfigure port4 pins p4.28,p4.29 as output
«29);

while(l)
{
LPC _ GPI02->FIOSET=(1 «8); lienable DC motor by making P2.8=1
LPC_GPI04->FIOSET = (1«28); II P4.28 =1
LPC_GPI04->FIOCLR= (1«29); II P4.29 = 0
}
}

b. Anticlockwise Direction
#include <lpc 17xx.h>
int maint)
{
LPC _ GPI02->FIODIR = (1«8); IIConfigure the PORlf2 pins as OUTPUT
LPC _ GPI04->FIODIR = (1«28)1(1 Ilconfigure port4 pins ~8'P4.29 as Input
«29);

while(l)
{
LPC _ GPI02->FIOSET=(1 «8);
LPC_GPI04->FIOCLR= (1«28);
LPC_GPI04->FIOSET = (1«29); clockwise rotation
}
}
c. Control DC motor using switches.
#include <lpc 17xx.h>
int maint)
{
LPC _ GPI02->FIODIR = (1~); IIConfigure the PORT2 pins as OUTPUT
LPC _ GPI04->FIODIR = (1«28)1(1 Ilconfigure port4 pins p4.28,p4.29 as Input
«2j;)~ Ilconfig all the pins of Port 1 as i/p
LPC _ GPIO l->FIODIR= 00;
while(l)
{
lienable DC motor by making P2.8=1

II P4.28 =1
II P4.29 = 0 DC motor Clockwise rotation

LPC_GPI04->FIOCLR= (1«28); II P4.28 = 0


LPC_GPI04->FIOSET = (1«29); II P4.29 =1 Anti-clockwise rotation
}
if(! (LPC GPIOl-> FIOPIN & (1«19)))
{
LPC_GPI04->FIOSET = (1«28); II P4.28 =1
LPC_GPI04->FIOSET = (1«29); II P4.29 = 1 DC motor Stops rotating.
}
}
}
DC Motor Pin Configuration

DC (direct current) motor rotates continuously. It has two terminals positive and negative. Connecting DC
power supply to these terminals rotates motor in one direction and reversing the polarity of the power
supply reverses the direction of rotation.

U9 is L293 driver IC used to drive the dc motor. It has enable lines which is used to switch on the DC
motor. It is connected to P4.28. Logic' l' enables the driver and logic '0' disables the driver.P4.28 and
P4.29 are used for Motor 1 direction and speed control.

DC Motor Pin connection table.

Motor Motor LPC-1768 LPC-1


Selection Direction Pin No Port N
J-~
P4.28=1 &
DCMO Clockwise 82
85
DCMl Anti clock

DCM EN P2.8=1

We can't drive a de motor directly through a microcontroller pin. It usually operates in 3.3v-5v and lower currents
but DC motor normally works in 6-12v, 300mA and it has other drawbacks like the back EMF produced by the DC
motor may harm the controller ports and damagertgem. The solution to the above problems is using motor driving
circuit usually known as H-Bridges. They are ~asicallx built using FETs and many dedicated ICs are also available
like L293D etc.

These are dual H-bridge motor drivers, i.e., by using one IC we can control two DC motors in both clock wise and
counter clockwise directions. The L~SBDcan provide bidirectional drive currents of up to 60 OmAat voltages from
4.5 Vto 36 V.

P4.28 P4.29 EN DC motor Action


;"0/1 0 Stop. Not enabled
0 1 Rotates Anticlockwise
1 1 Rotates Clockwise
1 1 Stop
0 1 Stop
9. Display the Hex digits 0 to F on a 7-segment LED interface, with an appropriate delay in between.

#include <LPC 17xx.H>


unsigned char dat7seg[] = {Ox88,Oxeb,Ox4c,Ox49,Ox2b,OxI9,OxI8,Oxcb,Ox8,Ox9,Oxa,0x38,Ox9C,Ox68,
Oxlc,Oxle} ;
int main (void)
{
unsigned int i, j;
unsigned int count=O; II initially count=O;
LPC_GPI02->FIODIR = OxOOOOOOFF; II Seven seg on PORT2 p2.0 to p2.7 are output
LPC_GPI02->FIOPIN = OxOOOOOOFF; II Display blank
LPC _ GPIO l->FIODIR = Ox3COOOOOO; IlDig control on PORTI p1.26 to p1.29 are output
LPC GPIO l->FIOPIN &= ~(Ox3COOOOOO); II P1.26 to 1.27 are made 0

while(l)
{
if (count> OxF) count = 0; I I if count Greater than F, re initialize to 0
for (i=O; i < 20000; i++) Ilchange to illc1dec speed of count
{
LPC_GPI02->FIOPIN = dat7seg[count]; II & OxOOOF];
LPC_GPIOI->FIOSET = (1«26); 1126 fOF'first Sev segnjent , 27 for second
for G=O;j<IOOO; j++); Ilchange to incldec brightness of display
} LPC_GPI01->FIOCLR ~ (1«26); ~

CounH+; Ilcount = count+ I


}
}

LED Pin Configuration

VTCM3 3board provides eight individual SMD led's connected to LPC-1768 device through
74HCl5ldriver IC. Dl te D8 are connected to general purpose 110 pins on LPC-1768 device as shown
in table(14) When LPC-1768 crevice drives Logic' I' the corresponding LED turns on.

DI D2 D3 D4 D5 D6 D7 D8

81 80 79 78 77 76 48 49
Pin No" LPC-1768
Port No
PO. 4 PO.5 PO. 6 PO. 7 PO.8 PO.9 PO.IO PO.II

SEVEN SEGMENT DIPLA Y Pin Configuration:

Dll, D12, Dl3 and Dl4 are Common Cathode segments connected to LPC-1768 device so that each
segment is individually controlled by a general purpose 110 pin. When the LPC-1768 device drives logic
'0' the corresponding segment turns on. See fig and table for more details.
9 cOMab gfc®ab 9 COM a b 9 coa a b

e d COM C P

09 010 011 012


Seven Segment Pin connection table.

Seven Segment
Data Lines g f a b p c d e
LPC-1768 Pin '\]~
No
LPC-1768 Port
75

P2.0
74

P2.1
73

P2.2 P2.3
70

P2.4
69 68

P2.6
IV
..-
P2.7
6

No ~

~
SEVEN SEGMENT Selection Pin Configurations: ~

As VTCM3_3 board comes with 4 digit seven segment unit. Displays connected to the microcontroller
usually occupy a large number of valuable 1/0 pins, which can be a big problem especially if it is needed to
display multi digit numbers. The problem i~more than obvious if, for example, it is needed to display four
digit numbers (a simple calculation shfrwstHat 32 output pins are needed in this case). The solution to this
problem is called MULTIPLEXING. This is how an optical illusion based on the same operating principle
as a film camera is made. Only one digit is-..acti;vaet a time, but they change their state so quickly
making impression that all digits of a number are simultaneously active. Each digit can made
active using switching transistors Q I, Q2, ~ and Q4 and these on switched on and off by selection lines
which are in tum connected to LPC"i 768 R0rtS. Table shows the details of seven segment selection lines.

~
Seven SegJiUent~ Displ Disp2 Disp3 Disp4
Selection Lines (D9) (DIO) (Dll) (DI2)
LPC-1768 P1o...N. o/ 40 43 44 45
1'\~~768 Port No Pl.26 Pl.27 Pl.28 Pl.29
,_\Cj(
Display EnC~ng.
Digits to Hex
Display Segments
display code

g f a B p c d e CODE
0 I 0 0 0 I 0 0 0 ~
I I I I 0 I 0 I I ~~
2 0 I 0 0 I I 0 0 ~q
3 0 I 0 0 I 0 0 I ~~
4 0 0 I 0 I 0 I I ~
5 0 0 0 I I 0 0 I [ill
6 0 0 0 I I 0 0 0 [I~
7 I I 0 0 I 0 I I ~~
8 0 0 0 0 I 0 0 0 ~
9 0 0 0 0 I 0 0 I p~
~
A 0 0 0 0 I 0 I 2 ~~
B 0 0 I I I 0 0 0 ~
C I 0 0 I I 0 0 o" ~~
D 0 I I 0 I 0 0 0 ~~
E 0 0 0 I
1- I " \2 0 ~q
F 0 0 0 I I I I 0 [11~

3 Controller _

II. To display hexa digitspO to FF with suitable delay

#include <LPC 17xx.H> *1

unsigned char dat7seg[] = {Ox88,Oxeb,Ox4c,Ox49,Ox2b,OxI9,OxI8,Oxcb,Ox8,Ox9,Oxa,0x38,Ox9C,Ox68,Oxlc,Oxle};

int main (void) ~


{

II Seven seg on PORT2 p2.0 to p2.7 are output


II Display blank
l!Dig control on PORTI p1.26 to p1.29 are output
I/Display blank

if (count> OxF) count = 0;


for (i=O; i < 20000; i++) Ilchange to inc/dec speed of count
{
LPC_GPI02->FIOPIN = dat7seg[count]; I I get data from array offset by count
LPC_GPIOI->FIOSET = (1«26)1(1«27); lifirst and second 7 segment devices ON
for G=O;j<IOOO;j++); Ilchange to inc/dec brightness of display
LPC_GPIOl->FIOCLR = (1«26) I (1«27);
}
count++;
}
}

91 • - ·8 b 9 f
- .. 8 9 • - .'·8 9 • - .8

pz';11
P.t.2
10,
r r
j, J
P!.3
Pl:.4
PlJJ Iii! i..R.B ,Iii
... fJHl! ;,
Pl;S,
PZJ;,

Pl:.~
e ~ ~~ c P . . ~ ~ c P • ~ -. p . ~ ~~• p

LP'C17'68

PIL.:l!'

!'1L.:ll>

PIL.:l,~

PIL.:li,
'16 X 2 LCD Dis/!_ia]
An LeD display is specifically manufactured to be used with microcontrollers, which means that it cannot
be activated by standard Ie circuits. It is used for displaying different messages on a miniature liquid
crystal display. It displays all the letters of alphabet, Greek letters, punctuation marks, mathematical
symbols etc. In addition, it is possible to display symbols made up by the user. Other useful features
include automatic message shift (left and right), cursor appearance, LED backlight etc.

y
There are pins along one side of a small printed board. These are used for connecting to the
microcontroller. There are in total Of~14pins marked with numbers (16 if it has backlight). Their function is
described in the table below:
LCD Pin Configuration
LPC- LPC-
~~CD LCD Pin 1768 1768
I~p:~
Functions Pin Port
o
I <
Y No No
1 GND - -
2 vee - -
3 - -
4 RS 24 P2.28
5 RIW GND GND
6 EN 27 P2.27
7 DATI 75 P2.0
8 DAT2 74 P2.l
9 DAT3 73 P2.2
10 DAT4 70 P2.3
11 DAT5 69 P2.4
12 DAT6 68 P2.5
13 DAT7 67 P2.6
14 DAT8 66 P2.7
15 vee - -
16 GND - -
No HEX Value COMMAND TO LCD'
'l IOxlO'l C1'ea,.,lDi'spIa y Scree n
:2 'Ox3'0 !Fuli'lct:lonSe't::' a,-bit 1 Line, 5:;:.;7Dots.
3 Ox3:8 Function Se:ti:::S-bit,. 2: Line S,x7 Dots
4 lOx20 !FunclLioIIlJ Se'l!:: 4-bit:, ~ Un eo 5x 7' Dots.
.'5 0:>;;:28 !FuncltionSelt:, 4-bit::, :2 Une" 5.x7' Dots,
6 IOx106, BnIT'y Mode
1-'~7 0~X,,-,,~O:-:;8::-' ~[)~'~FS;o::IP·~II'ay=-o, ·" Cursor
off
.e OxOE lD~slil'~oany, Cursor €In
'9 OxOC lDiispllayon. Cursor €Iff
'lQ OxQIF lD~spl'ay'orr, Cursor' blinking
:iII.::!IL 'Ox:18 Shlift: entire display' le,ft
12 lOxl,:C Shift entire displ;ay right
:ilL 3 lOx110 Mlovecursor le·ft:bv €Ine·character
:ilL 4 lOx,141 Move cUl'Sorri'ght by one' character
JlL5 Qx80 !Force cursor to be,ginning of ~5t, row
:ill. 6, 'OxOO !Forcecursor toobeginning of 2nd row

10.) Interface LCD with 1768 and write a Program to display Messa~ge an LCD screen.

#include <LPC 17xx.h>


#define LCD RS (l«28)
#define LCD EN (l«27)

void LCD _ Command(unsigned char cmd)


{
LPC _ GPI02->FIOPIN = cmd
;
LPC_GPIOO->FIOCLR 1=LCD_RS; II RS=O
LPC_GPIOO->FIOSET 1=LCD_EN; II EN=-l
for(int k=O;k<IOOOOO;k++); II delay~
LPC_GPIOO->FIOCLR 1=LCD_EN; IIEN=O
}

tid LCD_Data(unsigncd char data) ~ ~

LPC GPI02->FIOPIN = data; "-..)


LPC_GPIOO->FIOSET 1=LCD_RS; II RS=1
LPC_GPIOO->FIOSET 1=~C])_EN; IIEN=1
for(intj=O;j<IOOOOO;j++1; II delay
} LPC_GPIOO->FIOCLRI~EN; II EN~O

void LCD Init( void)


{
LPC_GPIOO-:>FIODIR 1=(LCD_RS 1LCD_EN); II EN and Read Select Pins are configured as olp
II Config P2.0 to P2.7 as olp pins
II 8 bits, 2 lines, 5x7 Dots
I I Clear Display screen
I I Display on & cursor On
}

I I initialize x=o

II Force cursor to beginging of! row, [OxcO for II row]


I I if content of str in not a null char
LCD Data(str[x]); I I send to LCD as Data

x++·, I!increment x
}
}
10.a) Interface a 4x4 keyboard and display the key code on an LCD.

#include <LPC 17xx.H>


#include "led.h"

void col_ write( unsigned char data )


{
LPC_GPIOl->FIOSET 1=(data « 14) & (1«1411«1511«1611«17);
}

int main (void)


{
unsigned char key, i;
unsigned char rval[] = {Ox7,OxB,OxD,OxE};
unsigned char keyPadMatrix[ ] = { '0' ,'1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,'A' ,'B' ,'c','D' ,'E' ,'F'}',

init Icdt);

LPC_GPIOl->FIODIR= (1«1411«1511«1611«17); //sct~s as Outputs

led_putstring 16(0, "Press HEX _ Key Board ..");


led_putstringI6(1,"Key Pressed = ");

while (1)
{
key = 0;
for( i ~ 0; i <4; i++) ~

Lpc GPIOl->FIOCLR 1=(1<<:1411<<5'1511<<1611<<17);


II tum on COL output one by one
II read rows - break when key press detected

II ifno key pressed key++ ncrements upto 16 i.e Oxl0


");

led _gotoxy( 1,14);


led _putchar(keyPadMatrix[key D;
}
}
}
HEX KEY PAD Pin configurations:

The hex keypad is a peripheral that is organized in rows and Columns. Hex key Pad 16 Keys arranged in a 4 by 4
grid, labeled with the hexadecimal digits 0 to F. An example of this can been seen in Figure 1, below. Internally,
the structure of the hex keypad is very simple. Wires run in vertical columns (we call them CO to C3) and in
horizontal rows (called ROto R3). These 8 wires are available externally, and will be connected to the lower 8 bits
of the port. Each key on the keypad is essentially a switch that connects a row wire to a column wire. Wlien a key is
pressed, it makes an electrical connection between the row and column. Table shows connections f0r H~X K-:EY
Pad matrix.

HEX KEY Pad matrix table.

ROW/COLOUMNS Rl R2 R3 R4 Cl
LPC-1768 Pin No 32 33 34 35 89
LPC-1768 Port No P1.18 P1.19 P1.20 P1.21 P1.14 P1.17

C1 C.2 C3: C4

...L. ...L. ...L. ...L.


11. Determine Digital output for a given Analog input using Internal ADC of ARM controller

//Program display Internal ADC value on 16x2 led


#include <LPC 17xx.H> /* NXP LPC 17xx definitions */
#include <stdio.h>
#include "lcd.h"

#define ADC DONE Ox80000000


#define ADC OVERRUN Ox40000000

#define ADC CLK 1000000 /* set to IMhz */

volatile int ADCValue;

void ADCInit( int Clk )


{
LPC_SC->PCONP 1=(1 « 12); I' Enable CLOCK ~trol1er 'I

LPC_PINCON->PINSELlI= Ox00004000;
LPC ADC->ADCR = (1« 0) I /* select channel ; Here Oth bit is 1 ie channel 0 is selected */
(14«8)1 /* CLKDIV = Fpclk / ~DC_Clk - 1 * CLKDIV starts from 8 bit
(1«21); I' PDN ~ I, n~peration 'I
return ;
}
int ADCRead( )
{
int reg Val, ADC _ Data;
LPC_ADC->ADCR &= OxFFFFFFOO; ~11c1cardata
LPC_ADC->ADCR 1=(1 «24) 11; /* switch channel,start AID convert */

while ( 1 ) /* wait until end of AID convert */


{
regVal = LPC_ADC->ADDRO; //Contains the recent ADC value for respective channel
if( regVal & A:flC_DONE) break; /* read result of AID conversion */
}

/* stop ADC now */

if( regVal & ADC_OVERRUN)


return (0 J; /* save data when it's not overrun, otherwise, return zero */
ADC_Dat~( re_gxral» 4) & OxFFF; //read data in 4: 15 so shift by 4 times to bring to 0: 7
return (ADC Data);
/* return AID conversion value */

int main (void)


{
char Istr[IO];
double volt;

ADCInit( ADC CLK);


init lcdt);
lcd_putstringI6(0,"ADC Val = 000 ");
lcd_putstringI6(1,"VOLTAGE = O.OOV");

while(l)
{
ADCValue = ADCReadO; II read ADC value
sprintf(lstr, "%4u", ADCValue);
led_gotoxy(O,10); Ilgoto l" line, 10 char place
led_putstring(lstr); Ilprint

volt = ADCValue * 3.3/4096; II(ADCValue * 3.3) 1 4096) ;


sprintf (lstr, "%0.2f', volt);
led_gotoxy(l, 10); Ilgoto 2nd line 10th char place
led_putstring(lstr); Ilprint
delay(500);
}
}
Table 80'.. Pin Iunctlol'l select regisle~ 1 (PINS:E,U • address Ox41l02 C0G41 bj~ descruplfon

PIMSEL.1 P<lnname FUM.lion, when Function Fu:nellon Funilt!'lon lReset


DO when 01 when 10 when 11 value

1:0 PO.16 GPIO PontO 1& RXD1 SS'ElO S,sEL

3.:2 IPO.H GPIO Port 0 ..17 CTS1 MII&DO MISO

1),:4 IP.Q.18 GPIO Port 0 ..HI, OCDl MOSIO MOSI

7:6 PO.19ill GPIO Port 0.19 OSR1 Re~Ned SOAl


9(8 P,0.2D1!l GPIO Port 0 ..20 OTR1 ReS€Ned SCl1

11:10 IPO.21l!l GPIO Port 0..21 RI! Re~Ned R01

13:12 IPO..22 GPIO Port 0..22: RTS1 Re.~Ned T01

15:14 IPozilll GPIO Pont 0.23 ADO'.O 12SR.X_GLK CA1f'3.0

17:16 IP024l!l GPIO Port 0 ..24 ADO.1 12SRX_ 'INs. CA1f'3.1

19:18 PO.25 GPIO Pont 0 ..25 ADO'.2 12SRX~ SDA Txm


2:1:20 IPO.2.6 GPIO Pont 0.2& Aocn AOUT RXiD3

23:22 PO.2:7l!lm GPIO Port 0.27 SDAO IUSB._SDA R.ese!\1e;]

25:24 PO.2:Bl!ll@l GPIO Pont 0.28, SCLO lUSB_SCL R.eseNe;]

LPC1768 has an inbuilt 12 bit Successive Approximation ADC which is multiplexed among 8 input pins.
The ADC reference voltage is measured across VREFN to VREFP, meaning it can do the conversion within this
range. Usually the VREFP IS connected to VDD and VREFN IS connected to GND.
As LPC1768 works on 3.3 volts, this will be the ADC reference voltage.
Now the resolution of ADC = 3.3/ 212 = 3.3/4096 =0.000805 = 0.8mV

The ADC pin can be enabled by configuring the corresponding PINSEL register to select ADC function.
When the ADC function is selected for that pin in the Pin Select register, other Digital signals are disconnected

"
from the ADC input pins.

"~

~ I ~I1 I
Adc Associated PINSEL
Pin Functions
Register

Ch an PO 23 O-GPIO, I-ADOrO], 2-12SRX_CLK 14,15 bits of PINSELl


. 3-CAP3[0]

~ ~E
nel

O-GPIO, l-ADO[l], 2-12SRX WS,


16,17 bits of PINSELI
3-CAP3[1]

~E
O-GPIO, l-ADO[2], 2-12SRX SDA,
18,19 bits of PINSELl
3-TXD3

~E O-GPIO, l-ADO[3], 2-AOUT,


3- RXD3
20,21 bits of PINSELl
c:JE O-GPIO, I-VBUS, 2-, 3-ADO[4] 28,29 bits of PINSEL3

c:JE
~==========~
O-GPIO, I-SCKl, 2-, 3-ADO[5] 30,31 bits ofPINSEL3

c:JE
~==========~
O-GPIO, l-RXDO, 2-ADO[6], 3- 6,7 bits of PINSELO

c:JE
~==========~
O-GPIO, I-TXDO, 2-ADO[7], 3- 4,5 bits ofPINSELO

ADC Registers

The below table shows the registers associated with LPCl768 ADC.
We are going to focus only on ADCR and ADGDR as these are sufficient for simple AID conversion.

\~
1 R_eg;...i_st_er II D_e_sc_r...;ip_t_iO_n 1

IADCR IAID COntrol Register: Used for Con~gz~C


AID Global Data Register: This register contains the ADC's DONE bit and the result of the
ADGDR
most recent AID conversion
I I ~
IADINTEN IIAID Interrupt Enable Re~r , I

IADDRO - ADDR7 IAID Channel ~a Register: Contains the recent ADC value for respective channel

IADSTAT IAID Stat~s ~er~tains DONE & OVERRUN flag for all the ADC channels

~ ~.-
ADC Register Configuration

Now lets see how to configure the individual registers for ADC conversion.

ADCR

)31:28
r=
1[]~1~23:=22==IEJ~120:=17==1r=J1~15=:8 ===1 i7=:1O=======il I

;< ~11~ed IEE:JIReserved IlpDN IIBURST IICLCKDIV IISEL I

~:O - SEL : Channel Select


These bits are used to select a particular channel for ADC conversion. One bit is allotted for each channel. Setting
the Bit-O will make the ADC to sample ADO[O] for conversion. Similary setting bit-7 will do the conversion for
ADO[7].

Bit 15:8 - CLCKDIV : Clock Divisor


The APB clock (PCLK _ADCO) is divided by (this value plus one) to produce the clock for the AID converter,
which should be less than or equal to 13 MHz.
Bit 16 - BURST
This bit is used for BURST conversion. If this bit is set the ADC module will do the conversion for all the channels
that are selected(SET) in SEL bits.
CLearing this bit will disable the BURST conversion.

Bit 21- PDN: Power Down Mode


Setting this bit brings ADC out of power down mode and makes it operational.
Clearing this bit will power down the ADC.

Bit 24:26 - START


When the BURST bit is 0, these bits control whether and when an AID conversion is started:
000 - Conversion Stopped
001- Start Conversion Now

The remaining cases (010 to Ill) are about starting conversion on occurrence of edge on a particular CAP or MAT
pm.

Bit 27 - EDGE ~
This bit is significant only when the START field contains 010-111. It starts conversion on selected CAP or MAT
input.
o - On Falling Edge
1 - On Rising Edge

ADGDR (ADC Global Data Register)


ADGDR

~I 27 ~=2=6=:2~4~~~=====2=3=:1=6======~=====15=:4======1~
IDONEII OVERRUN Reserved RESUL1l IIReservedl

Bit 15:4 - RESUL T


This field contains th€ Ubit AID conversion value for the selected channel in ADCR.SEL
The vale for this register shetild be read oncve the conversion is completed ie DONE bit is set.

Bit 26:24 - CHN : Channel


These bits contain the channel number for which the AID conversion is done and the converted value is available in
RESULT ~g. 000 identifies channel 0, 011 channel S...).

Bit 27-OVERRUN
~his b'it is set during the BURST mode where the previous conversion data is overwritten by the new AID
conversion value.

Bit 31- DONE


This bit is set to 1 when an AID conversion completes. It is cleared when this register is read and when the
ADCR is written. If the ADCR is written while a conversion is still in progress, this bit is set and a new conversion
is started.
Temperature Sensor

The LM35 series are precision integrated-circuit temperature sensors, whose output voltage is linearly proportional
to the Celsius (Centigrade) temperature. The output of sensor converted to digital that easy connecting with
microcontroller.

12.Measurement of ambient temperature using a sensor and SPI ADC IC.

#include <LPC l7xx.H>


#include <stdio.h>
#include "lcd.h"
#include "spi.h"

int main (void)


{
int msb,lsb;
int ADCValue;
float temp;
char lstr[lO];

SPI InitO;
init lcdt);

lcd_putstring16(0,"TEMP = 000 Deg_C");


while(l)
{
SPI_EnableChipSelectO;
delay(l);
SPI Write(OxOl);
msb = SPI Write(OxAO); II SGL=l, ODD=O,MSBF=l
lsb = SPI Write(OxOQ);

#include <lpc 17xx.h>


#include "spi.h"

uint8_t dummy_u8;
static uint32_t spi_GetPclk(void);
void SPI Init(void)
{
LPC_PINCON->PINSELO 1=OxCOOOOOOO; IISCK
LPC_PINCON->PINSELlI= Ox0000003C; IISSEL, MISO, MOSI
LPC_GPIOO->FIODIR 1= Ox00058000; IISSEL, MOSI, SCK are Outputs 15,16,18
LPC_GPIOO->FIODIR&= ~Ox00020000; IIMISO is Input 17

SPI_DisableChipSelectO; I I Disable the Slave Select

LPC_SC->PCONP 1=(l «8); I I enable power to spi clock

LPC_SPI->SPCCR = spi_GetPclkO/SCK_Freq; I I Set Spi Clock

LPC_SPI->SPCR = «O«SBIT_CPHA) 1(O«SBIT_CPOL) 1(l«SBIT_MSTR));


dummy_u8 = LPC_SPI->SPSR; 1* Dummy read to clear the f1ag~L
dummy_u8 = LPC_SPI->SPDR;
I' Dummy ~ the flags '1
}

uint8_t SPI_Write (uint8_t spiData_u8)


{
LPC_SPI->SPDR = spiData_u8;
dummy_u8 = 0;
while(dummy_u8 == 0)
{
dummy_u8 = LPC_SPI->SPSR & Ox80; IlWaitun~t
} dummy_u8 = LPC_SPI->SPSR;
spiData_u8 = (uint8_t)LPC_SPI->SPDR;
return spiData_u8;
}

static uint32_t spi_GetPclk(void) ~


{ uint32_t v_spiPclk_u32,v_Pclk_u32; ~,")
v_spiPclk_u32 = (LPC_SC->PCLKSELO::>>1' 6) &
Ox03; switch( v_spiPclk_u32)
{
case OxOO:
v_Pclk_u32 = SystemCorepbckl4; IISystemFrequency or SystemCoreClock

y
break;
case OxOl: =
'
V_PGlk_U3 Syst2emCoreClock;
break;
case Ox02:
v_Pclk_u32 = SystemCoreClockl2;
break;
case Ox03:
v_P"clk_u32= SystemCoreClockl8;
break;
}
return (v_Pclk_u32);

IC1 PO[16,]
PO[1S]
PO[H]
LPC1768
PO[18]
PO[1~]
PO[2G]
PO[,21]
PO[l']
\ISS,

P2[1'1]
P2[12]
ARM Cortex M3 Series: An Introduction
Brief History
ARM was founded in 1990 as Advanced RISC Machines Ltd., a joint venture of Apple Computer, Acorn
Computer Group, and VLSI Technology. In 1991, ARM introduced the ARM6 processor family, and VLSI
became the initial licensee. Subsequently, additional companies, including Texas Instruments, NEC, Sharp
and ST Microelectronics, licensed the ARM processor designs. Nowadays ARM partners ship in excess of 2
billion ARM processors each year. Unlike many semiconductor companies, ARM does not manufacture
processors or sell the chips directly. Instead it licenses the processor designs to business partners. This
business model is commonly called intellectual property (lP) licensing.
Architecture Versions
Over the years, ARM has continued to develop new processors and system blocks. These include the popular
ARM7TDMI processors, more recently the ARMll processor family and latest being the ARM Cortex
Processor family. Table 2.1 summarizes the various architecture versions and processor families.
Architecture Processor Family
ARMv1 ARM1
ARMv2 ARM2, ARM3
ARMv3 ARM6, ARM7
ARMv4 StrongARM, ARM7TDMI, ARM9TDMI
ARMv5 ARM7EJ, ARM9E, ARMlO~-;"'X~~
ARMv6 ARMll, ARM Cortex -M V Y
ARMv7 ARM Cortex-A, ARM Cortex-R, ARM Cortex-M

ARM Cortex Processor Profiles


In the ARMv7 architecture the design is divided into three profiles-
1. A Profile (ARMv7-A) - is designed for high performance open application platforms. They can handle
complex applications such as high end embedded operating system~.
Example products include high-end smartphonos, tablet PCs and PDAs.

2. R Profile (ARMv7-R) - is designed for high end embedded systems in which real time performance is
needed. Example applications include higli -eRa.car braking systems.
3. M-Profile (ARMv7-M) - is designed for aeeply embedded microcontroller type systems. Processors
belonging to this profile are the subject for this manual and are studied in greater detail.

Evolution of the ARM Instpfction Set


Enhancement and extension of insjjructiontsets used by the ARM processors has been one of the key driving
forces of the architecture's evolution. Historically, two different instruction sets were supported on the ARM
processor: the ARM mstructions, ~lilch are 32 bits and Thumb instructions, which are 16 bits. During
program execution, tIle processor can be dynamically switched between the ARM state and the Thumb state.
The Thumb instruction ~et provides only a subset of the ARM instructions, but it can provide higher code
density. It is useful for products with tight memory requirements.
The Thumb-2 technolGgy:extended the Thumb Instruction Set Architecture (ISA) into a highly efficient and
powerful instruction set that delivers significant benefits in terms of ease of use, code size and performance.
The extended instruction set in Thumb-2 is a superset of the previous 16-bit Thumb instruction set, with
additional l~it instructions alongside 32-bit instructions. It allows more complex operations to be carried
out in the 'IlliUffi<l3 state, thus allowing higher efficiency by reducing the number of states switching between
ARM state and>Thumb state.
The Cortex-M3 processor supports only the Thumb-2 (and traditional Thumb) instruction set. Instead
of using ARM instructions, as in traditional ARM processors, it uses Thumb-2 instruction set for all
operations. As a result, the Cortex-M3 processor is not backward compatible with traditional ARM processors,
whiQh use the ARM as well as Thumb instruction set.
The Thumb-2 instruction set is a very important feature of the ARMv7 architecture. For the first time,
hardware divide instruction is available on an ARM processor, and a number of multiply instructions are also
available.
Salient Features of the Cortex-M3
• 32-bit microprocessor.
• 32-bit data path, 32-bit register bank and 32-bit memory interfaces.
• Harvard Architecture - separate instruction bus and data bus.
• 3-stage pipeline with branch speculation.
• Thumb-2 instruction set.
• No switching between ARM state and thumb state.
• Instruction fetches are 32 bits. Up to two instructions can be fetched in one cycle. As a result, there's
more available bandwidth for data transfer.
• ALU with hardware divide and single cycle multiply.
• Configurable Nested Vector Interrupt Controller
(NVIC).
• Maximum of 240 external interrupts can be configured.
• Low gate count, suitable for low power designs.
• Memory Protection Unit (MPU).
• Operation Mode Selection - user and privilege
modes.
• Advanced debug components.

Registers

• The Cortex-M3 has registers RO through R15. R13 (the stack pointer) is banked, with only one copy of the
R13 visible at a time.
• RO - R12: General Purpose Registers. These are 32 bit registers for data operations. Some 16-bit
Tnumb instructions can only access a subset of these registers (low registers RO-R7).
• R13: Stack Pointers. Contains two stack pointers. They are banked so that only one is visible at a
time.
• Main Stack Pointer (MSP) - The main stack pointer used by the Operating system and
exception handlers.
• Process Stack Pointer (PSP) - used by the application code.
• R14: Link Register. When a subroutine is called, the return address is stored in the link
register.
• R15: Program Counter. The program counter is the current program
address.
• The Cortex-M3 also has a number of special registers. They are
• Program Status registers (PSR)
• Interrupt Mask registers (PRIMASK, FAULTMASK and BASEPRIV
• Control register (CONTROL)
• The Cortex-M3 has 18 registers in total compared to 37 registers for traditional ARM.
Memory Map
The Cortex-M3 has predefined memory maps, which allows built in peripherals, such as the interrupt
controller and debug components, to be accessed by simple wemory access instructions. The predefined
memory map also allows the Cortex-M3 proceswr to be highly optimized for speed and ease of integration in
system-on-a-chip (SoC) designs.
The Cortex-M3 design has an internal b4.s infrastmcture optimized for this memory usage. In addition, the
design allows these regions to be used differently. FOI1example, data memory can still be put into the CODE
region, and program code can be executed from an: external Random Access Memory (RAM) region. The
Cortex-M3 memory map is outlined in figure as shown.
Operation Modes
The Cortex-M3 processor has two meJdes of operation and two privilege levels. The operation modes (thread
mode and handler mode) determine wl},ether the processor is running a normal program or running an
exception handler like an interrupt handler or system exception handler. The privilege levels provide a
mechanism for safegua~ding memory accesses to critical regions as well as providing a basic security model.
When the processor: is running a main program (thread mode), it can be either in a privileged state or a user
state, but exception handle~{San only be in a privileged state. When the processor exits reset, it is in thread
mode with privileged acces~nght. In this state, a program has access to all memory ranges and can use all
supported instructions. DElftwarein the privileged access level can switch the program into the user access
level using the control register. When an exception takes place, the processor will always
switch ba~Kto the privileged state and return to the previous state when exiting the exception handler. A user
program cannot clYangeback to the privileged state by writing to the control register. It has to go through
an exception handler that programs the control register to switch the processor back into the privileged
access level when re~rning to thread mode.

N:~ed Vector Interrupt Controller (NVIC)


The Gortex-M3 processor includes an interrupt controller called the Nested Vectored Interrupt Controller
(NViC). It is closely coupled to the processor core and provides a number of features as
follows:
• Nested interrupt support
• Vectored interrupt support
• Dynamic priority changes support
• Reduction of interrupt latency
• Interrupt masking
Nested Interrupt support - All the external interrupts and most of the system exceptions can be
programmed to different priority levels. When an interrupt occurs, the NVIC compares the priority of this
interrupt to the current running priority level. If the priority of the new interrupt handler is higher than the
current level, the interrupt handler of the new interrupt will override the current running task.
Vectored Interrupt Support - When an interrupt is accepted, the starting address of the interrupt service
routine (ISR) is located from a vector table in memory.
Dynamic Priority Changes Support - Priority levels of interrupts can be changed by software during run
time. Interrupts that are being serviced are blocked from further activation until the ISR is completed, so
their priority can be changed without risk of accidental reentry.
Reduction of Interrupt Latency - The Cortex-M3 processor also includes a number of advanced features
to lower the interrupt latency. These include automatic saving and restoring some register contents and
reducing delay in switching from one ISR to another.
Interrupt Masking - Interrupts and system exceptions can be masked based on their priority level or
masked completely using the interrupt masking registers BASEPRI,PRIMASK,and FAULTMASK.

Das könnte Ihnen auch gefallen