Download presentation
Presentation is loading. Please wait.
Published byAnastasia Harper Modified over 6 years ago
1
Introduction to C Programming K Broerman Mentor, Team 868 TechHounds December, 2005
2
Disclaimer! 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. :^)
3
Some Wisdom (no extra charge!)
"Computer science is no more about computers than astronomy is about telescopes." E. W. Dijkstra
4
A Very Simple C Program /* This program will print out the message This is a C program */ #include <stdio.h> /* find and use the stdio header file */ main() { printf ("This is a C program\n“); /* \n means add a newline (linefeed) */ }
5
Some C Program Syntax (Nuts & Bolts)
Language Component Examples pre-processor statements #include <stdio.h> #define PI 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 > 100) { … } ANSI library functions printf, memcpy, malloc, … comments /* clip motor speed to prevent over-current condition */
6
C Pre-Processor If first column contains #, indicates pre-processor command… Examples: #include <stdio.h> /* find and use stdio.h */ #define PI /* this is a MACRO defn */ #if 0 /* conditional compile switch */ //compiler will skip this code #else //compiler will compile this code #endif
7
C 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
8
C 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!
9
C 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
10
Integer Data Type Sizes and Limits (MPLAB C18)
Data Type Size (bits) Minimum Value Maximum Value char unsigned char int unsigned int short unsigned short short long ,388, ,388,607 unsigned short long ,777,215 long ,147,483,648 2,147,483,647 unsigned long ,294,967,295
11
Fun with Math You must consider storage size and usage when selecting variable types! unsigned char counter = 100; // uchar ranges from counter = counter + 150; // counter now equals 250 counter = counter + 50; // counter now equals 44! int distance = 32767; // int ranges from distance = distance + 1; // distance now equals !
12
Floating Point Data Type Sizes and Limits (MPLAB C18)
Type Size (bits) Minimum Value Maximum Value float e e + 38 double data type same as float on C18 compiler
13
So 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
14
Array Variables Arrays are defined using square brackets [ ] as follows: #define NUM_EMPLOYEES 10 #define MAX_NAME_LENGTH 256 int employee_id[NUM_EMPLOYEES]; int employee_salary[NUM_EMPLOYEES]; char employee_name[NUM_EMPLOYEES][MAX_NAME_LENGTH]; //2-D array memcpy (employee_name[2], "Ronald McDonald", 15); employee_id[2] = 10023; employee_salary[2] = 85000; /* ooops! */
15
Conditionals 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...
16
Conditionals Conditionals are logical operations involving comparison of quantities (of the same type) using the conditional operators: < less than <= less than or equal to == equal to != not equal to >= greater than or equal to > greater than
17
Boolean (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;
18
Functions 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-necessary ) { ...local-declarations... ...statements … return return-value; }
19
Symbolic Constants // You can define constants of any type by using the #define // compiler directive. #define SPEED_MIN // max reverse speed is -127 #define SPEED_MAX // max forward speed is +127 int rate_limit( int requested_speed ) { if (requested_speed < SPEED_MIN) requested_speed = SPEED_MIN; else if (requested_speed > SPEED_MAX) requested_speed = SPEED_MAX; return requested_speed; }
20
Loops 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)
21
Looping: while The while loop repeats a statement until the test at the top proves false. count = 0; while(count < 7) { // do something useful count = count + 1; }
22
Looping: while The while loop can also be used for waiting:
while( !rc_dig_in01 ) //limit switch 1 closed? { /* energize motor! */ }
23
Looping: for The for loop can execute a block of code N times:
for (i=0; i < FILTER_SIZE-1; i++) { filter_value[i] = 0; /* init array */ } for (month=1; month <= 12; month++) /* calc # days in month */
24
Some C Syntax Shortcuts
Example 1: Standard x = x + 1; Shortcut x += 1; Even Better x++; Example 2: Standard x = x & 0xF; Shortcut x &= 0xF;
25
Almost Done!
26
Data 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.
27
Data 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 = ; promote( employee, 5000.); }
28
C Coding Style For readability, use block indentation
Use descriptive variable names avoid keiths_var = ; One executable statement per line avoid: motor=100; if (switch_off) goto end; wait(ONE_SEC); Avoid highly nested function calls avoid: sqrt(1+(tan(1-hypot(PI*angle/180) << 2 * length)…. Provide useful comments avoid my_var = my_var + 1; //increment my_var
29
Bad Style! Q: What does this code do???
#include <stdio.h> main(t,_,a) char * a; { /*printf("main(%d,%d,\"%s\")\n",t,_,a);*/ return! 0<t? ( ( t<3? main(-79,-13,a+ main(-87,1-_, main(-86, 0, a+1 ) +a)): 1 ), ( t<_? main(t+1, _, a ) :3 ), ( main ( -94, -27+t, a ) &&t == 2 ? ( (_<13) ? main ( 2, _+1, "%s %d %d\n" ) :9 ) :16 ) : ( t<0? ( t<-72? main( _, t, #q#n+,/+k#;*+,/'r :'d*'3,}{w+K w'K:'+}e#';dq#'l q#'+d'K#!/+k#;\ q#'r}eKK#}w'r}eKK{nl]'/#;#q#n'){)#}w'){){nl]'/+#n';d}rw' i;# ){nl]!/n{n#'; \ r{#w'r nc{nl]'/#{l,+'K {rw' iK{;[{nl]'/w#q#\ n'wk nw' iwk{KK{nl]!/w{%'l##w#' i; :{nl]'/*{q#'ld;r'}{nlwb!/*de}'c ;;\ {nl'-{}rw]'/+,}##'*}#nc,',#nw]'/+kd'+e}+;\ #'rdq#w! nr'/ ') }+}{rl#'{n' ')# }'+}##(!!/") ( t<-50? ( _==*a ? putchar(31[a]): main(-65,_,a+1) ) : main((*a == '/') + t, _, a + 1 ) ( 0<t? main ( 2, 2 , "%s") :*a=='/'|| main(0, main(-61,*a, "!ek;dc .vpbks,fxntdCeghiry") ,a+1) ) ; }
30
Answer: 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 On the fourth day of Christmas my true love gave to me four callaing birds, three french hens, two turtle doves On the fifth day of Christmas my true love gave to me five gold rings; On the sixth day of Christmas my true love gave to me six geese a-laying, five gold rings; On the seventh day of Christmas my true love gave to me sevean swans a-swimming, 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, On the tenth day of Christmas my true love gave to me ten lords a-leaping, On the eleventh day of Christmas my true love gave to me eleven pipers piping, ten lords a-leaping, On the twelfth day of Christmas my true love gave to me twelave drummers drumming, eleven pipers piping, ten lords a-leaping,
31
Common 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) C is case sensitive! unsigned char wheel_count; /* NOT the same as unsigned char Wheel_count; */
32
The best way to learn C is to write a program that does something useful! Happy Programming!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.