Title: Introduction to C Programming K Broerman Mentor, Team 868 TechHounds December, 2005
1Introduction to C Programming K
BroermanMentor, Team 868 TechHoundsDecember,
2005
2Disclaimer!
- This introduction to C will not make you a
computer scientist! 0 - However, after this overview you should be able
to read and understand some of the default FRC
code. )
3Some Wisdom (no extra charge!)
- "Computer science is no more about computers than
astronomy is about telescopes." - E. W. Dijkstra
4A Very Simple C Program
- / This program will print out the message This
is a C program / - include ltstdio.hgt / find and use the stdio
header file / - main()
-
- printf ("This is a C program\n) / \n means
add a newline (linefeed) / -
5Files and what they do
- Header files (.h)
- Header files are used for defining macros a.k.a.
aliases, and prototyping methods, and can also be
used for defining structs. Macros are basically
a way of referencing an unknown variable, in FRC
programming these commonly reference inputs and
outputs so that when a device is hooked up to a
different port only 1 line needs to be changed
instead of a very large number of lines. A
method prototype is part of the C language and is
used to let the compiler know what functions can
be called in your C file. The function prototype
requires one line of code, which states the name
of the function, what the function returns and
what must be passed into the function. Structs
are sort of like data types but they can hold
multiple variables when they are used.
6Files and what they do
- C Source Files (.c)
- C files contain the bulk of your code. This is
where the heart and soul of the operations are
housed. All the functions that were prototyped
in your header files are used here.
7Some C Program Syntax (Nuts Bolts)
- Language Component Examples
- pre-processor statements include ltstdio.hgt
- define PI 3.14159
- keywords if, then, return, switch,
- built-in functions ,-,,/,!,,,,,
- variable definitions int motor_speed
- function definitions float square_root(float x)
- executable statements motor_speed 100
- conditional statements if (motor_speed gt 100)
- ANSI library functions printf, memcpy, malloc,
- comments / clip motor speed to prevent
over-current condition /
8C Pre-Processor
- If first column contains , indicates
pre-processor command - Examples
- include ltstdio.hgt / find and use stdio.h /
- define PI 3.14159 / this is a MACRO defn /
- if 0 / conditional compile switch /
- //compiler will skip this code
- else
- //compiler will compile this code
- endif
9C Comments
- 2 forms
- / this is a multi-line comment /
-
- / now is the time for all good men to come
- to the aid of their country /
- // this is a one-line C style comment
- // you need double slashes on each line
- // for multi-line comments
- // like this
-
10C Syntax Rules (partial list)
- Every executable statement must end with a
semicolon - White space (tabs, etc) is ignored by compiler
- Keywords are reserved
- this will generate a compiler error int
switch / front panel switch / - C is case-sensitive!
11C Variable Types
- Variable names are arbitrary (with some
compiler-defined maximum length, typically 32
characters). - C provides the following standard variable types
- int ? integer variable
- unsigned int ? integer variable
- short ? short integer
- long ? long integer
- float ? single precision real (floating point)
variable - char ? character variable
- unsigned char ? character variable
12Integer Data Type Sizes and Limits (MPLAB C18)
- Data Type Size (bits) Minimum
Value Maximum Value - char 8 -128 127
- unsigned char 8 0 255
- int 16 -32768 32767
- unsigned int 16 0 65535
- short 16 -32768 32767
- unsigned short 16 0 65535
- short long 24 -8,388,608 8,388,607
- unsigned short long 24 0 16,777,215
- long 32 -2,147,483,648 2,147,483,647
- unsigned long 32 0 4,294,967,295
13Fun with Math
- You must consider storage size and usage when
selecting variable types! - unsigned char counter 100 // uchar ranges from
0.. 255 - counter counter 150 // counter now equals
250 - counter counter 50 // counter now equals 44!
- int distance 32767 // int ranges from
-32768.. 32767 - distance distance 1 // distance now equals
-32768!
14Floating Point Data Type Sizes and Limits(MPLAB
C18)
- Type Size (bits) Minimum Value Maximum
Value - float 32 1.17549435e - 38 6.80564693e 38
- double data type ? same as float on C18 compiler
15So Why Not Use Floats for Everything?
- Floating point arithmetic is 100x slower than
integer arithmetic! (no FPU on PIC 18F8520 uC) - Your FRC code will not run once the total code
execution time exceeds the FRC main loop timer
(26 mS)! - FRC controller contains only 2 kB of data RAM
16Array Variables
- Arrays are defined using square brackets as
follows - define NUM_EMPLOYEES 10
- define MAX_NAME_LENGTH 256
- int employee_idNUM_EMPLOYEES
- int employee_salaryNUM_EMPLOYEES
- char employee_nameNUM_EMPLOYEESMAX_NAME_LENGTH
//2-D array - memcpy (employee_name2, "Ronald McDonald", 15)
- employee_id2 10023
- employee_salary2 85000 / ooops! /
17Conditionals
-
- Conditionals are used within the if and while
constructs - if (conditional_1)
-
- ...block of statements executed if
conditional_1 is true... -
- else if (conditional_2)
-
- ...block of statements executed if
conditional_2 is true... -
- else
-
- ...block of statements executed otherwise...
-
18Conditionals
- Conditionals are logical operations involving
comparison of quantities (of the same type) using
the conditional operators - lt less than
- lt less than or equal to
- equal to
- ! not equal to
- gt greater than or equal to
- gt greater than
19Boolean (True/False) Operators
- There are 3 boolean operators
- logical AND
- logical OR
- ! logical NOT (inversion)
- Example usage
- fun_weekend !homework !chores
- in_trouble broke_window spilled_milk
- good_student (homework_done !daydreaming)
have_apple
20Functions
- Functions allow large programs to be partitioned
into smaller blocks, each of which is easier to
write, read, and maintain. - A function has the following layout
- return-type function-name ( argument-list-if-neces
sary ) -
- ...local-declarations...
- ...statements
-
- return return-value
-
21Functions
- Functions as stated earlier must be prototypes
in a header file and can have a number of
different attributes to them so here is your
explanation of what these functions do and what
they are used for. First here is an example of a
method with a breakdown of what every part does
- void My_Function(unsigned char x1, unsigned
char x2) -
- pwm03 x1 x2
- return pwm03
-
- My_Function(1, pwm02)
- The first word void is what the function
returns, this can be a data type or it can be
void which means nothing. The second word is the
name of the function and is what the user will
need when they call the function. Inside the
parenthesis are the arguments, which are
variables that the function needs in order to
execute and the code for the function is inside
the brackets. You can have as many arguments
passed into a method as you want but it is not
recommended that you have a function that
required more than three, for the sake of code
readability.
22Symbolic Constants
- // You can define constants of any type by
using the define //
compiler directive. - define SPEED_MIN -100 // max reverse speed
is -127 - define SPEED_MAX 100 // max forward speed
is 127 - int rate_limit( int requested_speed )
-
- if (requested_speed lt SPEED_MIN)
- requested_speed SPEED_MIN
- else if (requested_speed gt SPEED_MAX)
- requested_speed SPEED_MAX
- return requested_speed
-
23Loops
- Most real programs contain some construct that
loops within the program, performing repetitive
actions on a stream of data or a region of
memory. There are several ways to loop in C. - Two of the most common are the while loop and the
for loop - while (expression-is-true)
-
- ...block of statements to execute...
-
- for (expression_1 expression_2 expression_3)
-
- ...block of statements to execute...
-
24Looping while
- The while loop repeats a statement until the test
at the top proves false.
count 0 while(count lt 7) // do something
useful count count 1
25Looping while
- The while loop can also be used for waiting
- while( !rc_dig_in01 ) //limit switch 1
closed? -
- / energize motor! /
-
26Looping for
- The for loop can execute a block of code N times
- for (i0 i lt FILTER_SIZE-1 i)
-
- filter_valuei 0 / init array /
-
- for (month1 month lt 12 month)
-
- / calc days in month /
-
27Some C Syntax Shortcuts
- Example 1
- Standard x x 1
- Shortcut x 1
- Even Better x
- Example 2
- Standard x x 0xF
- Shortcut x 0xF
28Almost Done!
29Data Structures
- A data structure is a user-defined abstract data
type. - Used to group related data as a single unit
(object). - Programs containing data structures are
conceptually easier to write, maintain, and
understand. - Algorithms (methods) are then written to
perform operations on the abstract data type.
30Data Structure Example
- struct database
- int id_number
- int age
- float salary
-
- int main()
-
- struct database employee / There is an
employee variable with modifiable
variables inside it. / - employee.age 22
- employee.id_number 1
- employee.salary 17500.21
-
- promote( employee, 5000.)
-
31C Coding Style
- For readability, use block indentation
- Use descriptive variable names
- avoid keiths_var 2.71828
- One executable statement per line
- avoid motor100 if (switch_off) goto end
wait(ONE_SEC) - Avoid highly nested function calls
- avoid sqrt(1(tan(1-hypot(PIangle/180) ltlt
2 length). - Provide useful comments
- avoid my_var my_var 1 //increment
my_var
32Bad Style! Q What does this code do???
- include ltstdio.hgt
- main(t,_,a)
- char a
-
- /printf("main(d,d,\"s\")\n",t,_,a)/
- return!
- 0ltt?
- (
- ( tlt3? main(-79,-13,a main(-87,1-_,
main(-86, 0, a1 ) a)) 1 ), - ( tlt_? main(t1, _, a ) 3 ),
- ( main ( -94, -27t, a ) t 2 ?
- ( (_lt13) ? main ( 2, _1, "s d
d\n" ) 9 ) - 16
- )
- )
-
- ( tlt0?
- ( tlt-72?
- main( _, t,
33Answer 12 Days of Christmas!
- On the first day of Christmas my true love gave
to me - a partridge in a pear tree.
- On the second day of Christmas my true love gave
to me - two turtle doves
- and a partridge in a pear tree.
- On the third day of Christmas my true love gave
to me - three french hens, two turtle doves
- and a partridge in a pear tree.
- On the fourth day of Christmas my true love gave
to me - four callaing birds, three french hens, two
turtle doves - and a partridge in a pear tree.
- On the fifth day of Christmas my true love gave
to me - five gold rings
- four callaing birds, three french hens, two
turtle doves - and a partridge in a pear tree.
On the eighth day of Christmas my true love gave
to me eight maids a-milking, sevean swans
a-swimming, six geese a-laying, five gold
rings four callaing birds, three french hens,
two turtle doves and a partridge in a pear
tree. On the ninth day of Christmas my true love
gave to me nine laadies dancing, eight maids
a-milking, sevean swans a-swimming, six geese
a-laying, five gold rings four callaing birds,
three french hens, two turtle doves and a
partridge in a pear tree. On the tenth day of
Christmas my true love gave to me ten lords
a-leaping, nine laadies dancing, eight maids
a-milking, sevean swans a-swimming, six geese
a-laying, five gold rings four callaing birds,
three french hens, two turtle doves and a
partridge in a pear tree. On the eleventh day of
Christmas my true love gave to me eleven pipers
piping, ten lords a-leaping, nine laadies
dancing, eight maids a-milking, sevean swans
a-swimming, six geese a-laying, five gold
rings four callaing birds, three french hens,
two turtle doves and a partridge in a pear
tree. On the twelfth day of Christmas my true
love gave to me twelave drummers drumming, eleven
pipers piping, ten lords a-leaping, nine laadies
dancing, eight maids a-milking, sevean swans
a-swimming, six geese a-laying, five gold
rings four callaing birds, three french hens,
two turtle doves and a partridge in a pear tree.
34Common C Gotchas
- Forgetting during equivalence checking
- if (test_score 93) / WRONG! sets test_score
to 93 / - printf (Hooray\n)
- if (test_score 93) / correctly compares
test_score / printf (Hooray\n) -
- Best Method of Prevention
- if (93 test_score)
- printf (Hooray\n)
- C is case sensitive!
- unsigned char wheel_count / NOT the same as
- unsigned char Wheel_count /
-
35The best way to learn C is to write a program
that does something useful!Happy Programming!