SlideShare a Scribd company logo
EE403W Senior Project
Design
Design
Section 4 Embedded Systems
Section 4 – Embedded Systems
C Tutorial
QUIZ
// initialization section
unsigned char x = 2;
unsigned char x 2;
// execution section
if (x = 7)
x = 0;
Aft thi d h t i th l t d i th
• After this code runs, what is the value stored in the memory
location referenced by the variable ‘x’?
2
‘C’ Programming Language
Why program microcontrollers in ‘C’?
• More compact code (visually speaking)
p ( y p g)
• Less cryptic code – easier to understand
• Easier to maintain/update
• Easier to manage large projects w/ multiple programmers
• Easier to manage large projects w/ multiple programmers
• More portable (to an extent)
• ‘C’ is a more marketable skill (than BASIC, etc)
Why NOT program in ‘C’?
• $$$ for a compiler
$$$ for a compiler
• Assembly potentially more compact code (memory size, execution speed)
- Assuming you have a competent assembly programmer on-hand
M b i k / i f ll j t t d i ASM (< 1kb t )
3
• May be quicker/easier for very small projects to code in ASM (< 1kbyte)
‘C’ Programming Language
C vs. Assembly Language
C Assembly Machine
C Assembly Machine
i = 3 LDAA #$03 4000:86 03
STAA $800 4002:7A 08 00
j = 5 LDAA #$05 4005:86 05
STAA $801 4007:7A 08 01
$
k = i + j LDAA $800 400A:B6 08 00
ADDA $801 400D:BB 08 01
ADDA $801 400D:BB 08 01
STAA $803 4010:7A 08 03
A bl t
Compiler converts
D l d d
4
Assembler converts Downloaded
to chip
‘C’ Programming Language
Going from Assembly to Machine Code requires an Assembler
Example.asm Assembler
Example.s19
Linker
Source code Executable - 1s & 0s
that get loaded into
Object code
program memory
5
‘C’ Programming Language
Going from ‘C’ to Machine Code requires a Compiler,
Assembler & Linker Adds lib function calls
Example.c
Compiler
Example.s19
Pre-
processor Linker
Adds .lib, function calls,
and links all object files
p
Source code
p
Compile
Optimize
Example.o
Assembler
Example asm
Source code
Executable - 1s & 0s that
get loaded into program
memory
Optimize
Iterative process,
multiple passes
Example.asm
memory
Usually a compiler option
– optimize for code size,
execution speed
multiple passes
execution speed
‘C’ Programming Language
Basic Program Structure
#______ are preprocessor directives
#include < stdio.h>
Every program needs 1 (and only 1)
void main( )
{
Every program needs 1 (and only 1)
main function
printf("nHello Worldn");
} printf( ) is a function defined in stdio.h
Function is in brackets
‘C’ Programming Language
Use Lots of Comments!!!
1. Traditional ‘C’ comments
/* Everything between is a comment */
2. C++ style comments
// Everything on this line is a comment
// Everything on this line is a comment
3. Preprocessor-enforced comments
#if (0)
Everything between is a comment;
8
#endif
‘C’ Programming Language
Variable Names & Keywords
Variable Names - can be up to 31 characters long
- may use upper/lower case letters, digits 0-9, and ‘_’
- compiler & library vars use ‘_’ as first char in names
Reserved keywords – can’t be used for var names
auto double int struct
break else long switch
case enum register typedef
h t t i
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
default goto sizeof volatile
do if static while
‘C’ Programming Language
Data Types
char 8 bits Integers types are signed by
short 16 bits default.
l 32 bi
long 32 bits
long long 64 bits
float 32 bits +/-10+/-38 ~ 6.5 significant digits
float 32 bits / 10 6.5 significant digits
double 64 bits +/-10+/-308 ~ 15 significant digits
int Usually depends on architecture
(32-bits for x86s 16 bits for HCS08)
Signed #s use Two’s complement form
Signed #s use Two s complement form
• signed char is 8 bits, range is -128 to +127
• unsigned char is 8 bits, range is 0 to +255
‘C’ Programming Language
1
0
1
1
1
0
0
1
Straight binary (unsigned)
MSB LSB
= 0x9D
1
0
1
1
1
0
0
1
1 x 27 + 0 x 26 + 0 x 25 + 1 x 24 + 1 x 23 + 1 x 22 + 0 x 21 + 1 x 20 = 15710
0x9D
Total range of possible values is 010 Æ 25510
To di ide b t o shift one position to the left
To divide by two, shift one position to the left
MSB LSB
LSB = 0 if even #
0
1
1
1
0
0
1
0
0 x 27 + 1 x 26 + 0 x 25 + 0 x 24 + 1 x 23 + 1 x 22 + 1 x 21 + 0 x 20 = 7810
= 1 if odd #
= 0x4E
‘C’ Programming Language
Useful #
conversion
chart
12
‘C’ Programming Language
ASCII text
A i St d d C d
ASCII i f d i
American Standard Code
for Information Interchange
• ASCII is often used in
computer systems to
represent characters
H
- Hyperterm
- Many LCD screens
13
‘C’ Programming Language
Math Operators
+ Addition
- Subtraction
- Subtraction
* Multiplication Note: ‘*’ and ‘/’ have higher
/ Division precedence than ‘+’ and ‘-’
p
% Modulus operator
if Ans, Rem and the numbers 5 and 8 are integers, then
Ans = 5/8; // result is 0
Rem = 5%8; // result is 5
‘C’ Programming Language
Convert a number to ASCII
i d h l
unsigned char value;
…
value = 0xF5; // 245 base 10
;
temp1 = (value%10)+0x30;
temp2 = value/10;
temp3 = temp2/10+0x30;
2
On hyperterm window you’d see …
temp3 = temp2/10+0x30;
temp2 = temp2%10+0x30;
printf(temp3”n"); // MSB
4
5
printf(temp2”n");
printf(temp1”n"); // LSB
‘C’ Programming Language
Increment & Decrement
i = i + 1; is equivalent to … i++;
k = k - 1; “ “ k--;
C ll d t i ti d d t d ti
C allows pre- and post-incrementing and pre- and post-decrementing
num = 1;
while (num++ < 3)
num = 0;
while (++num < 3)
{
// do something
};
{
// do something
}
Are these
code snippets
equivalent?
equivalent?
‘C’ Programming Language
Shift
x = 8;
x = x >> 2;
0000 1000 (810) → 0000 0010 (210)
Equivalent to dividing by 22
y = 8;
y = y << 3;
0000 1000 (8 ) 0100 0000 (64 )
0000 1000 (810) → 0100 0000 (6410)
Equivalent to multiplying by 23
May take less clocks than executing a multiply or divide instruction
‘C’ Programming Language
Logical Operators
NOTE:
< less than
<= less than or equal to
h
if (0); // Is always false
if (1); // Is always true
> greater than
>= greater than or equal to
== is equal to
if (1); // Is always true
== is equal to
!= is not equal to
&& AND
Logical operators are binary operators
The statement
|| OR if (A >= B) …
Returns 0 if the statement is false and 1
if true
‘C’ Programming Language
Bitwise Operators
& Bitwise AND
| Bitwise OR
~ Bitwise NOT
^ Bitwise Exclusive OR
Note:
B &= MASK;
#define MASK (%1111 0000)
A = 0x88 & MASK; // result is 0x80
is equivalent to
B = B & MASK;
A 0x88 & MASK; // result is 0x80
B = 0x88 | MASK; // result is 0xF8
C = 0x88 ^ MASK; // result is 0x78
;
C = ~C; // result is 0x87
‘C’ Programming Language
Loops – for loop
start end increment
for (i=0; i<10; i++)
power[i] = volts[i] * current[i];
for(;;)
{
//loop forever
}
}
‘C’ Programming Language
Loops – while loop
cntr = 0;
while (cntr < 10) // loop will execute 10 times
{
{
num[cntr] = 5;
cntr++;
}
}
while (1)
{
// this loop will execute forever
}
}
‘C’ Programming Language
Loops – do while loop
cntr = 0;
d
do
{
[ ]
num[cntr] = 5;
cntr++;
} while (cntr < 10); // still executes 10 times
‘C’ Programming Language
If statement
if (num <= 10 || eli==7)
{
// d thi
‘else if’ and ‘else’ never get tested if
“if (num<=10) is TRUE
// do something
}
else if (num >= 20)
{
Can have only one ‘if’ and one ‘else’, but
{
// do something
}
y
as many ‘else if’s as you want
else
{
// default case
}
‘C’ Programming Language
The switch statement
switch (buffer[3]) If you were to look at the assembly
switch (buffer[3])
{
case 1:
// execute function 1
b k
If you were to look at the assembly
or machine code, switch and if-else
statements are functionally
equivalent. But if there are many
break;
case 2:
//function eli
case 3:
cases, a switch statement is usually
easier to look at, add to, etc.
case 5:
// execute function 2
break;
Switch statements lend themselves
well to things like command parsers
d t t hi
…
case n:
// execute function n
break;
and state machines.
default:
// execute function _ERROR
break;
}
‘C’ Programming Language
Functions
FUNCTION
type function_name( type, type, type, …) PROTOTYPE
- At top of ‘C’ file or
included in header
Return argument – can
be char, int, etc.
‘void’ means no return
Values passed to a
function – one way
copy to function
included in header
file
void means no return
argument
If not ‘void’ function
d ‘ t ( l )’
copy to function
‘void’ means no
values passed
needs a ‘return (value)’
statement at the end
‘C’ Programming Language
// Function PROTOTYPES
// Includes
#include <Timer.h>
Functions (cont.)
// Function PROTOTYPES
void config_Timer (void);
// Function PROTOTYPES
void config_IO (void);
// MAIN Routine
void main (void)
void main (void)
{
// Configure Port I/O
config_IO ();
// Initialize Timer 3
fi Ti ()
config_Timer();
}
}
// Other Routines
Timer.h
void config_IO (void)
{
//Set up micro I/O ports
} Main.c
EE403W.4 Spring 26
‘C’ Programming Language
Note on Recursion / Reentrancy
n! = n * (n-1) * (n-2) * …
l f i l (i )
Function calculates a factorial by
calling itself until n = 0
long factorial (int n)
{
if (n == 0)
calling itself until n = 0.
Need to be careful doing this, every
function call puts multiple bytes on the
if (n == 0)
return (1);
else
function call puts multiple bytes on the
stack. If not terminated correctly could
overflow the stack very easily.
return (n * factorial (n-1));
}
‘C’ Programming Language
Why use functions?
• Makes code more modular – easier to read
• If sections of code are repeated multiple times, putting that
code in a function saves code space
• If section of code is not repeated more than once, function call
adds extra code (and hence runtime)
adds extra code (and hence runtime)
• What if you want the modularity but not the extra stuff, what
f y y ff
do you do?
‘C’ Programming Language
Macros
A way to “modularize” code without the penalty of a function call
In ‘file_name.h’ …
#define square (x) (x) * (x)
In ‘file name.c’ …
In file_name.c …
Power = square (I) * R;
If you look at the compiled code the macro definition gets inserted
If you look at the compiled code, the macro definition gets inserted
as in-line code, whereas functions get treated as jumps to a single
block of code somewhere else in memory.
‘C’ Programming Language
Local Variables vs. Global Variables
// Function PROTOTYPES
void calc_number (void);
static unsigned char this_is_global;
// Main Routine
void main (void)
void main (void)
{
unsigned char this_is_local;
this_is_global = 10;
this_is_local = this_is_global;
This won’t compile - error.
calc_number ( );
}
// Other Routines
void calc number (void)
Why? Global var’s get dedicated
memory locations, local variables
void calc_number (void)
{
unsigned temp1, temp2;
temp1 = this_is_global;
temp2 = this_is_local;
}
all share a section of ‘scratchpad’
memory – the compiler figures out
exactly which variable gets which
l ti t ti
} memory location at any one time.
‘C’ Programming Language
How to share Global Variables among multiple ‘C’ files
// Main.c
#include <main.h>
unsigned char this_is_global = 7;
// Main Routine
id i ( id)
// main.h
extern unsigned char this_is_global;
extern void calc_number ( );
void main (void)
{
unsigned char this_is_local;
this_is_local = this_is_global;
calc_number ( );
// Algorithm.c
#include <main.h>
// R ti
run_algorithm ( );
}
// Other Routines
void calc number (void)
// Routine
void run_algorithm (void)
{
unsigned char this_is_local_too;
this is local too = this is global;
void calc_number (void)
{
unsigned temp1;
temp1 = this_is_global;
}
_ _ _ _ _g
calc_number ( );
}
Variables and functions can be external / global.
‘C’ Programming Language
Arrays
unsigned char cnum[5] = {5, 7, 2, 8, 17}; // 5 bytes of memory
unsigned int inum[5]; // 10 bytes
fl f [5] // 20 b
float fnum[5]; // 20 bytes
Mem Location Value
Mem Location Value
0100 5
0101 7
Address of cnum[0]
0102 2
0103 8
0104 17
0104 17
‘C’ Programming Language
Multidimensional Arrays
unsigned char cnum[2][3];
cnum[0][0] = 3;
cnum[0][1] = 6;
i l
cnum[0][1] 6;
cnum[0][2] = 8;
cnum[1][0] = 1;
[1][1] 0
Mem Location Value
0100 3
0101 6
cnum[1][1] = 0;
cnum[1][2] = 12;
0101 6
0102 8
0103 1
0104 0
0105 12
‘C’ Programming Language
Pointers
Memory
Location
Value
* - deference operator
& - address of
Location
F004 F00C
F008
p
q
unsigned int *p, *q;
unsigned int i;
F00C 5
F010 F004
F014
i
r
g ;
unsigned int **r
F014
i = 5;
p = &i;
r = &p;
*p = 0; // like saying “set the contents of
// memory location pointed to by p
r &p;
// to 0” (i.e. i = 0)
**r = ?
‘C’ Programming Language
Pointers – another example
You are working on a 16 bit machine, and the memory
location at absolute address 0x67A9 needs to be set to an
initialization value of 0xAA55. How do you do it?
i t * t
int *ptr;
ptr = (int *) 0x67A9; //Type Cast!
* 0 AA55
*ptr = 0xAA55;
PORTA_DATA_REG = 1;
#define PORTA_DATA_REG *(unsigned char *)(0x0004)
‘C’ Programming Language
Advantage of Using Pointers
• Allows you to directly access machine
function call
memory
– i.e. contents of specific registers
• Helps to modularize code
BufCopy (num, &outputBuf, &inputBuf);
– can pass a pointer in a function call
void BufCopy (char nbytes, char *DstBufPtr, char *SrcBufPtr)
{
while (nbytes-- > 0)
{
{
*DstBufPtr = *SrcBufPtr;
DstBufPtr++; SrcBufPtr++;
}
}
function
}
‘C’ Programming Language
typedef, struct and union
struct FOURBYTES
{
char byte4;
union FLOAT Impedance [8],
unsigned char I_bytes [8][4];
char byte3;
char byte2;
char byte1;
}
Impedance [6].f = 23.556;
I b t [6][0] I d [6] b b t 1
};
typedef union FLOAT
{
I_bytes [6][0] = Impedance [6].b.byte1;
I_bytes [6][1] = Impedance [6].b.byte2;
I_bytes [6][2] = Impedance [6].b.byte3;
I bytes [6][3] = Impedance [6] b byte4;
{
float f;
struct FOURBYTES b;
};
I_bytes [6][3] Impedance [6].b.byte4;
};
‘C’ Programming Language
typedef, struct and union
typedef struct
// Definition
typedef struct
{
unsigned char BIT_0 : 1;
unsigned char BIT 1 : 1;
BITFLAG UserFlags;
// In code
g _ ;
unsigned char BIT_2 : 1;
unsigned char BIT_3 : 1;
unsigned char BIT_4 : 1;
// In code
UserFlags.BIT_0 = TRUE;
UserFlags.BIT_1 = FALSE;
unsigned char BIT_5 : 1;
unsigned char BIT_6 : 1;
unsigned char BIT_7 : 1;
} BITFLAG
} BITFLAG;
#define TRUE (1)
#define FALSE (0)
#define FALSE (0)
‘C’ Programming Language
Preprocessor Directives
#include
#define
#d fi GREEN
#pragma
Conditional compilation
#define GREEN
#define RED
…
#if (GREEN)
p
#if / #ifdef / #ifndef
#elif
#if (GREEN)
//compile this code
…
#elif (RED)
#else
#endif
#elif (RED)
// compile this code
…
#endif
‘C’ Programming Language
Other keywords –
static
void process_buttons (void)
{
static
1. Local variables declared
static maintain their value
static unsigned char button_old = 0;
button_new = PORTA & %0000 0001;
if (button_new & button_old)
{
static maintain their value
between function
invocations
{
// button press TRUE 2 times
// in a row do something!
}
b ld b
2. Functions declared static
can only be called by
functions in the same
button_old = button_new;
}
module
‘C’ Programming Language
Other keywords – volatile
Wh i bl i d l d l il h il i f d
• When a variable is declared volatile, the compiler is forced to
reload that variable every time it is used in the program.
Reserved for variables that change frequently.
- Hardware Registers
- Variables used in interrupt service routines (ISR)
Variables shared by multiple tasks in multi threaded apps
- Variables shared by multiple tasks in multi-threaded apps
Ex.
volatile unsigned char UART Buffer [48];
volatile unsigned char UART_Buffer [48];
// UART_Buffer is used in the UART ISR to
// record the incoming data stream
‘C’ Programming Language
Other keywords – const
• Doesn’t mean ‘constant’, means ‘read-only’
• The program may not attempt to write a value to a const
i bl
variable
• Generates tighter code, compiler can take advantage of some
additional optimizations
p

More Related Content

PPTX
Microcontroller lec 3
PPTX
C for Engineers
PPTX
C programming language
PPT
C tutorial
PPTX
Top Programming Training Centre in Jalandhar
PPTX
Top Programming Training Centre in Jalandhar
DOCX
C tutorials
Microcontroller lec 3
C for Engineers
C programming language
C tutorial
Top Programming Training Centre in Jalandhar
Top Programming Training Centre in Jalandhar
C tutorials

Similar to Lenguaje de Programación en C Presentacion (20)

PPTX
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
PPTX
cmp104 lec 8
PDF
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
ODP
Programming basics
PDF
Embedded_C_1711824726engéiiiring_with_the_best.pdf
DOC
Datastructure notes
PPT
c_tutorial_2.ppt
PDF
C programing Tutorial
PPTX
Data Type in C Programming
DOC
C notes for exam preparation
PPTX
presentation_c_basics_1589366177_381682.pptx
PPTX
Fundamentals of computer programming by Dr. A. Charan Kumari
PPTX
Unit 1.1 - Introduction to C.pptx
DOC
Basic c
ODP
C prog ppt
PDF
C Programming - Refresher - Part I
PPT
C the basic concepts
PPTX
What is c
PPTX
First c program
PPTX
Introduction to c programming
NTRODUCTION TO COMPUTER PROGRAMMING Loop as repetitive statement,
cmp104 lec 8
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Programming basics
Embedded_C_1711824726engéiiiring_with_the_best.pdf
Datastructure notes
c_tutorial_2.ppt
C programing Tutorial
Data Type in C Programming
C notes for exam preparation
presentation_c_basics_1589366177_381682.pptx
Fundamentals of computer programming by Dr. A. Charan Kumari
Unit 1.1 - Introduction to C.pptx
Basic c
C prog ppt
C Programming - Refresher - Part I
C the basic concepts
What is c
First c program
Introduction to c programming
Ad

Recently uploaded (20)

PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
PPT on Performance Review to get promotions
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
Structs to JSON How Go Powers REST APIs.pdf
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
Well-logging-methods_new................
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
web development for engineering and engineering
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
PPT on Performance Review to get promotions
Mechanical Engineering MATERIALS Selection
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
CH1 Production IntroductoryConcepts.pptx
Foundation to blockchain - A guide to Blockchain Tech
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Lesson 3_Tessellation.pptx finite Mathematics
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Structs to JSON How Go Powers REST APIs.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Embodied AI: Ushering in the Next Era of Intelligent Systems
Internet of Things (IOT) - A guide to understanding
Well-logging-methods_new................
bas. eng. economics group 4 presentation 1.pptx
web development for engineering and engineering
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Ad

Lenguaje de Programación en C Presentacion

  • 1. EE403W Senior Project Design Design Section 4 Embedded Systems Section 4 – Embedded Systems C Tutorial
  • 2. QUIZ // initialization section unsigned char x = 2; unsigned char x 2; // execution section if (x = 7) x = 0; Aft thi d h t i th l t d i th • After this code runs, what is the value stored in the memory location referenced by the variable ‘x’? 2
  • 3. ‘C’ Programming Language Why program microcontrollers in ‘C’? • More compact code (visually speaking) p ( y p g) • Less cryptic code – easier to understand • Easier to maintain/update • Easier to manage large projects w/ multiple programmers • Easier to manage large projects w/ multiple programmers • More portable (to an extent) • ‘C’ is a more marketable skill (than BASIC, etc) Why NOT program in ‘C’? • $$$ for a compiler $$$ for a compiler • Assembly potentially more compact code (memory size, execution speed) - Assuming you have a competent assembly programmer on-hand M b i k / i f ll j t t d i ASM (< 1kb t ) 3 • May be quicker/easier for very small projects to code in ASM (< 1kbyte)
  • 4. ‘C’ Programming Language C vs. Assembly Language C Assembly Machine C Assembly Machine i = 3 LDAA #$03 4000:86 03 STAA $800 4002:7A 08 00 j = 5 LDAA #$05 4005:86 05 STAA $801 4007:7A 08 01 $ k = i + j LDAA $800 400A:B6 08 00 ADDA $801 400D:BB 08 01 ADDA $801 400D:BB 08 01 STAA $803 4010:7A 08 03 A bl t Compiler converts D l d d 4 Assembler converts Downloaded to chip
  • 5. ‘C’ Programming Language Going from Assembly to Machine Code requires an Assembler Example.asm Assembler Example.s19 Linker Source code Executable - 1s & 0s that get loaded into Object code program memory 5
  • 6. ‘C’ Programming Language Going from ‘C’ to Machine Code requires a Compiler, Assembler & Linker Adds lib function calls Example.c Compiler Example.s19 Pre- processor Linker Adds .lib, function calls, and links all object files p Source code p Compile Optimize Example.o Assembler Example asm Source code Executable - 1s & 0s that get loaded into program memory Optimize Iterative process, multiple passes Example.asm memory Usually a compiler option – optimize for code size, execution speed multiple passes execution speed
  • 7. ‘C’ Programming Language Basic Program Structure #______ are preprocessor directives #include < stdio.h> Every program needs 1 (and only 1) void main( ) { Every program needs 1 (and only 1) main function printf("nHello Worldn"); } printf( ) is a function defined in stdio.h Function is in brackets
  • 8. ‘C’ Programming Language Use Lots of Comments!!! 1. Traditional ‘C’ comments /* Everything between is a comment */ 2. C++ style comments // Everything on this line is a comment // Everything on this line is a comment 3. Preprocessor-enforced comments #if (0) Everything between is a comment; 8 #endif
  • 9. ‘C’ Programming Language Variable Names & Keywords Variable Names - can be up to 31 characters long - may use upper/lower case letters, digits 0-9, and ‘_’ - compiler & library vars use ‘_’ as first char in names Reserved keywords – can’t be used for var names auto double int struct break else long switch case enum register typedef h t t i char extern return union const float short unsigned continue for signed void default goto sizeof volatile default goto sizeof volatile do if static while
  • 10. ‘C’ Programming Language Data Types char 8 bits Integers types are signed by short 16 bits default. l 32 bi long 32 bits long long 64 bits float 32 bits +/-10+/-38 ~ 6.5 significant digits float 32 bits / 10 6.5 significant digits double 64 bits +/-10+/-308 ~ 15 significant digits int Usually depends on architecture (32-bits for x86s 16 bits for HCS08) Signed #s use Two’s complement form Signed #s use Two s complement form • signed char is 8 bits, range is -128 to +127 • unsigned char is 8 bits, range is 0 to +255
  • 11. ‘C’ Programming Language 1 0 1 1 1 0 0 1 Straight binary (unsigned) MSB LSB = 0x9D 1 0 1 1 1 0 0 1 1 x 27 + 0 x 26 + 0 x 25 + 1 x 24 + 1 x 23 + 1 x 22 + 0 x 21 + 1 x 20 = 15710 0x9D Total range of possible values is 010 Æ 25510 To di ide b t o shift one position to the left To divide by two, shift one position to the left MSB LSB LSB = 0 if even # 0 1 1 1 0 0 1 0 0 x 27 + 1 x 26 + 0 x 25 + 0 x 24 + 1 x 23 + 1 x 22 + 1 x 21 + 0 x 20 = 7810 = 1 if odd # = 0x4E
  • 12. ‘C’ Programming Language Useful # conversion chart 12
  • 13. ‘C’ Programming Language ASCII text A i St d d C d ASCII i f d i American Standard Code for Information Interchange • ASCII is often used in computer systems to represent characters H - Hyperterm - Many LCD screens 13
  • 14. ‘C’ Programming Language Math Operators + Addition - Subtraction - Subtraction * Multiplication Note: ‘*’ and ‘/’ have higher / Division precedence than ‘+’ and ‘-’ p % Modulus operator if Ans, Rem and the numbers 5 and 8 are integers, then Ans = 5/8; // result is 0 Rem = 5%8; // result is 5
  • 15. ‘C’ Programming Language Convert a number to ASCII i d h l unsigned char value; … value = 0xF5; // 245 base 10 ; temp1 = (value%10)+0x30; temp2 = value/10; temp3 = temp2/10+0x30; 2 On hyperterm window you’d see … temp3 = temp2/10+0x30; temp2 = temp2%10+0x30; printf(temp3”n"); // MSB 4 5 printf(temp2”n"); printf(temp1”n"); // LSB
  • 16. ‘C’ Programming Language Increment & Decrement i = i + 1; is equivalent to … i++; k = k - 1; “ “ k--; C ll d t i ti d d t d ti C allows pre- and post-incrementing and pre- and post-decrementing num = 1; while (num++ < 3) num = 0; while (++num < 3) { // do something }; { // do something } Are these code snippets equivalent? equivalent?
  • 17. ‘C’ Programming Language Shift x = 8; x = x >> 2; 0000 1000 (810) → 0000 0010 (210) Equivalent to dividing by 22 y = 8; y = y << 3; 0000 1000 (8 ) 0100 0000 (64 ) 0000 1000 (810) → 0100 0000 (6410) Equivalent to multiplying by 23 May take less clocks than executing a multiply or divide instruction
  • 18. ‘C’ Programming Language Logical Operators NOTE: < less than <= less than or equal to h if (0); // Is always false if (1); // Is always true > greater than >= greater than or equal to == is equal to if (1); // Is always true == is equal to != is not equal to && AND Logical operators are binary operators The statement || OR if (A >= B) … Returns 0 if the statement is false and 1 if true
  • 19. ‘C’ Programming Language Bitwise Operators & Bitwise AND | Bitwise OR ~ Bitwise NOT ^ Bitwise Exclusive OR Note: B &= MASK; #define MASK (%1111 0000) A = 0x88 & MASK; // result is 0x80 is equivalent to B = B & MASK; A 0x88 & MASK; // result is 0x80 B = 0x88 | MASK; // result is 0xF8 C = 0x88 ^ MASK; // result is 0x78 ; C = ~C; // result is 0x87
  • 20. ‘C’ Programming Language Loops – for loop start end increment for (i=0; i<10; i++) power[i] = volts[i] * current[i]; for(;;) { //loop forever } }
  • 21. ‘C’ Programming Language Loops – while loop cntr = 0; while (cntr < 10) // loop will execute 10 times { { num[cntr] = 5; cntr++; } } while (1) { // this loop will execute forever } }
  • 22. ‘C’ Programming Language Loops – do while loop cntr = 0; d do { [ ] num[cntr] = 5; cntr++; } while (cntr < 10); // still executes 10 times
  • 23. ‘C’ Programming Language If statement if (num <= 10 || eli==7) { // d thi ‘else if’ and ‘else’ never get tested if “if (num<=10) is TRUE // do something } else if (num >= 20) { Can have only one ‘if’ and one ‘else’, but { // do something } y as many ‘else if’s as you want else { // default case }
  • 24. ‘C’ Programming Language The switch statement switch (buffer[3]) If you were to look at the assembly switch (buffer[3]) { case 1: // execute function 1 b k If you were to look at the assembly or machine code, switch and if-else statements are functionally equivalent. But if there are many break; case 2: //function eli case 3: cases, a switch statement is usually easier to look at, add to, etc. case 5: // execute function 2 break; Switch statements lend themselves well to things like command parsers d t t hi … case n: // execute function n break; and state machines. default: // execute function _ERROR break; }
  • 25. ‘C’ Programming Language Functions FUNCTION type function_name( type, type, type, …) PROTOTYPE - At top of ‘C’ file or included in header Return argument – can be char, int, etc. ‘void’ means no return Values passed to a function – one way copy to function included in header file void means no return argument If not ‘void’ function d ‘ t ( l )’ copy to function ‘void’ means no values passed needs a ‘return (value)’ statement at the end
  • 26. ‘C’ Programming Language // Function PROTOTYPES // Includes #include <Timer.h> Functions (cont.) // Function PROTOTYPES void config_Timer (void); // Function PROTOTYPES void config_IO (void); // MAIN Routine void main (void) void main (void) { // Configure Port I/O config_IO (); // Initialize Timer 3 fi Ti () config_Timer(); } } // Other Routines Timer.h void config_IO (void) { //Set up micro I/O ports } Main.c EE403W.4 Spring 26
  • 27. ‘C’ Programming Language Note on Recursion / Reentrancy n! = n * (n-1) * (n-2) * … l f i l (i ) Function calculates a factorial by calling itself until n = 0 long factorial (int n) { if (n == 0) calling itself until n = 0. Need to be careful doing this, every function call puts multiple bytes on the if (n == 0) return (1); else function call puts multiple bytes on the stack. If not terminated correctly could overflow the stack very easily. return (n * factorial (n-1)); }
  • 28. ‘C’ Programming Language Why use functions? • Makes code more modular – easier to read • If sections of code are repeated multiple times, putting that code in a function saves code space • If section of code is not repeated more than once, function call adds extra code (and hence runtime) adds extra code (and hence runtime) • What if you want the modularity but not the extra stuff, what f y y ff do you do?
  • 29. ‘C’ Programming Language Macros A way to “modularize” code without the penalty of a function call In ‘file_name.h’ … #define square (x) (x) * (x) In ‘file name.c’ … In file_name.c … Power = square (I) * R; If you look at the compiled code the macro definition gets inserted If you look at the compiled code, the macro definition gets inserted as in-line code, whereas functions get treated as jumps to a single block of code somewhere else in memory.
  • 30. ‘C’ Programming Language Local Variables vs. Global Variables // Function PROTOTYPES void calc_number (void); static unsigned char this_is_global; // Main Routine void main (void) void main (void) { unsigned char this_is_local; this_is_global = 10; this_is_local = this_is_global; This won’t compile - error. calc_number ( ); } // Other Routines void calc number (void) Why? Global var’s get dedicated memory locations, local variables void calc_number (void) { unsigned temp1, temp2; temp1 = this_is_global; temp2 = this_is_local; } all share a section of ‘scratchpad’ memory – the compiler figures out exactly which variable gets which l ti t ti } memory location at any one time.
  • 31. ‘C’ Programming Language How to share Global Variables among multiple ‘C’ files // Main.c #include <main.h> unsigned char this_is_global = 7; // Main Routine id i ( id) // main.h extern unsigned char this_is_global; extern void calc_number ( ); void main (void) { unsigned char this_is_local; this_is_local = this_is_global; calc_number ( ); // Algorithm.c #include <main.h> // R ti run_algorithm ( ); } // Other Routines void calc number (void) // Routine void run_algorithm (void) { unsigned char this_is_local_too; this is local too = this is global; void calc_number (void) { unsigned temp1; temp1 = this_is_global; } _ _ _ _ _g calc_number ( ); } Variables and functions can be external / global.
  • 32. ‘C’ Programming Language Arrays unsigned char cnum[5] = {5, 7, 2, 8, 17}; // 5 bytes of memory unsigned int inum[5]; // 10 bytes fl f [5] // 20 b float fnum[5]; // 20 bytes Mem Location Value Mem Location Value 0100 5 0101 7 Address of cnum[0] 0102 2 0103 8 0104 17 0104 17
  • 33. ‘C’ Programming Language Multidimensional Arrays unsigned char cnum[2][3]; cnum[0][0] = 3; cnum[0][1] = 6; i l cnum[0][1] 6; cnum[0][2] = 8; cnum[1][0] = 1; [1][1] 0 Mem Location Value 0100 3 0101 6 cnum[1][1] = 0; cnum[1][2] = 12; 0101 6 0102 8 0103 1 0104 0 0105 12
  • 34. ‘C’ Programming Language Pointers Memory Location Value * - deference operator & - address of Location F004 F00C F008 p q unsigned int *p, *q; unsigned int i; F00C 5 F010 F004 F014 i r g ; unsigned int **r F014 i = 5; p = &i; r = &p; *p = 0; // like saying “set the contents of // memory location pointed to by p r &p; // to 0” (i.e. i = 0) **r = ?
  • 35. ‘C’ Programming Language Pointers – another example You are working on a 16 bit machine, and the memory location at absolute address 0x67A9 needs to be set to an initialization value of 0xAA55. How do you do it? i t * t int *ptr; ptr = (int *) 0x67A9; //Type Cast! * 0 AA55 *ptr = 0xAA55; PORTA_DATA_REG = 1; #define PORTA_DATA_REG *(unsigned char *)(0x0004)
  • 36. ‘C’ Programming Language Advantage of Using Pointers • Allows you to directly access machine function call memory – i.e. contents of specific registers • Helps to modularize code BufCopy (num, &outputBuf, &inputBuf); – can pass a pointer in a function call void BufCopy (char nbytes, char *DstBufPtr, char *SrcBufPtr) { while (nbytes-- > 0) { { *DstBufPtr = *SrcBufPtr; DstBufPtr++; SrcBufPtr++; } } function }
  • 37. ‘C’ Programming Language typedef, struct and union struct FOURBYTES { char byte4; union FLOAT Impedance [8], unsigned char I_bytes [8][4]; char byte3; char byte2; char byte1; } Impedance [6].f = 23.556; I b t [6][0] I d [6] b b t 1 }; typedef union FLOAT { I_bytes [6][0] = Impedance [6].b.byte1; I_bytes [6][1] = Impedance [6].b.byte2; I_bytes [6][2] = Impedance [6].b.byte3; I bytes [6][3] = Impedance [6] b byte4; { float f; struct FOURBYTES b; }; I_bytes [6][3] Impedance [6].b.byte4; };
  • 38. ‘C’ Programming Language typedef, struct and union typedef struct // Definition typedef struct { unsigned char BIT_0 : 1; unsigned char BIT 1 : 1; BITFLAG UserFlags; // In code g _ ; unsigned char BIT_2 : 1; unsigned char BIT_3 : 1; unsigned char BIT_4 : 1; // In code UserFlags.BIT_0 = TRUE; UserFlags.BIT_1 = FALSE; unsigned char BIT_5 : 1; unsigned char BIT_6 : 1; unsigned char BIT_7 : 1; } BITFLAG } BITFLAG; #define TRUE (1) #define FALSE (0) #define FALSE (0)
  • 39. ‘C’ Programming Language Preprocessor Directives #include #define #d fi GREEN #pragma Conditional compilation #define GREEN #define RED … #if (GREEN) p #if / #ifdef / #ifndef #elif #if (GREEN) //compile this code … #elif (RED) #else #endif #elif (RED) // compile this code … #endif
  • 40. ‘C’ Programming Language Other keywords – static void process_buttons (void) { static 1. Local variables declared static maintain their value static unsigned char button_old = 0; button_new = PORTA & %0000 0001; if (button_new & button_old) { static maintain their value between function invocations { // button press TRUE 2 times // in a row do something! } b ld b 2. Functions declared static can only be called by functions in the same button_old = button_new; } module
  • 41. ‘C’ Programming Language Other keywords – volatile Wh i bl i d l d l il h il i f d • When a variable is declared volatile, the compiler is forced to reload that variable every time it is used in the program. Reserved for variables that change frequently. - Hardware Registers - Variables used in interrupt service routines (ISR) Variables shared by multiple tasks in multi threaded apps - Variables shared by multiple tasks in multi-threaded apps Ex. volatile unsigned char UART Buffer [48]; volatile unsigned char UART_Buffer [48]; // UART_Buffer is used in the UART ISR to // record the incoming data stream
  • 42. ‘C’ Programming Language Other keywords – const • Doesn’t mean ‘constant’, means ‘read-only’ • The program may not attempt to write a value to a const i bl variable • Generates tighter code, compiler can take advantage of some additional optimizations p