Upload
karim-ibrahim
View
249
Download
0
Embed Size (px)
Citation preview
8/9/2019 microcontroller course1
1/72
Specially designed microprocessorsA microcontroller is a complete computer system on a single chip
Highly integrated chipincludes all or most parts needed for controller
A typical microcontroller has:bit manipulationeasy and direct access to I/Oquick and efficient interrupt processing
Microcontroller drastically reduces design cost
What we can do with microcontrollerAny control problem. Just let it go your imagination.
1/175
8/9/2019 microcontroller course1
2/72
Many people are already familiar withmicroprocessors as microprocessors are theheart of Personal Computers (PCs). Mostpeople, even some in the technicalcommunity, are not familiar withmicrocontrollers although microcontrollers areencountered in modern life much more thanmicroprocessors are. Microcontrollers are whatmake modern appliances intelligent andprogrammable. It is often found in washing
machines, video games, telephones,automobiles, copiers, elevators, CD ROMdrives, hard disk drives, keyboards, remotecontrol units, computer screens, and manyother equipments and consumer electronics
2/175
8/9/2019 microcontroller course1
3/72
Appliances(microwave oven, refrigerators, television and VCRs, stereos)
Computers and computer equipment(laser printers, modems, disk drives)
Automobiles(engine control, diagnostics, climate control),
Environmental control(greenhouse, factory, home)
Instrumentation
Aerospace
Robotics, etc...
3/175
8/9/2019 microcontroller course1
4/72
Computer engineering, computer science, electrical engineering(power and communications), applied electronics, and appliedphysics students and professionals all need to well know
microprocessors and microcontrollers. Mechanical engineers alsocan make better jobs with good knowledge of microprocessorsand microcontrollers.
4/175
8/9/2019 microcontroller course1
5/72
8048 (Intel)
8051 (Intel and others)
80c196 (MCS-96)
80186,80188 (Intel)
80386 EX (Intel)
65C02/W65C816S/W65C134S (Western Design Center)
MC14500 (Motorola)
5/175
8/9/2019 microcontroller course1
6/72
68HC05 (Motorola)
68HC11 (Motorola and Toshiba)
683xx (Motorola)
PIC (MicroChip)
COP400 Family (National Semiconductor)
COP800 Family (National Semiconductor)
HPC Family (National Semiconductor)
Project Piranha (National Semiconductor)
6/175
8/9/2019 microcontroller course1
7/72
Z8 (Zilog)
HD64180 (Hitachi)
TMS370 (Texas Instruments)
1802 (RCA)
MuP21 (Forth chip)
F21 (Next generation Forth chip)
7/175
8/9/2019 microcontroller course1
8/72
Machine/Assembly language
Ansi C
C Basic/ Turbo C
Embedded java
8/175
8/9/2019 microcontroller course1
9/72
Simulators
Resident Debuggers
Emulators
Java on Embedded Systems
9/175
Part 1
8/9/2019 microcontroller course1
10/72
The main difference between them is that amicroprocessor needs several accompanying chips tooperate. The microcontroller has most of these chipsintegrated on the same chip.
The types of this chipsADCDACSerial communication technique
External memory
10/175
8/9/2019 microcontroller course1
11/72
The good knowledge of digital electronics will help you much andwill speed up your learning curve. However, the basic concepts willbe reviewed during the course and a basic understanding will do. If
you are familiar with analog electronics, this will help you dobetter analog interfacing projects but it is not at all necessary forthis course.
11/175
8/9/2019 microcontroller course1
12/7212/175
8/9/2019 microcontroller course1
13/7213/175
8/9/2019 microcontroller course1
14/7214/175
8/9/2019 microcontroller course1
15/7215/175
8/9/2019 microcontroller course1
16/72
High-level language Low-level language
Ease of learning Easy Difficult
Ease of programming Easy Difficult
Development time shorter longer
Code efficiency Less efficient high efficient
Tool price Very expensive Free
16/175
8/9/2019 microcontroller course1
17/7217/175
8/9/2019 microcontroller course1
18/72
C is a computer programming language.C is what is called a compiled language. This means thatonce you write your C program, you must run it through aC compiler to turn your program into an executable that
the computer can run (execute). The C program is thehuman readable form, while the executable that comesout of the compiler is the machine-readable andexecutable form. What this means is that to write and runa C program, you must have access to a C compiler. Youcan use Turbo C or Turbo C++ Compilers for this purpose
18/175
8/9/2019 microcontroller course1
19/72
Small size Extensive use of function calls Loose typing -- unlike PASCAL Structured language Low level (Bitwise) programming readily available Pointer implementation - extensive use of pointers for memory, array,structures and functions.
C has now become a widely used professional language for variousreasons.
be used to write any complex program. It can handle low-level activities. It produces efficient programs. It is fast. (much faster than BASIC). It can be compiled on a variety of computers
19/175
8/9/2019 microcontroller course1
20/72
Documentation Section
Link Section
Definition Section
Global Declaration Section
Main() Function Section{Declaration Part
Executable Part }
Subprogram SectionFunction 1
Function 2..
..
Function n
20/175
8/9/2019 microcontroller course1
21/72
8/9/2019 microcontroller course1
22/72
#include /* preprocessor directive */#define PI 3.142 / * include standard C header file */float area; /* global declaration */int square (int r); /* prototype declaration */main(){ / * beginning of main function */int radius_squared; /* local declaration */
int radius = 3; /* declaration and initialization */radius_squared = square (radius);/* pass a value to a function */
area = PI * radius_squared;/* assignment statement */
printf(Area is %6.4f square units \ n,area);} /* end of main function & program */square(int r) /* function head */
{int r_squared; / * declarations here are known */
/* only to square */r_squared = r * r;return(r_squared); /* return value to calling statement
*/}
22/175
8/9/2019 microcontroller course1
23/72
#define directive, which substitutes text for the specified identifier#include directive, which includes the text of an external file into aprogram. the header file is denoted by a .h extension
#include //# include => This informationis used by the compiler to link all the hardware specifics and sourceprograms together.
#pragma, The pragma command instructs the compiler to perform aparticular action at the compile time such as specifying thePICmicroMUC being used or the file format generated.
Like : #pragma device PIC16C54
23/175
8/9/2019 microcontroller course1
24/72
Variables: A variable is a name for a specific memory location. This memorylocation can hold various values depending on how the variable was declared.In C, all variables must be declared before they are used. A variabledeclaration tells the compiler what type of variable is being used. All variable
declarations are statements in C and therefore must be terminated with asemicolon.
Ex: char, int, float, and long.The formattype variable_name;
24/175
8/9/2019 microcontroller course1
25/72
Constants: A constants is a fixed value which cannot be changed by theprogram . For example, 25 is a constant. Integer constants are specifiedwithout any fractional components, such as 100 or 40. Floating point constantsrequire the decimal point followed by the numbers fractional component. Thenumber 45.65 is a floating point constant. Character constants are enclosedbetween single quotes such as A or&.#define valueThe defines the name you will use throughout your program, value isthe value you are assigning to .EX: #define TRUE 1
#define pi 3.14159265359
#define data is not stored in memory, it is resolved at compile time.To save constants in the chip ROM, use the const keyword in a variabledeclaration. For example:char const id[5]={1234};
25/175
8/9/2019 microcontroller course1
26/72
main(){function1(int a,int b ){
Return()}function2(){
}}
main() is the first function called when the program is executed. Theother functions, function1() and function2(), can be called by anyfunction in the program .
26/175
8/9/2019 microcontroller course1
27/72
#define is a powerful directive as illustrated in the previous section. Callows defines to have parameters making them even more powerful.When parameters are used it is called a macro. Macros are used toenhance readability or to save typing. A simple macro:
#define var(x,v) unsigned int x=v;var(a,1)
var(b,2)
var(c,3)
is the same as:
unsigned int a=1;unsigned int b=2;
unsigned int c=3;
27/175
8/9/2019 microcontroller course1
28/72
The ANSI C standard defines 32 keywords for use in the C language.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsignd
continue for signed void
28/175
8/9/2019 microcontroller course1
29/72
Type Bit Width Range
short 1 0 or 1
short int 1 0 or 1
int 8 0 to 255
Char 8 0 to 255
unsigned 8 0 to 255
unsigned int 8 0 to 255
Signed 8 -128 to 127
signed int 8 -128 to 127
long 16 0 to 65536
long int 16 0 to 65536
signed long 16 -32768 to 32767
float 32 3.4E-38 to 3.4E+38
29/175
8/9/2019 microcontroller course1
30/72
+ addition- subtraction* multiplication/ division% modulus
a*=b is the same as a=a*ba/=b a=a/ba+=b a=a+ba-=b a=a-b
a%=b a=a%baba&=b a=a&ba|=b a=a|ba^=b a=a^b
30/175
8/9/2019 microcontroller course1
31/72
> greater than>= greater than or equal to< less than
8/9/2019 microcontroller course1
32/72
AND OR NOTp q p&&q p||q !p0 0 0 0 1
0 1 0 1 11 0 0 1 01 1 1 1 0
32/175
8/9/2019 microcontroller course1
33/72
& bitwise AND| bitwise OR
^ bitwise XOR~ 1s complement>> right shift expression
33/175
8/9/2019 microcontroller course1
34/72
if (expression){.
statement;
}
34/175
8/9/2019 microcontroller course1
35/72
if (expression1)
{
.
statement(s)
.
}
else if(expression2){
.
statement(s)
.
}
else{
.
statement(s)
.
}
35/175
8/9/2019 microcontroller course1
36/72
for( initialization ; conditional_test ;increment )void main(void)
{int i;for(i=0; i
8/9/2019 microcontroller course1
37/72
while (expression){statement;
}
37/175
8/9/2019 microcontroller course1
38/72
do{statements
}while(expression)
38/175
8/9/2019 microcontroller course1
39/72
void main(void)
{
int i;
for(i=0;i
8/9/2019 microcontroller course1
40/72
switch (variable){case constant1:statement(s);
break;case constant2:statement(s);break;case constantN:statement(s);
break;default:statement(s);}
40/175
8/9/2019 microcontroller course1
41/72
for (i=0;i
8/9/2019 microcontroller course1
42/72
type var_name [size];
int height[50];
height[24] = 60;
42/175
8/9/2019 microcontroller course1
43/72
type array_name[size] = {value_list};
int i[5] = {1,2,3,4,5};
43/175
8/9/2019 microcontroller course1
44/72
int number[5][5];
int num[3][3]={ 1,2,3,
4,5,6,7,8,9};
44/175
8/9/2019 microcontroller course1
45/72
We can mix c and assembly by using thecommand#asm
statements
#End asm
45/175
8/9/2019 microcontroller course1
46/72
The Input and Output ports on a PICmicroMCUare made up from two registers PORT and PORTDIRECTION and are designated PORTA,B,C,D,Eand TRISA,B,C,D,E.
Ex:
unwanted bits
46/175
8/9/2019 microcontroller course1
47/72
Technical support
Development tools
DocumentationPurchasing more devices at one manufacturer(A/D, memory, etc.)
Additional features(EEPROM, FLASH, LCD driver, etc.)
47/175
8/9/2019 microcontroller course1
48/72
Basic parts are:Central Processing UnitRAMEPROM/PROM/ROM or FLASHMemoryI/O serial or/and paralleltimersinterrupt controller
Optional parts are:
Watch Dog TimerAD ConverterLCD driveretc.
48/175
interruptcontrol
externalinerrupts
CPU
OSC
ROM
buscontrol
4 I/O
ports
serial
port
RAMtimer 0
timer 1 counterinputs
P0 P2 P1 P3address/
data
TxD RxD
8/9/2019 microcontroller course1
49/72
MICRO C PROWith the program
49/175
8/9/2019 microcontroller course1
50/72
50/175
8/9/2019 microcontroller course1
51/72
51/175
8/9/2019 microcontroller course1
52/72
RISC architecture
Only 35 instructions to learn
All single-cycle instructions except branches
Operating frequency 0-20 MHz
Precision internal oscillator Factory calibrated
Software selectable frequency range of 8MHz to 31KHz
Power supply voltage 2.0-5.5V
Consumption: 220uA (2.0V, 4MHz), 11uA (2.0 V, 32 KHz) 50nA (stand-by mode)
Power-Saving Sleep Mode
Brown-out Reset (BOR) with software control option
35 input/output pins
High current source/sink for direct LED drive
software and individually programmable pull-up resistor
Interrupt-on-Change pin
52/175
8/9/2019 microcontroller course1
53/72
8K ROM memory in FLASH technologyChip can be reprogrammed up to 100.000 times
In-Circuit Serial Programming Option
Chip can be programmed even embedded in the target device
256 bytes EEPROM memory
Data can be written more than 1.000.000 times
368 bytes RAM memory
A/D converter:
14-channels
10-bit resolution
3 independent timers/counters
Watch-dog timer
Analog comparator module with
Two analog comparators
Fixed voltage reference (0.6V)
Programmable on-chip voltage referencePWM output steering control
Enhanced USART module
Supports RS-485, RS-232 and LIN2.0
Auto-Baud Detect
Master Synchronous Serial Port (MSSP)
supports SPI and I2C mode
53/175
8/9/2019 microcontroller course1
54/72
1-Central Processor Unit (CPU):CPU is made in RISC technology because this fact can affect you to buyexactly this microcontroller.
RISC stands for Reduced Instruction Set Computer, which gives thePIC16F887 two advantages:
- Its CPU can recognize and execute only 35 simple instructions- Execution time is the same for all of them and lasts 4 clock
cycles
-The only exceptions are jump and branch instructions whoseexecution time is 8 cycles
54/175
8/9/2019 microcontroller course1
55/72
This microcontroller has three types of memory- ROM, RAM and EEPROM
1-ROM :ROM memory is used to permanently save program being executed. That is
why it is often called program memory. The PIC16F887 has 8Kb ROM (intotal of 8192 locations). Since, in this very case, ROM is made in FLASHtechnology, its contents can be changed by providing special programmingvoltage (13V).
2-EEPROM:
Similar to program memory, the contents of EEPROMis permanently saved, evenupon the power goes off. ,but unlike ROM, the contents of EEPROM can be changedduring operation of the microcontroller. That is why this memory (256 locations) is a
perfect one for permanently saving results created and used during the operation .
55/175
8/9/2019 microcontroller course1
56/72
RAM Memory :The most complex part of microcontroller memory. In this very
case, it consists of two parts: general-purpose registers andspecial-function registers (SFR).
SFR: special-function registers :there is two types: 1-Core (CPU) registers - control and monitor
operation and processes in the central processor. Even though there are only a fewof them, the operation of the whole microcontroller depends on their contents .
2-Peripheral SFRs- control the operation of peripheral units (serial communicationmodule, A/D converter etc.).
Note: unlike general-purpose registers, SFR purpose is predeterminedduring manufacturing process and cannot be changed.
56/175
8/9/2019 microcontroller course1
57/72
RAM Memory Banks : The data memory is partitioned into four banks.Prior to access some register during program writing (in order to read or changeits contents), it is necessary to select bank which contains that register. Twobits of the STATUS register are used for bank selecting.
57/175
8/9/2019 microcontroller course1
58/72
58/175
8/9/2019 microcontroller course1
59/72
Stack :A part of RAM used for stack consists of eight 13-bit registers.Before the microcontroller starts to execute a subroutine (CALLinstruction) or when an interrupt occurs, the address of first nextinstruction being currently executed is pushed onto the stack,the microcontroller knows from where to continue regularprogram execution. This address is cleared upon return to themain program because there is no need to save it any longer, andone location of the stack is automatically available for furtheruse.
59/175
8/9/2019 microcontroller course1
60/72
The first thing that the microcontroller does upon an interruptrequest arrives is to execute the current instruction and thenstop regular program execution. Immediately after that, thecurrent program memory address is automatically pushed ontothe stack and default address is written to the program counter.
The difference between interrupts and pollingInterrupts: external ,physical interrupts,
Polling :software interrupts.
When an interrupt request arrives it does not mean that interruptwill automatically occur, because it must be also enabled by the
user by using .
60/175
8/9/2019 microcontroller course1
61/72
61/175
8/9/2019 microcontroller course1
62/72
One of the most important feature of the microcontroller is anumber of input/output pins used for with peripherals.
TRIS register: TRISA, TRISB, TRISC etc.which determinesperformance, but not the contents of the port bits.
By clearing some bit of the TRIS register (bit=0), thecorresponding port pin is configured as output. Similarly, bysetting some bit of the TRIS register (bit=1), the correspondingport pin is configured as input. This rule is easy to remember 0 =
Output, 1 = Input.
62/175
8/9/2019 microcontroller course1
63/72
There are three completely independent timers/counters marked asTMR0, TMR1 and TMR2.
The timer TMR0 module is an 8-bit timer/counter with thefollowing features : 8-bit timer/counter register
8-bit prescaler (shared with Watchdog timer) Programmable internal or external clock source
Interrupt on overflow
Programmable external clock edge selection
In order to make an initial value for the timer
TMR0 Initial = 256 - (Delay Time * Clock Frequency / 8)
63/175
8/9/2019 microcontroller course1
64/72
1. Write to ADCON1 indicating what are the digital I/O pins andwhich are the analog I/O pins. At this time, if a 10-bit conversionis going to be done, set the format flag in ADCON 1 appropriately.
2. Write to ADCON0, setting ADON, resetting ADIF and GO/_DONEand specifying the ADC TAD clock and the pin to be used.
3. Wait for the input signal to stabilize.4. Set the GO/_DONE bit. If this is a high-accuracy measurement,ADIE should be enabled for interrupts and then the PICmicroMCU put to sleep.
5. Poll GO/_DONE until it is reset (conversion done ). 6. Read
the result form ADRES and optionally ADRESH.
64/175
8/9/2019 microcontroller course1
65/72
EUSART:Enhanced Universal Synchronous Asynchronous ReceiverTransmitter (EUSART) module is a serial I/O communicationperipheral. It is also known as Serial Communications Interface(SCI). It contains all clock generators, shift registers and databuffers necessary to perform an input or output serial datatransfer independently of device program execution.
the PIC16F887 microcontroller has the followingfeatures: Full-duplex asynchronous transmit and receive
Programmable 8- or 9-bit character length
Address detection in 9-bit mode
Input buffer overrun error detection
Half-duplex communication in synchronous mode (master or slave)
65/175
8/9/2019 microcontroller course1
66/72
Each data is transferred in the following way: In idle state, data line has high logic level (1).
Each data transmission starts with START bit which is always azero (0).
Each data is 8- or 9-bit wide (LSB bit is first transferred) Each data transmission ends with STOP bit which always haslogic level which is always one (1).
66/175
8/9/2019 microcontroller course1
67/72
In order to enable data transmission via EUSART module, it is necessary to configure it to operateas a transmitter. I other words, it is necessary to define the state of the following bits:
TXEN = 1 - EUSART transmitter is enabled by setting this bit of the TXSTA register.
SYNC = 0 - EUSART is configured to operate in asynchronous mode by clearing this bit of the TXSTAregister.
SPEN = 1 - By setting this bit of the RCSTA register, EUSART is enabled and the TX/CK pin isautomatically configured as output. If this bit is simultaneously used for some analog function, it
must be disabled by clearing the corresponding bit of the ANSEL register.
Byte will be immediately transferred to the shift register TSR. TXREG registerremains empty, which is indicated by setting flag bit TXIF of the PIR1 register. If theTXIE bit of the PIE1 register is set, an interrupt will be generated. Besides, the flagis set regardless of whether an interrupt is enabled or not. Also, it cannot becleared by software, but by writing new data to the TXREG register.
67/175
8/9/2019 microcontroller course1
68/72
Similar to the activation of EUSART transmitter, in order to enable receiver it is necessary to
define the following bits:
CREN = 1 - EUSART receiver is enabled by setting this bit of the RCSTA register.
SYNC = 0 - EUSART is configured to operate in asynchronous mode by clearing this bit stored in theTXSTA register.
SPEN = 1 - By setting this bit of the RCSTA register, EUSART is enabled and the RX/DT pin isautomatically configured as input. If this bit is simultaneously used for some analog function, it must be
disabled by clearing the corresponding bit of the ANSEL register .
Data is automatically transferred to the RCREG register (if empty).
The flag bit RCIF is set and an interrupt, if enabled by the RCIE bit of the PIE1 register,occurs. Similar to transmitter, the flag bit is cleared by software only, i.e. by reading the RCREG register.
Have in mind that this is a two character FIFO memory ( first-in, first-out) which allows reception of twocharacters simultaneously.
If the RCREG register is occupied (contains two bytes) and the shift register detects STOP bit, theoverflow bit OERR will be set. In this case, a new coming data is lost, and the OEER bit must be cleared bysoftware. It is done by clearing and resetting the CREN bit.
68/175
8/9/2019 microcontroller course1
69/72
MSSP module ( Master Synchronous Serial Port) is a very useful,but at the same time one of the most complex circuit within themicrocontroller. It enables high speed communication between amicrocontroller and other peripherals or microcontroller devicesby using few input/output lines (maximum two or three).Therefore, it is commonly used to connect the microcontroller toLCD displays, A/D converters, serial EEPROMs, shift registers etc.The main feature of this communication is that it is synchronousand suitable for use in systems with a single master and one ormore slaves. A master device contains the necessary circuitry forbaud rate generation and supplies the clock for all devices in thesystem. Slave devices may in that way eliminate the internalclock generation circuitry
69/175
8/9/2019 microcontroller course1
70/72
The MSSP module can operate in one of two modes:SPI mode (Serial Peripheral Interface)I2C mode (Inter-Integrated Circuit)
70/175
8/9/2019 microcontroller course1
71/72
SPI ModeThe SPI mode allows 8 bits of data to be transmitted and received simultaneouslyusing 3 input/output lines:
SDO - Serial Data Out - transmit line.
SDI - Serial Data In - receive line.
SCK - Serial Clock - synchronization line.
In addition to these three lines, in case the microcontroller exchanges data withseveral peripheral devices, the forth line (SS) may be also used. SS - Slave Select -is additional pin used for specific device selection. It is active only in case themicrocontroller is in slave mode, i.e. when the external - master device requiresdata exchange.
When operating in SPI mode, MSSP module uses in total of 4 registers:
SSPSTAT - status register SSPCON - control register
SSPBUF - buffer register
SSPSR - shift register (not directly available)
71/175
8/9/2019 microcontroller course1
72/72
Step 1. Data to transmit should be written to the buffer register SSPBUF .Immediately after that, if theSPI module operates in master mode the microcontroller will automatically perform the following step 2, 3and 4. If the SPI module operates as Slave, the microcontroller will not perform these steps until the SCKpin detects clock signal.
Step 2 . This data is now moved to the SSPSR register and the SSPBUF register is not clearedStep 3. Synchronized with clock signal, this data is shifted to the output pin (MSB bit first) while theregister is simultaneously being filled with bits through input pin. In Master mode, the microcontrolleritself generates clock, while the Slave mode uses external clock (pin SCK).
Step 4. The SSPSR register is full once the 8 bits of data have been received. It is indicated by settingthe BF and SSPIF bits. The received data (that byte) is automatically moved from the SSPSR register to theSSPBUF register. Since data transfer via serial communication is performed automatically, the rest of theprogram is normally executed while data transfer is in progress. In that case, the function of the SSPIF bitis to generate interrupt when one byte transmission is completed.
Step 5 .At last, the data stored in the SSPBUF register is ready for use and moved to any registeravailable