1 / 30

‘C’ in a Nutshell

‘C’ in a Nutshell. A “crash course” in C... ...with designs for embedded systems by J. S. Sumey. III. Pot Luck. Arrays. can have an array of elements of a particular data type use brackets to indicate dimensions and number of elements ex: int lottery_numbers[6]; char winner_name[40];

Download Presentation

‘C’ in a Nutshell

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ‘C’ in a Nutshell A “crash course” in C... ...with designs for embedded systems by J. S. Sumey

  2. III. Pot Luck 'C' in a Nutshell by J. Sumey

  3. Arrays • can have an array of elements of a particular data type • use brackets to indicate dimensions and number of elements • ex: int lottery_numbers[6];char winner_name[40]; • subscripts are zero-based • can have multiple dimensions • ex: top3_winners[3][40]; 'C' in a Nutshell by J. Sumey

  4. Structures • named collection of 1 or more variables grouped together for convenient handling • equivalent to records in other languages • used to organize complicated data • may be assigned to, copied, passed to and returned from functions • structure members are accessed via the ‘.’ operator • may be nested 'C' in a Nutshell by J. Sumey

  5. Structure example • a structure declaration to hold sample point of weather data struct tmstruct { /* data structure to hold a time */ int hr, min, sec; } struct wxstruct { /* sample wx data structure */ int temp_in, temp_out, humidity; float barometer; struct tmstruct sample_time; }; 'C' in a Nutshell by J. Sumey

  6. Structure use • declare & use variables using defined weather data structure struct wxstruct sample1, sample2; /* output sample 1’s indoor temp */ printf( “%i”, sample1.temp_in ); /* output sample 2’s barometric pressure */ printf( “%f”, sample2.barometer ); /* output sample 1’s minute */ printf( “%i”, sample1.sample_time.min ); 'C' in a Nutshell by J. Sumey

  7. Arrays of structures • array elements may be compound types, i.e. structures! • this combination, as well as incorporating pointers, provide for powerful data handling • an array of structures is static • an array of structure pointers is dynamic • ex: an array to hold weather data samples for each hour of a day • struct wxstruct wxdata[24]; 'C' in a Nutshell by J. Sumey

  8. Pointers • simply put: a pointer is a variable that contains the address of some piece of data • although easily abused, pointers are one of C’s most useful features • extended / complex data types • multiple function return values • based on linear memory model 'C' in a Nutshell by J. Sumey

  9. Pointer declarations • a variable is declared a pointer by prefixing its name with a unary ‘*’ • ex: char *ch_ptr;means:a) “ch_ptr” is a pointer to a char andb) the expression “*ch_ptr” is a char • this applies to any basic type as well as arrays, structures, functions, etc. 'C' in a Nutshell by J. Sumey

  10. Pointers & function arguments • by default, C function parameters are “pass by value” instead of “pass by reference” • meaning: a function gets a copy of each argument instead of access to the actual argument • this prevents a called function from modifying a variable in the calling function • can be expensive in embedded systems (additional storage allocation & execution time) • may be overridden using pointers and & • this is why scanf() requires ‘&’! 'C' in a Nutshell by J. Sumey

  11. Pointer operators • & - unary operator yielding the address of an object • ex: char ch = ‘k’; char *ch_ptr = &ch; • * - unary operator used to dereference a pointer • i.e. access the object that the pointer points to • ex: putchar( *ch_ptr ); ch_ptr: ch: ‘k’ 'C' in a Nutshell by J. Sumey

  12. Pointers example • a function to swap the values of 2 integers: void swap( int x, int y ) { int temp; temp = x; x = y; y = temp; } main() { int a = 5, b = 10; swap( a, b ); printf( “a = %i b = %i”, a, b ); } What will this program output? OOPS! What’s wrong here? How can this be fixed? 'C' in a Nutshell by J. Sumey

  13. Pointer macros for I/O registers • the pointer mechanism provides a nice solution to accessing I/O registers at fixed memory locations • ex: #define DDRB (*(byte *)0x03) • “DDRB” dereferences physical location 3 as a byte value • remember to use “volatile” for registers that can self-change • i.e. input ports and status registers#define PORTB (*(volatile byte *)0x01) 'C' in a Nutshell by J. Sumey

  14. Libraries • various libraries provide extended functionality beyond the language • every C implementation must include the “standard library” suite at a minimum • input / output • string handling / conversions • dynamic storage management • mathematical routines • header files provide the interface to library resources (data types & functions) 'C' in a Nutshell by J. Sumey

  15. Libraries: standard i/o • provides access to input/output facilities and related data types as standardized by ANSI • uses compiler directive #include <stdio.h> • character, string & formatted output • putchar(), puts(), printf() • character, string & formatted input • getchar(), gets(), scanf() • file access • fopen(), fscanf(), fprintf(), fclose() 'C' in a Nutshell by J. Sumey

  16. printf() details • “print formatted” – the standard method of doing output from C • printf(const char *format, /*args…*/); • outputs 0 or more arguments according to conversion specifications in format string • ex: printf(“Hello %s, it’s %d:%02d am.\n”, “World”, 10, 9); • ex:printf(“pi = %.5f”, 4 * atan(1.0)); • numerous conversion specs available:%c, %s, %d, %i, %u, %o, %x, %f, %g, %p • fprintf() – sends output to opened file • sprintf() – sends output to a string • very useful in embedded systems! 'C' in a Nutshell by J. Sumey

  17. Libraries: string handling • compiler directive: #include <string.h> s & t are char * strlen(s)returns integer length of string s strcpy(s, t)copies string t to string s strcat(s, t)concatenates t onto end of s strcmp(s, t) compares 2 strings; returns –n, 0, +n for s<t, s==t, or s>t strchr(s, c) searches for char c in string s; returns pointer if c found in s, NULL if not strstr(s, t) searches for string t in string s;returns pointer if t found in s, NULL of not strtok(s, delims) divides string into word tokens 'C' in a Nutshell by J. Sumey

  18. Libraries: character classification • compiler directive: #include <ctype.h> is___(c)classifies character, returns true (non-zero) / false (zero) result predicates: alpha, upper, lower, digit, xdigit, alnum, space, punct, print, graph, cntrl, ascii ex: c = getchar(); // get input character if (isdigit(c)) … // process digit entries 'C' in a Nutshell by J. Sumey

  19. Libraries: memory manipulation • <string.h> also includes some very useful memory-handling utility functions! s1 & s2 are void * (i.e., pointers to anything) memset(s, c, n)sets n bytes of memory starting at s to a given c byte memcpy(s1, s2, n)copies n bytes of memory from s2 to s1 memcmp(s1, s2, n)compares n bytes of memory between s1 and s2 memchr(s, c, n)searches up to n memory bytes from s for given char c 'C' in a Nutshell by J. Sumey

  20. Libraries: memory management • dynamically-allocated memory via pointers • and “heap” memory • compiler directive: #include <stdlib.h> malloc(n)allocates n bytes of memory from heap; returns pointer, NULL if fail calloc(nelem, elsize)allocates array of nelem*elsize bytes and initializes to zeros realloc(ptr, size)reallocates memory block to new size free(ptr)returns memory block to heap 'C' in a Nutshell by J. Sumey

  21. Libraries: sorting & searching • compiler directive: #include <stdlib.h> • both functions support any data types • use a user-supplied comparison function qsort()quicksorts a table (array) of data in place bsearch()search a sorted table using binary search 'C' in a Nutshell by J. Sumey

  22. Libraries: string-number conversion • compiler directive: #include <stdlib.h> • tip: do reverse conversions with sprintf() ! atoi(s)convert from ASCII string to int atol(s)convert from ASCII string to long atof(s)convert from ASCII string to float strtol(s, end, base)convert from string to long strtoul(s, end, base)convert from string to unsigned long strtod(s, end)convert from string to double 'C' in a Nutshell by J. Sumey

  23. Libraries: mathematical functions • compiler directive: #include <math.h> x, y & return value are type double sin(x), asin(x)sine/arcsine of x, x in radians cos(x), acos(x)cosine/arcsine of x , x in radians tan(x), atan(x)tangent/arctangent of x , x in radians atan2(y,x) quadrant-correct version of arctangent exp(x)exponential function ex log(x) natural logarithm (base e) of x log10(x) common logarithm (base 10) of x pow(x, y) xy sqrt(x) square root of x ceil(x), floor(x) ceiling/floor functions 'C' in a Nutshell by J. Sumey

  24. Libraries: JS’s “Embedded” Library • #include <embeddedlib.h> • collection of support functions useful to embedded systems projects • currently implemented on Freescale ‘S12 and Coldfire families • includes 3 categories • timing-related • pin I/O • general utility 'C' in a Nutshell by J. Sumey

  25. Timing related functions… PLL_init() initialize Phase Locked Loop module initTiming() initialize software timers support usDelay() time delay for given number of microseconds msDelay() time delay for given number of milliseconds msRunTime() return runtime in milliseconds startTimer() perform a non-blocking delay then invoke user-specified call-back function restartTimer() start new time-out for specified timer ID cancelTimer() cancel specified timer ID time-out and resulting call-back getTimer() get remaining time for specified timer ID waitTimer() for given timer ID, perform blocking delay until its time-out 'C' in a Nutshell by J. Sumey

  26. Pin I/O functions… pinDir() set direction of specified pin pinSet() set specified pin to given logic value pinCom() toggle specified pin pinGet() read specified pin & return as a bool pwmOn() activate Pulse-Width Modulation output on specified pin pwmOff() deactivate Pulse-Width Modulation output on specified pin pulseIn() wait for and measure an input pulse on specified pin pulseOut() output pulse of given duration to specified pin count() count number of cycles received on pin within given duration pingTime() acquire echo time of a PING))) sensor connected to specified pin pingDistInCm() measure and return distance in cm to obstacle serialIn() receive a single character RS-232 style from specified pin serialOut() send a single character RS-232 style to specified pin serialOutS() send a string of characters RS-232 style to specified pin freqOut() output frequency for given duration to specified pin freqOut2() output mix of 2 specified frequencies for given duration dtmfOut() output phone digit for given duration to specified pin dtmfOutS() output phone digit string to specified pin playNote() output MIDI note of given duration to specified pin playNotes() output array of MIDI notes as given 'C' in a Nutshell by J. Sumey

  27. General utility functions… checksum8() compute & return 1's complement checksum of byte array checksum16() compute & return 1's complement checksum of word array constrain() constrain given value to min-max range map() map given value from one range to another btoa() convert a byte value into 3-digit ASCII dtoa() convert a decimal integer value to an ASCII string itoa() convert an integer value to an ASCII string itoan() convert an integer value to an ASCII string 'C' in a Nutshell by J. Sumey

  28. Example use: produce 100 Hz 1% DC square wave #include “embeddedlib.h” #define OSCCLK 8000000 // crystal oscillator speed #define BUSCLK 16000000 // operational bus frequency void main() { PLL_init(OSCCLK, BUSCLK); // initialize PLL for high speed initTiming(BUSCLK/1000000); // init embedded library timing support pinDir(PIN_PA0, OUTPUT); while (1) // infinite loop { pinSet(PIN_PA0, HIGH); // set PORTA0 high usDelay(1000); // delay 1 ms pinCom(PIN_PA0); // return it low msDelay(99); // output freq = 100 Hz } } 'C' in a Nutshell by J. Sumey

  29. Example use: play Charge! on PORTT6 #include “embeddedlib.h” #define OSCCLK 8000000 // crystal oscillator speed #define BUSCLK 16000000 // operational bus frequency // array definition of trumpet charge! tune const Note_t chargeTune[] = { { NOTE_C4, 200, 0 }, // MIDI note, duration, rest { NOTE_E4, 200, 0 }, { NOTE_G4, 200, 0 }, { NOTE_C5, 300, 150 }, { NOTE_A4, 200, 0 }, { NOTE_C5, 400, 0 }, -1 // end of tune marker }; void main() { PLL_init(OSCCLK, BUSCLK); // initialize PLL for high speed initTiming(BUSCLK/1000000); // init embedded library timing support playNotes(PIN_PT6, chargeTune); // charge! } 'C' in a Nutshell by J. Sumey

  30. Summary • arrays, structures & pointers provide enhanced data-handling capabilities • libraries provide useful support functionality that can save tremendous amounts of time in the development of embedded systems 'C' in a Nutshell by J. Sumey

More Related