Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "‘C’ in a Nutshell A “crash course” in C......with designs for embedded systems by J. S. Sumey."— Presentation transcript:

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

2 'C' in a Nutshell by J. Sumey2 of 30 III. Pot Luck  Arrays  Structures  Pointers  Libraries

3 'C' in a Nutshell by J. Sumey3 of 30 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];

4 'C' in a Nutshell by J. Sumey4 of 30 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

5 'C' in a Nutshell by J. Sumey5 of 30 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; };

6 'C' in a Nutshell by J. Sumey6 of 30 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 );

7 'C' in a Nutshell by J. Sumey7 of 30 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];

8 'C' in a Nutshell by J. Sumey8 of 30 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

9 'C' in a Nutshell by J. Sumey9 of 30 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 and b) the expression “*ch_ptr” is a char this applies to any basic type as well as arrays, structures, functions, etc.

10 'C' in a Nutshell by J. Sumey10 of 30 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 ‘&’! Pointers & function arguments

11 'C' in a Nutshell by J. Sumey11 of 30 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 ); ‘k’ ch_ptr: ch:

12 'C' in a Nutshell by J. Sumey12 of 30 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?

13 'C' in a Nutshell by J. Sumey13 of 30 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)

14 'C' in a Nutshell by J. Sumey14 of 30 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)

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

16 'C' in a Nutshell by J. Sumey16 of 30 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!

17 'C' in a Nutshell by J. Sumey17 of 30 Libraries: string handling compiler directive: #include 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 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

18 'C' in a Nutshell by J. Sumey18 of 30 Libraries: character classification compiler directive: #include 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

19 'C' in a Nutshell by J. Sumey19 of 30 Libraries: memory manipulation also includes some very useful memory-handling utility functions! s, 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

20 'C' in a Nutshell by J. Sumey20 of 30 Libraries: memory management dynamically-allocated memory via pointers and “heap” memory compiler directive: #include 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

21 'C' in a Nutshell by J. Sumey21 of 30 Libraries: sorting & searching compiler directive: #include 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

22 'C' in a Nutshell by J. Sumey22 of 30 Libraries: string-number conversion compiler directive: #include 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

23 'C' in a Nutshell by J. Sumey23 of 30 Libraries: mathematical functions compiler directive: #include 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 e x log(x)natural logarithm (base e) of x log10(x)common logarithm (base 10) of x pow(x, y)x y sqrt(x)square root of x ceil(x), floor(x)ceiling/floor functions

24 'C' in a Nutshell by J. Sumey24 of 30 Libraries: JS’s “Embedded” Library #include 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

25 'C' in a Nutshell by J. Sumey25 of 30 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

26 'C' in a Nutshell by J. Sumey26 of 30 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

27 'C' in a Nutshell by J. Sumey27 of 30 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

28 'C' in a Nutshell by J. Sumey28 of 30 Example use: produce 100 Hz 1% DC square wave #include “embeddedlib.h” #define OSCCLK // crystal oscillator speed #define BUSCLK // operational bus frequency void main() { PLL_init(OSCCLK, BUSCLK);// initialize PLL for high speed initTiming(BUSCLK/ );// 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 }

29 'C' in a Nutshell by J. Sumey29 of 30 Example use: play Charge! on PORTT6 #include “embeddedlib.h” #define OSCCLK // crystal oscillator speed #define BUSCLK // 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/ );// init embedded library timing support playNotes(PIN_PT6, chargeTune);// charge! }

30 'C' in a Nutshell by J. Sumey30 of 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


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

Similar presentations


Ads by Google