‘c’ in a nutshell

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

Upload: mariko-burke

Post on 01-Jan-2016

39 views

Category:

Documents


0 download

DESCRIPTION

‘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]; - PowerPoint PPT Presentation

TRANSCRIPT

‘C’ in a Nutshell

A “crash course” in C......with designs for embedded systems

by J. S. Sumey

'C' in a Nutshell by J. Sumey 2 of 30

III. Pot Luck

ArraysStructures

Pointers

Libraries

'C' in a Nutshell by J. Sumey 3 of 30

Arrays

can have an array of elements of a particular data typeuse brackets to indicate dimensions and number of elements ex: int lottery_numbers[6];

char winner_name[40];

subscripts are zero-basedcan have multiple dimensions ex: top3_winners[3][40];

'C' in a Nutshell by J. Sumey 4 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 datamay be assigned to, copied, passed to and returned from functionsstructure members are accessed via the ‘.’ operatormay be nested

'C' in a Nutshell by J. Sumey 5 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;

};

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

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

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

'C' in a Nutshell by J. Sumey 9 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

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 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

'C' in a Nutshell by J. Sumey 11 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:

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

'C' in a Nutshell by J. Sumey 13 of 30

Pointer macros for I/O registers

the pointer mechanism provides a nice solution to accessing I/O registers at fixed memory locationsex: #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 of 30

Libraries

various libraries provide extended functionality beyond the languageevery 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 of 30

Libraries: standard i/o

provides access to input/output facilities and related data types as standardized by ANSIuses 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 of 30

printf() details

“print formatted” – the standard method of doing output from Cprintf(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 filesprintf() – sends output to a string

very useful in embedded systems!

'C' in a Nutshell by J. Sumey 17 of 30

Libraries: string handling

compiler directive: #include <string.h>s & t are char *

strlen(s) returns integer length of string sstrcpy(s, t) copies string t to string sstrcat(s, t) concatenates t onto end of sstrcmp(s, t) compares 2 strings;

returns –n, 0, +n for s<t, s==t, or s>tstrchr(s, c) searches for char c in string s;

returns pointer if c found in s, NULL if notstrstr(s, t) searches for string t in string s;

returns pointer if t found in s, NULL of notstrtok(s, delims) divides string into

word tokens

'C' in a Nutshell by J. Sumey 18 of 30

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 of 30

Libraries: memory manipulation

<string.h> 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 s1memcmp(s1, s2, n) compares n bytes of memory between

s1 and s2memchr(s, c, n) searches up to n memory bytes from s

for given char c

'C' in a Nutshell by J. Sumey 20 of 30

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 failcalloc(nelem, elsize) allocates array of

nelem*elsize bytes and initializes to zeros

realloc(ptr, size) reallocates memory block to new sizefree(ptr) returns memory block to heap

'C' in a Nutshell by J. Sumey 21 of 30

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 placebsearch() search a sorted table using binary search

'C' in a Nutshell by J. Sumey 22 of 30

Libraries: string-number conversion

compiler directive: #include <stdlib.h>

tip: do reverse conversions with sprintf() !

atoi(s) convert from ASCII string to intatol(s) convert from ASCII string to longatof(s) convert from ASCII string to floatstrtol(s, end, base) convert from string to longstrtoul(s, end, base) convert from

string to unsigned longstrtod(s, end) convert from string to double

'C' in a Nutshell by J. Sumey 23 of 30

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 radianscos(x), acos(x) cosine/arcsine of x , x in radianstan(x), atan(x) tangent/arctangent of x , x in radiansatan2(y,x) quadrant-correct version of arctangentexp(x) exponential function ex

log(x) natural logarithm (base e) of xlog10(x) common logarithm (base 10) of xpow(x, y) xy

sqrt(x) square root of xceil(x), floor(x) ceiling/floor functions

'C' in a Nutshell by J. Sumey 24 of 30

Libraries: JS’s “Embedded” Library

#include <embeddedlib.h>collection of support functions useful to embedded systems projectscurrently implemented on Freescale ‘S12 and Coldfire familiesincludes 3 categories timing-related pin I/O general utility

'C' in a Nutshell by J. Sumey 25 of 30

Timing related functions…

PLL_init() initialize Phase Locked Loop moduleinitTiming() initialize software timers supportusDelay() time delay for given number of

microsecondsmsDelay() time delay for given number of millisecondsmsRunTime() return runtime in millisecondsstartTimer() perform a non-blocking delay then invoke

user-specified call-back functionrestartTimer() start new time-out for specified timer IDcancelTimer() cancel specified timer ID time-out and

resulting call-backgetTimer() get remaining time for specified timer IDwaitTimer() for given timer ID, perform blocking delay

until its time-out

'C' in a Nutshell by J. Sumey 26 of 30

Pin I/O functions…pinDir() set direction of specified pinpinSet() set specified pin to given logic valuepinCom() toggle specified pinpinGet() read specified pin & return as a boolpwmOn() 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 pincount() count number of cycles received on pin within given

durationpingTime() acquire echo time of a PING))) sensor connected to

specified pinpingDistInCm() measure and return distance in cm to obstacleserialIn() receive a single character RS-232 style from specified pinserialOut() send a single character RS-232 style to specified pinserialOutS() send a string of characters RS-232 style to specified pinfreqOut() output frequency for given duration to specified pinfreqOut2() output mix of 2 specified frequencies for given durationdtmfOut() output phone digit for given duration to specified pindtmfOutS() output phone digit string to specified pinplayNote() output MIDI note of given duration to specified pinplayNotes() output array of MIDI notes as given

'C' in a Nutshell by J. Sumey 27 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 rangemap() map given value from one range to anotherbtoa() convert a byte value into 3-digit ASCIIdtoa() convert a decimal integer value to an ASCII

stringitoa() convert an integer value to an ASCII stringitoan() convert an integer value to an ASCII string

'C' in a Nutshell by J. Sumey 28 of 30

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 speedinitTiming(BUSCLK/1000000); // init embedded library timing supportpinDir(PIN_PA0, OUTPUT);while (1) // infinite loop{

pinSet(PIN_PA0, HIGH); // set PORTA0 highusDelay(1000); // delay 1 mspinCom(PIN_PA0); // return it lowmsDelay(99); // output freq = 100 Hz

}}

'C' in a Nutshell by J. Sumey 29 of 30

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! tuneconst 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 speedinitTiming(BUSCLK/1000000); // init embedded library timing supportplayNotes(PIN_PT6, chargeTune); // charge!

}

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