Lecture-6-PIC Programming in C
Lecture-6-PIC Programming in C
Lecture-6-PIC Programming in C
Lecture 6
PIC Programming in C
CSE 3442/5442
Embedded Systems 1
Based heavily on slides by Dr. Gergely Záruba and Dr. Roger Walker
Code Space Limitations
4
C Integer Data Types
(C18 Compiler)
5
C Integer Data Types
(XC8 Compiler)
6
Unsigned char
(0 to 255)
• PIC18 is 8-bit architecture, char type (8 bits) is the
most natural choice
• C compilers use signed char (-128 to +127) by
default unless we put “unsigned”
– char == signed char
7
Unsigned char array
(0 to 255)
8
Unsigned char array
(0 to 255)
9
Unsigned char array
(0 to 255)
z=0
PORTB = ‘0’ (in code)
PORTB = 0x30 = 48 (actual)
10
PORTB = 0b 0011 0000 (pins)
Unsigned char array
(0 to 255)
PINS
Direction Pin Value
(TRISB) (PORTB)
0 0
0 0
0 1
0 1
0 0
0 0
0 0
0 0
z=0
PORTB = ‘0’ (in code)
PORTB = 0x30 = 48 (actual)
11
PORTB = 0b 0011 0000 (pins)
Unsigned char array
(0 to 255)
z=1
PORTB = ‘1’ (in code)
PORTB = 0x31 = 49 (actual)
12
PORTB = 0b 0011 0001 (pins)
Unsigned char array
(0 to 255)
z=6
PORTB = ‘A’ (in code)
PORTB = 0x41 = 65 (actual)
13
PORTB = 0b 0100 0001 (pins)
Signed char
(-128 to +127)
• Still 8-bit data type but MSB is sign value
14
Unsigned int
(0 to 65,535)
• PIC18 is 8-bit architecture, int type (16 bits) takes
two bytes of RAM (only use when necessary)
• C compilers use signed int (-32,768 to +32,767) by
default unless we put “unsigned”
– int == signed int
15
Larger Integer Types
(short, long, short long)
16
Floating-Point Data Types
• 25 % 5 = 0
• 25 % 7 = 4
• 25 % 10 = 5
• 428 % 100 = 28
• 1568 % 10 = 8 18
Casting to Prevent Data Loss
?
19
Casting to Prevent Data Loss
20
Time Delay
• Three methods:
– Using a simple loop (for/while) (crude)
– Using PIC18 timer peripheral (later)
– Built-in delay functions (reliable and accurate)
21
Two Factors for
Delay Accuracy in C
1. The crystal’s frequency (int. or ext.)
– Duration of clock period for instruction cycle
2. The compiler used for the C program
– In ASM, we control the exact instructions
– Different compilers produce different ASM code
22
Time Delay Example
25
26
PORT I/O Programming in C
28
PORTxbits.Rxy
29
PORT I/O Programming in C
30
31
.ASM Generated from C
32
Header Files
33
Header Files
• Bit-Wise Operators
36
Binary (hex) to Decimal and
ASCII Conversion
• Sometimes we can’t handle multiple-digit
decimals natively in C for display purposes
• printf() is standard for generic C but
requires more memory space than a
PIC18 is willing to sacrifice
• Best to build your own “custom” print or
display functions in C
37
Extract Single Decimal Digits
38
Extract Single Decimal Digits
39
Extract Single Decimal Digits
40
Extract Single Decimal Digits
41
#define Directive
42
Questions?
43