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

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Introduction to C Programming
Introduction to C Programming
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
One Dimensional Arrays
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
 2000 Prentice Hall, Inc. All rights reserved Fundamentals of Strings and Characters String declarations –Declare as a character array or a variable.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Pointers in C Rohit Khokher
Kernighan/Ritchie: Kelley/Pohl:
1 Lecture 7  Fundamental data types in C  Data type conversion:  Automatic  Casting  Character processing  getchar()  putchar()  Macros on ctype.h.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
Chapter 10.
Chapter 8 Characters and Strings Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
Chapter 8 Arrays and Strings
Guide To UNIX Using Linux Third Edition
Review of C++ Programming Part II Sheng-Fang Huang.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
UniMAP Sem2-08/09 DKT121: Fundamental of Computer Programming1 Introduction to C – Part 2.
By Sidhant Garg.  C was developed between by Dennis Ritchie at Bell Laboratories for use with the Unix Operating System.  Unlike previously.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
C Tokens Identifiers Keywords Constants Operators Special symbols.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
(continue) © by Pearson Education, Inc. All Rights Reserved.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
UniMAP Sem1-07/08EKT120: Computer Programming1 Week2.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Characters and Strings File Processing Exercise C Programming:Part 3.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
5-1 Embedded Systems C Programming Language Review and Dissection III Lecture 5.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
Characters and Strings
CS 1704 Introduction to Data Structures and Software Engineering.
UNIMAP Sem2-07/08EKT120: Computer Programming1 Week 2 – Introduction to Programming.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
CCSA 221 Programming in C INPUT AND OUTPUT OPERATIONS IN C – PART 1 1.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Numbers in ‘C’ Two general categories: Integers Floats
C Characters and Strings
Computer Science 210 Computer Organization
A bit of C programming Lecture 3 Uli Raich.
C Characters and Strings
C Basics.
Computer Science 210 Computer Organization
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
WEEK-2.
The C Language: Intro.
Programming Languages and Paradigms
C Characters and Strings
Professor Jodi Neely-Ritz University of Florida
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. Sumey2 of 30 III. Pot Luck  Arrays  Structures  Pointers  Libraries

'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];

'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

'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; };

'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 );

'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];

'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

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

'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

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

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

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

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

'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()

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

'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

'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

'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

'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

'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

'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

'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

'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

'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

'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

'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

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

'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! }

'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