Introduction to C Programming

Slides:



Advertisements
Similar presentations
Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
Advertisements

IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Structure of a C program
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
Basic Elements of C++ Chapter 2.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
8-1 Embedded Systems Fixed-Point Math and Other Optimizations.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Dennis Ritchie 1972 AT & T Bell laboratories (American Telephone and Telegraph) USA 1www.gowreeswar.com.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
Windows Programming Lecture 06. Data Types Classification Data types are classified in two categories that is, – those data types which stores decimal.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
Bill Tucker Austin Community College COSC 1315
C++ Lesson 1.
C++ LANGUAGE MULTIPLE CHOICE QUESTION
Chapter Topics The Basics of a C++ Program Data Types
The Machine Model Memory
Data types Data types Basic types
Chapter 12 Variables and Operators
Chap. 2. Types, Operators, and Expressions
Tokens in C Keywords Identifiers Constants
Basic Elements of C++.
C Language VIVA Questions with Answers
Fundamental of Programming (C)
CISC/CMPE320 - Prof. McLeod
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
C Short Overview Lembit Jürimägi.
C Basics.
Introduction to C Programming Language
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 3: Understanding C# Language Fundamentals
Introduction to C Programming
Basic Elements of C++ Chapter 2.
11/10/2018.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Starting JavaProgramming
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Java - Data Types, Variables, and Arrays
Basics of ‘C’.
Introduction to Java, and DrJava part 1
Introduction to C Programming
C Operators, Operands, Expressions & Statements
Lectures on Numerical Methods
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.
CISC/CMPE320 - Prof. McLeod
Introduction to Java, and DrJava
C Programming Getting started Variables Basic C operators Conditionals
2. Second Step for Learning C++ Programming • Data Type • Char • Float
The C Language: Intro.
Primitive Types and Expressions
C++ Programming Basics
Introduction to Java, and DrJava
Module 2 Variables, Data Types and Arithmetic
Introduction to Java, and DrJava part 1
DATA TYPES There are four basic data types associated with variables:
C Language B. DHIVYA 17PCA140 II MCA.
Introduction to C Programming
INTRODUCTION TO C.
Presentation transcript:

Introduction to C Programming Embedded Workshop Microcontrollers April 26, 2017

Baseline This is NOT an introduction to programming class. I will probably repeat this class outside of the Embedded Workshop series. We can pause to try running test code on the Arduino.

History C is like a high level assembler. Designed for system programming, namely implementing UNIX. Originally targeted DEC PDP series minicomputers. Ability to express optimization by accessing the special capabilities of the processor.

The Preprocessor Essentially a language around a language. Start the line with a ‘#’. Uses Header file inclusion. Macro substitution. Conditional compilation. Compiler control.

Header File Inclusion #include <file name> #include “file name” Searches for the file in standard system directories. #include “file name” Searches for the file in the directory where the file containing the #include statement resides, then in system directories.

Macro Substitution #define NAME value literally replaces “NAME” with “value”.

Macro Substitution #define BLINK_LED(pin) digitalWrite(pin, HIGH); \ delay(500); \ digitalWrite(pin, LOW); expands this code in place.

Conditional Compilation #ifdef DEBUG stuff #endif #if VERSION >= 2 stuff #else other stuff #endif

Compiler Control #pragma Special instructions to the compiler.

Syntax These are the rules for writing code. C is free form – white space is ignored except within a character string. C is case sensitive. A ‘\’ at the end of a line treats the next line as part of the current line. This is usually only needed for defining a complicated macro.

Comments /* comment */ /* * comment */ // comment

Block Structured { declarations statements }

Block Structured { int foo; foo = 1; }

Source File Structure comment block header file interface global variable declarations int function () { } int anotherFunction () { }

Indentation Not enforced by the language. Useful to make structure of your code clearer. Some people feel very strongly about the particular indentation style. Pick a style and stick to it.

K & R Indentation Style int function() { if (foo == 0) { statement; } }

Some Like This Indentation Style int function() { if (foo == 0) { statement; } }

My Indentation Style int function() { if (foo == 0) { statement; } }

Naming Defined names in all caps #define LED 13 Variable names multiple_word_name multipleWordName MultipleWordName Again, pick a style and stick to it.

Standard C versus Arduino C

Standard C int main() { do stuff; }

Arduino C void setup() { initialization stuff } void loop() { repeated stuff }

The missing link int main() { setup(); while (1) loop(); }

Variables and Types Base types are categorized by the data format Integer Real Pointer Character

Integer Whole numbers only. int is the default base type. unsigned means there is no sign bit. The sizes of a short and a long are implementation specific. A short is no longer than a long. Newer compilers implement long long. Plain int is usually the most efficient variable type.

Real A number consisting of a magnitude and an exponent. Think scientific notation, but in binary. float is a single precision number. double is a double precision number.

Pointers This is simply the address of something. ptr++ increments the pointer by the size of type pointed to. Similarly for pointer arithmetic: ptr + 2 compiles as ptr + 2 * sizeof(type)

Arrays Index 0 is the first element int foo[N] allocates foo[0], …, foo[N-1] Elements are stored in row-major order. Elements in a row are next to each other. int array[column][row];

Characters and Strings char represents a single letter, digit or symbol. May be signed or unsigned when not specified, depending on the compiler. A string is an array of characters terminated by a character with a binary 0 value. A string cannot contain a binary 0 (duh!).

Enum Short for enumerated type. A list of related constants. Similar to a series of #define statements, except the compiler can automatically assign the numerical value.

Typedef Allows assigning a simple name to a complicated type.

Type casting Directs the compiler how to interpret or convert a variable. Of the form (type) Examples (unsigned) x (char *) p

Const Tells the compiler that a variable is not intended to be changed after initialization. const int ratio = 3;

Volatile Tells the compiler that a variable may change at any time. This situation arises in embedded programming: The variable is an input port mapped to an address. The variable may be changed by an interrupt handler.

Register Tells the compiler that a variable is heavily used and suggests that it be kept in a register. This is mostly obsolete because compilers are now much better at code optimization and do not need the hint.

Void void is used when declaring functions to indicate it takes no arguments or returns no value. void is also used to declare a generic pointer to an unspecified type. Type cast it to use it to access data.

Struct Groups related variables together. A union is a special form of struct which allows overlaying more than one variable definition on the same memory location.

Scope int programGlobalVariable; int function () { }

Scope static int fileGlobalVariable; int function () { }

Scope int function () { int functionLocalVariable; }

Scope int function() { if (foo == 0) { int blockLocalVariable; statement; } }

Scope int whichOneIsVisible; int function () { int whichOneIsVisible; statements }

Static static int fileGlobalVariable; int function () { static int persistentLocalVariable; }

Operators Unary Arithmetic Relational Logical Bitwise Assignment Special

Unary Operators -a a++ ++a a— --a Get the negative of a Get the value of a, then increment a Increment a, then take its value Get the value of a, then decrement a Decrement a, then take its value

Arithmetic Operators a + b a – b a * b a / b a % b Get the sum of a and b Get the difference of b from a Get the product of a and b Get the quotient of b into a Get the remainder after dividing b into a

Relational Operators a == b a != b a > b a < b a >= b True if a is equal b True if a is not equal b True if a is greater than b True if a is less than b True if a is greater than or equal to b True if a is less than or equal to b

Logical Operators a && b a || b !a (a) ? b : c True if a and b are both true True if either a or b is true True if a is false; false if a is true If a is true, do b else do c

Bitwise Operators a & b a | b a ^ b ~a a << b a >> b The bits of a anded with b The bits of a ored with b The bits of a exclusive ored with b The bits of a inverted a shifted left b bit positions a shifted right b bit positions

Assignment Operators a = b a += b a -= b a *= b a /= b a %= b Assign b to a Add b to a Subtract b from a Multiply b to a Divide b into a Assign remainder of a / b to a Shift a left b bit positions Shift a right b bit positions And b to a Exclusive or b to a Or b to a

Special Operators sizeof(a) &a *a a.b Get the number of bytes occupied by a Get the address of a Get the data at the address in a Get member b of data structure a

More Special Operators a[b] a->b , Get element b of array a, short for *(a+b) Get member b of data structure at the address in a; short for (*a).b Evaluate a series of expressions from left to right; the value is that of the rightmost expression

Operator Precedence There are way too many levels of precedence. Some of them do not make sense. Find a precedence chart you like and keep a copy of it handy. When in doubt, use parenthesis, but too many of them makes code difficult to read.

Operator Precedence Example 100 – 25 * 3 % 4 100 – 75 % 4 100 – 3 97

Truth table for NOT P NOT P 1

Truth table for AND P Q P AND Q 1

Truth table for OR P Q P OR Q 1

Truth table for EXCLUSIVE OR P Q P XOR Q 1

Flow of Control if (foo == 0) doSomething(); if (foo == 0) doSomething(); else doTheOther();

Flow of Control while (foo == 0) doThisSeveralTimes(); do doThisSeveralTimesButAtLeastOnce(); while (foo == 0);

Flow of Control for (initialization; condition; step) doThisSeveralTimes(); is equivalent to initialization; while (condition) { doThisSeveralTimes(); step; }

Flow of Control switch (foo) { case 0: doSomething(); break; default: otherwiseDoThis(); }

Functions Standard C requires functions be defined before they are referenced, or a function prototype be provided. Arduino C automatically generates function prototypes.

the "standard library“ This was originally the set of UNIX system calls “Compatible” compilers supported them so that code can be ported from UNIX to more systems. Useful for formatting, data conversion, math functions. Not so good for memory management on the Arduino.

a little bit of C++ A class is a struct with added features. Hidden data members. Methods are functions to manipulate the object. Some Arduino library code such as Serial uses C++ classes. Serial.print

language traps to avoid I can write an entire book on why C is not my favorite programming language, but it is what it is = versus == Forgetting break in switch // comment in #define Not understanding operator precedence

debugging techniques Unfortunately, there is no Arduino debugger Use print statements Use Serial.print to display information Divide and conquer