32
Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Embed Size (px)

Citation preview

Page 1: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Lecture 6: C Programming & Data Types

Bryan Burlingame

7 October 2015

Page 2: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Announcements Exam in two weeks

More info next week Homework due next week Read Ch. 1 - 2 in text Lab Kits available today

Page 3: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

The Plan for Today

Introduce the C Programming Language Describe the structure of a C program

Microcontrollers for engineering applications What is a microcontroller? How are microcontrollers used? The Arduino hardware platform The Spartronics Experimenter board Programming the Arduino

Page 4: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Learning Objectives Explain the basic parts of a C program Explain what a microcontroller is Explain where microcontrollers are used Describe the Arduino prototyping platform Describe the Spartronics Experimenter board Explain what is meant by a pin being an input

or an output

Page 5: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Fundamental Flow of a C Program

Start

Main

EndReturn value to Operating System (very important!)

Calling parametersAvailable from Operating System

Page 6: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Structure of a C Program A formal letter has a

structure So does a program in C

Burford FurmanProfessorDept. of Mech. and Aero. EngSan José State UniversitySan Jose, CA 95192-0087

July 20, 2009

Dear Prof. Furman,

I’m writing you to see if I can get into ME 30……

Sincerely,

Jane Student

Title block

Date

Salutation

Body

Closing

Signature

Page 7: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

C Code for D&D 3.15cProgrammer’s block

Pre-processor directive

Declare and initialize variables

While loop(repetition structure)

Main function (statements go between { } )

return statement

Page 8: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Programmer’s Block Include important information (comments)

to document the program: Title Date Author Description Inputs/Outputs Algorithm Revision history

Add comments using one of two methods:

1. /* put comment between */ (note: traditional C)

2. // comment (note: single line only)

Full program

Page 9: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

# include (pre-processor directive)

Includes a library file for ‘standard io’ functions for things like printing, etc.

Full program

Page 10: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

main() function

Full program

Your program needs a main() function Statements go between

the braces { } main() ends with the return keyword and usually the value zero

If main() runs successfully, it returns a value of zero

Page 11: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Declare and initialize variables Unlike MatLab variables must be declared before you can use them

Full program

Page 12: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Declarations

All variables must be “declared” and should must be “initialized”

Declaration – allocating memory for a variable value, assigning that memory location a name and a format (integer, float, etc.)

Initialization – giving a variable a starting value

Page 13: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Declaration example

double velocity = 4.565;

Variables should have descriptive names int a = 3434; // what does ‘a’ hold? int current_location = 3434; Int curr_loc = 3434;

Data type name Initial value

Page 14: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Structured Programming Sequence Selection

IF IF – ELSE SWITCH

Repetition WHILE DO – WHILE FOR

Subroutines (Functions)

Page 15: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

15

Kinds of Data (simplified view)

The basic kinds of data that we will mostly use: Numeric

Integers: Real (floating point) numbers:

Character (are enclosed by single quotes in C) All letters, numbers, and special symbols

Ex. ‘A’, ‘+’, ‘5’ String (are enclosed by double quotes in C)

Are combinations of more than one character Ex. “programming”, “ME 30”

Logical (also called ‘Boolean’ named after George Boole an English mathematician from the early 1800’s) True or False (1 or 0)

Page 16: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

16

Constants and Variables Constant

A data element that never changes in your program 5, 62.37, 4.219E-6, “record_string”, ‘$’ i = j + 7; /* which one is the constant? */ first_letter = ‘a’; /* which one is the constant? */

Variable A data element that can take on different values

Its name represents a location (address) in memory i = j + 7; /* which are variables? */ second_letter = ‘b’; /* which is the variable? */

Values are ‘assigned’ using a single equal sign ( = ) Read the statement: i = j + 7;

NOTE!! Variables in C must be ‘declared’ before they can be used!

Page 17: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

Declaration example

double velocity = 4.565;

Variables should have descriptive names int a = 3434; // what does ‘a’ hold? int current_location = 3434; int curr_loc = 3434;

Data type name Initial value

Page 18: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

C Data Types - IntegersType Size

char 1 or 2 bytes (commonly 1 byte)

short At least 2 bytes (commonly 2 bytes)

int Most common, at least 2 bytes (commonly 4 bytes)

long (long int) At least 4 bytes (commonly 4 bytes)

long long int At least 8 bytes (commonly 8 bytes) – relatively new

Type Size

char 1 or 2 bytes (commonly 1 byte)

short At least 2 bytes (commonly 2 bytes)

int Most common, at least 2 bytes (commonly 4 bytes)

long (long int) At least 4 bytes (commonly 4 bytes)

long long int At least 8 bytes (commonly 8 bytes) – relatively new

Modifier Comment

unsigned Forces the integer to be unsigned, effectively doubling the upper bound

signed Forces the integer to be signed (uncommon, used with char)

const Not commonly implemented, marks the integer as a constant

Page 19: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

C Data Types – Floating pointType Size

char 1 or 2 bytes (commonly 1 byte)

short At least 2 bytes (commonly 2 bytes)

int Most common, at least 2 bytes (commonly 4 bytes)

Type Size

float Single precision floating point (usually 4 bytes)

double Double precision floating point (usually 8 bytes)

long double Many implementations (10 byte, 16 byte, 8 byte)…

Page 20: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

C Datatypes

C’s built-in datatypes have a problem! No strong standard on how many bits are

assigned to each Size is implementation specific Ex: int (integer)

Arduino Uno: 16 bits Arduino Due: 32 bits

Page 21: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

C Data Types – New TypesType Size

char 1 or 2 bytes (commonly 1 byte)

short At least 2 bytes (commonly 2 bytes)

int Most common, at least 2 bytes (commonly 4 bytes)

Type Size

intN_t Signed integer of size N bits, where N should be 8, 16, 32, or 64. Example: int8_t is an 8 bit integer

uintN_t Unsigned integer of size N bits, where N should be 8, 16, 32, or 64. Example: uint16_t is a 16 bit unsigned integer

float_t At least as long as a float (they still can’t get it together, but at least this is testable!)

double_t At least as long as a double

Page 22: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

22

Variable Names Sequence of lower and/or upper case letters, digits, and

underscores Case sensitive! ex: my_num is not the same as My_num

Initial character may not be a digit May not use reserved words as identifiers Avoid names used by run-time libraries (e.g., log, which is used in

math.h) Try to use lowercase letters for variable names, and UPPER CASE

letters for symbolic constants (e.g., #define PI 3.14159) Choose names that are meaningful (e.g., light_level instead of just

output)

Page 23: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

23

Operators

Operator: a symbol (or combination of symbols) used to combine variables and constants to produce a value(Overland, B. (1995) C in plain English, MIS Press, New York.)

The variables and constants that get combined are called ‘operands’

How the combining is carried out depends on the precedence and associativity of the operator

Example – identify the operator(s), operands, and results on each line:int i, j = 3;i = j + 7;

Page 24: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

24

Operator Precedenceand Associativity

• All operators have the properties of precedence and associativity.

• Precedence has to do with which operations take priority in

groupings of operands around adjacent operators

• Associativity has to do with which operations take priority when the operators in an expression have

the same precedence• Use parentheses () to specify a

particular grouping order and to make expressions more readable

Page 25: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

25

Arithmetic with Mixed Data Types

Fundamentally, the computer is not able to arithmetically combine data of different types Arithmetic with integers integer results

int div_int = 8 / 5; /* what is div_int? */

Arithmetic with floating point data floating point results

float div_flt = 8.0 / 5.0; /* what is div_flt? */

Arithmetic with integers and floating point values in the same expressions ??

int div_int = 8.0 / 5; /* what is div_int? */ float div_flt = 8.0 / 5; /* what is div_flt? */ float div_flt = 8 / 5; /* what is div_flt? */

Page 26: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

26

Implicit Type Casting

In operations (e.g., +, -, /, etc.) with operands of mixed data types, the resultant data type will take the higher order data type of the two operands1

1Cheng, Harry H. (2010). C for Engineers and Scientists: An Interpretive Approach, McGraw-Hill, New York.

long double

double

float

unsigned long long

long long

unsigned long

long

unsigned int

int

unsigned short

short

unsigned char

char

Higher

Lower

Page 27: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

27

Expressions and Statements

Expression (very much like MatLab) Any combination of operators, numbers, and names

that evaluates to a single value 5 j = 17 j = i = 10 i + j

Statement A chunk of code that does something (executes)

Terminating an expression with a semicolon (;) turns it into a statement

Page 28: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

28

Formatted Output

We use the printf function (stands for ‘print-formatted) to display text and numeric information to the screen printf is available by including the Standard

IO library, stdio.h (more on this later) Ch already “knows” about printf, so it is not

necessary to include stdio.h Ex. Print a line of text

printf("Hello ME 30!!");

Page 29: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

29

printf() – a closer look General form:

printf(“control string”, arg1, arg2,…); Control string

A string enclosed in double quotes that controls the conversion and formatting of zero or more arguments

Arguments are expressions that the function printf acts on Inside the control string will often be conversion specifications

and modifiers that specify how the data from the arguments is to be converted into displayable form

Escape sequences (a \ followed by a letter or combination of digits)) are also used to control the position of the cursor and/or provide literal representations of non-printing or special characters

Ex. Try this in ChIDE

printf("printf example:\n 1+1=%d\n", 1+1);

Page 30: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

30

Conversion Specifications (partial list)

ConversionSpecification

Output

%ccharacter (if datum is an int, prints ASCII value corresponding to least significant byte)

%s string of characters

%d or %i decimal integer

%e, E floating point number in e (or E)–notation

%f floating point number (float or double) in decimal notation

%g, Guses %f or %e, E depending on datum value. Trailing zeros are removed

%u unsigned decimal integer

%o octal integer (base 8)

%x, X hexadecimal integer (base 16), lower, Upper case

%% Prints a % sign

Adapted from: http://www.eecs.umich.edu/~bartlett/printf.html

Page 31: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

31

Escape Sequences (partial list)

EscapeSequence

Represents

\a Bell (alert)

\b Backspace

\f Formfeed

\n New line

\r Carriage return

\t Horizontal tab

\v Vertical tab

\' Single quotation mark

\“ Double quotation mark

\\ Backslash

\? Literal question mark

http://msdn.microsoft.com/en-us/library/h21280bw(VS.80).aspx

Page 32: Lecture 6: C Programming & Data Types Bryan Burlingame 7 October 2015

References

Microcontroller. (2009, November 20). In Wikipedia, the free encyclopedia. Retrieved November 21, 2009, from http://en.wikipedia.org/wiki/Microcontroller

Arduino Home Page. (2009, November 21). Retrieved November 21, 2009, from http://arduino.cc/