Embedded Systems. Introduction. The C Language. Introduction. Why C instead ASM. Introduction to C Embedded Programming language

Similar documents
Operators. Java operators are classified into three categories:

Short introduction to C for AVR

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Fundamental of Programming (C)

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Fundamentals of Programming

CT 229 Java Syntax Continued

UNIT- 3 Introduction to C++

Part I Part 1 Expressions

Writing Program in C Expressions and Control Structures (Selection Statements and Loops)

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Unit 3. Operators. School of Science and Technology INTRODUCTION

Programming in C++ 5. Integral data types

Course Outline Introduction to C-Programming

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Review of the C Programming Language for Principles of Operating Systems

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

Operators in C. Staff Incharge: S.Sasirekha

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

A flow chart is a graphical or symbolic representation of a process.

CHW 469 : Embedded Systems

ME 461 C review Session Fall 2009 S. Keres

More Programming Constructs -- Introduction

Computers Programming Course 6. Iulian Năstac

SECTION II: LANGUAGE BASICS

Department of Computer Science

UIC. C Programming Primer. Bharathidasan University

Quick Reference Guide

The C Programming Language Guide for the Robot Course work Module

Operators and Expressions:

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Lecture 3. More About C

Programming for Engineers Iteration

C Programming Language (Chapter 2 of K&R) Variables and Constants

DEPARTMENT OF MATHS, MJ COLLEGE

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Part I Part 1 Expressions

Chapter 4: Basic C Operators

Expressions and Precedence. Last updated 12/10/18

Chapter 3: Operators, Expressions and Type Conversion

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Fundamental of C programming. - Ompal Singh

Operators & Expressions

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Lecture 2: C Programming Basic

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Programming with Java

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

JAVA OPERATORS GENERAL

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Quick Reference Guide

Mechatronics and Microcontrollers. Szilárd Aradi PhD Refresh of C

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Operators And Expressions

Chapter 12 Variables and Operators

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Review of the C Programming Language

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Information Science 1

CSC 1214: Object-Oriented Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

CENG 447/547 Embedded and Real-Time Systems. Review of C coding and Soft Eng Concepts

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Engineering Computing I

Arithmetic Operators. Portability: Printing Numbers

ISA 563 : Fundamentals of Systems Programming

Informatics Ingeniería en Electrónica y Automática Industrial

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Week 4 Lecture 1. Expressions and Functions

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

Arduino Uno. Power & Interface. Arduino Part 1. Introductory Medical Device Prototyping. Digital I/O Pins. Reset Button. USB Interface.

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

Why embedded systems?

Chapter 12 Variables and Operators

Operators in java Operator operands.

Programming. Elementary Concepts

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

C Programming Language

C: How to Program. Week /Mar/05

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Operators. Lecture 12 Section Robb T. Koether. Hampden-Sydney College. Fri, Feb 9, 2018

Creating a C++ Program

Variables and literals

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Transcription:

Introduction Embedded Systems Introduction to C Embedded Programming language Why C instead ASM 1. C is a high level language, it is easier to write and read than assembly codes. 2. You don't have to think about hardware logic with C, this is taken care of in the background. 3. C codes can be compiled for different microcontrollers without significant modifications of code. 1 3 Introduction In this lecture we will cover the fundamentals of the C programming language as it applies to embedded microcontroller applications. 2 The C Language The C language is function based programming language. Function consists of: 1. A Return Type 2. The Function Name 3. Followed by parentheses enclosing arguments or an empty pair of parentheses if there are not arguments required. f ( x) = x int cube (int x) = x 3 3 y = Integers f (x) y = cube(3) 4 1

while(1); The C Language A C program itself is a function. All C program MUST have a main() function. This function must be included in every program because this is the function which is run when the program is executed. An embedded C program in its simplest form: // do forever 5 The C Language #include <stdio.h> This is a preprocessor command. All preprocessor commands are identified by the # sign. The #include command tells the preprocessor to open filestdio.handcompile itasapartoftheprogram. Nextlineisvoidmain(). It is always necessary to define the type of function, its return type and of course whether the function has any arguments. The type void indicates that this main() function does not return an output and the empty brackets indicates that the function takes no inputs. An open brace indicates the beginning of the block of statements within the function and the function closes with a closing brace. 7 The C Language C Preprocessor Commands #include <avr/io.h> // AVR Header File #include <avr/io.h> // AVR Header File int n; DDRB = 0xFF; DDRA = 0x00; while(1) // do forever PORTB = PINA; 6 Preprocessing, this is the first stage of any C program during compilation. Preprocessor commands are used to combine header files to the mainfiles. During the preprocessing stage, symbols, macros and constants are defined. With the help of preprocessor commands programs become easier to develop and modify. The preprocessor is directed using # symbol at the beginning of the command. All preprocessor commands start with a #. 8 2

C Preprocessor Commands #include : This directive is used to include external c files and headers that are needed for the compilation of a specific project. The#include is used in the following way,#include <filename>. #include <avr/io.h> // General header files #include <avr/interrupt.h> Variables Types Variables are simple keywords which are defined by the values. Values can be changed. Variables are like a boxes with some size where values like apples canbeputin.sovariablescanbeofvariousformsandsizes. A variable type is defined by a reserved word which indicates the type and size of variable identifier: unsigned char Peabody; #include "uart.h" // User s own header files #include "lcd.h" int dogs, cats; long int total_dogs_and_cats; 9 11 C Preprocessor Commands Variables Types #define: This directive allows the programmer to construct constants and macro commands needed for a project. The #define is used in the following way, #define identifier value #define BAUD_RATE 9600UL #define F_CPU 3686400UL // Named constant // Frequency of the clock There are other preprocessor directives that are used in C but not as widelyusedastheonesabove. 10 12 3

Variables Types Constant A Constant value is understandable as being non-changeable value like the (pi=3.141592...) value in math. Usually you use constants in your programs, but don't realize that they are constants. For instance: x = x + 3; The number 3 is a constant which will be compiled directly in addition operation. Constants canalsobeacharacterorstring. It is usually recommended to declare constants by using identifier with reserved word const: const int No = 44; 13 15 Global & Local Variables unsigned char globley; void function_z (void) unsigned int tween; tween = 12; globley = 47; main_loc = 12; unsigned char main_loc; Variables Scope // global variable // a function //local variable //OK //OK //ERROR // local variable #include <avr/io.h> unsigned char z; DDRB = 0xff; DDRA = 0x00; while(1) z = PINA; I/O Operations // Declare z // Set all pins on port B for output // Set all pins on port A for input globley = 34; tween = 12; while(1); //OK //ERROR // do forever PORTB = z + 1; 14 16 4

Operators These are symbols that tells the compiler which type of operation is to be performed. Assume that an unsigned char y = 0xC9 Note: There are certain rules that governs the order in which operations are performed. Once a variable has been declared, operations can be performed on them. Below are some of the typical arithmetic operations that are usually carried out on variables. Multiplication(*) Division(/) Modulo(%) Addition (+) Subtraction/ Negation(-) 17 Operation x = ~y; x = y <<3; x = y >>4; x = y ^1; x =y 0x10; Results x = 0x36 x = 0x48 x = 0x0C x = 0xC8 x = 0xD9 19 Bitwise Operation These operators perform functions that will affect an operand onthebitlevel. These operators work on non-floating point operands such as char and int. There are six bitwise operators: OnesComplement(~) LeftShift(<<) RightShift(>>) AND(&) ExclusiveOR-(XOR)(^) OR(InclusiveOR)( ) 18 Logical and Relational Operators: These are binary operations that gives a Boolean result. This means that expressions with these operators return TRUE or FALSE values. ZeroistakenasFALSEandanon-zerovalueistakenasTRUE. Logical operators are: Negation or NOT(!) logicaland && logical OR 20 5

Relational Operators: These operators are used in operations where a comparison is to be made. In essence these operators ask about the relationship of two expressions in order to gain a TRUE or FALSE reply. These operators include: Is Equal to (== ) Is Not Equal to (!=) Less Than ( <) Less Than or Equal to (<= ) Greater Than (> ) Greater Than or Equal to (>= ) Here is an example; ( x ==y ) FALSE Assume that x = 3and y = 5. ( x!=y) TRUE 21 ( x >y ) FALSE Bit masking is a operation where single bits of a variable or register are changed. Bit masking is a common way to control microcontroller s peripherals (I/O) since single bits in microcontroller s registers represent some change to the state of the system, for example, enabling interrupts. Logical operators AND (&), OR ( ), XOR ( ˆ ) and COMPLEMENT ( ) are utilised to change single bits in a register without modifying the rest bits of the register value. In addition, SHIFT (<<, >>) operators are used to simplify changing the known bit in the register. 23 Note that the equality operator is == and not =. The equality sign alone( = ) is an assignment operator. Ifyouwanttocomparetwovaluesforequalitythen == shouldbe used instead of =.For instance if wewish to assign the valueof a tobwewritea=b. Ifwewanttocheckifthevalueofbisequaltoa,wewritea==b. The following code example shows how bit values are changed to attain the required register value. Set and clear single bit PORTA = PORTA 0x20; // Set bit 5 (bits 0, 1,..., 7) DDRA = DDRA & ~0x20; // Clear bit 5 DDRA = DDRA (1 << 5); // Set bit 5 using shift operator Set and clear multiple bits PORTD = PORTD 0x50; // Set bits 4 and 6 DDRD = DDRD & ~0x50; // Clear bits 4 and 6 PORTD = (PORTD << 4); // Shifting PORTD 4 bits to left 22 24 6

Increment operators: This operator modifies the value of a variable by increasing it by 1. Increment operators can be applied to variables as prefix or postfix, for example, x=x+1;isthesameas ++x; // pre increment operation x++; // post increment operation Decrement operators: This operator modifies the value of a variable by decreasing it by 1. Decrement operators can be applied to variables as prefix or postfix, for example: y=y-1 isthesameas --y y-- // pre increment operation // post increment operation 25 27 Letstakeaquicklookatanexample; Leta=1;and b=3*a++; Whatisthevalueofaandbrespectively? b=3anda=2. Nowleta=1;and b=3*++a; Whatisthevalueofaandbrespectively? b=6anda=2. 26 Compound Assignment Operators: These operators are used as a method to reduce the amount syntax required during the construction of a program. Here are some examples: (i) a+=3; //a=a+3 (ii) b-=3; //b=b 3 (iii)c*=5; //c=c*5 (iv)d/=a; //d=d/a (v)porta =0x20; //PORTA=PORTA 0x20 (vi)ddra&=~0x20;//ddra=ddra&(~0x20) NB, these expressions are processed from right to left. 28 7

Operator Precedence Rules Name Level Operators Order of evaluation Primary 1 [ ] ( ) -> L to R Unary 2 + sizeof ( )! ++ R to L Binary 3 * / % L to R Arithmetic 4 + - L to R Shift 5 << >> L to R Relational 6 < <= > >= L to R Control statements are used to control the flow of execution of a program. Among these statements are if/else, switch/case, and loop sentence likewhile,dowhile,and for. If/else statements are used to guide or branch an operation in either one of two directions. Theloopstatements(while,dowhile and for) areusedto controlthe repetition of a block of instructions. switch/case statements are used to make a decision from a block of severalinstructionsinorder to allow theprogram to flow inaconcise manner. 29 31 Name Level Operators Order of evaluation Equality 7 ==!= L to R Bitwise 8 & L to R Bitwise 9 ^ L to R Bitwise 10 L to R Logical 11 && L to R Logical 12 L to R Conditional 13?: R to L Assignment 14 &= -= = <<= >>= R to L The While Loop This is one of the most basic control elements of a program. The format in which the whilestatement is used is as follows: while(expression) or while(expression) statement; statement1; statement2;. 30 32 8

#include <stdio.h> unsigned char c; c = 1; printf("start of program \n"); while(c <= 100) printf("c = %d\n", int(c)); c++; printf("end of program \n"); while(1); This loop is often used where data is to be read. The test then verifies the data, and loops back to read again if it was unacceptable. The format of the do/whilestatement is as follows. do or do statement; statement1; while (expression); statement2; while(expression); 33 35 The do/while Loop This is very similar to the while loop except that the expression is tested after the loop body has been executed one time. This means that the instructions in a do/while loop areexecuted atleastoncebeforethedecisionismade onwhetherornottoremainintheloop. In the while construct, the test is made before the instructions in the loop are executed even once. 34 #include <stdio.h> unsigned char c; c = 0; printf("start of program \n"); do printf("c = %d\n", int(c)); c++; while(c < 100); printf("end of program \n"); while(1); 36 9

TheForLoop A for loop construct is usually used to execute a statement or a statement block for a specific number of times. This construct takes three arguments each separated by semi-colons. 1. The first is run before the loop is entered. This is usually the initialisation of the loop variable. 2. Thesecond isatest, theloopisexitedwhenthisreturnsfalse. 3. The third is a statement to be run every time the loop body is completed. The for loop is extremely flexible and allows many types of program behaviour to be specified simply and quickly. The if/else statements are used to guide or branch the operation of the program based on the evaluation of a conditional statement. An if/else statement has the form; If (expression) statement1; statement1; else statement1; statement2; 37 39 #include <stdio.h> unsigned char c; c = 0; printf("start of program \n"); for(c = 1; c <= 100; c++) printf("c = %d\n", int(c)); printf("end of program \n"); while(1); 38 The following test decides whether a student has passed an exam with a pass markof40 if(result>=40) printf("pass\n"); else printf("fail\n"); Other case is with if/else if sentence structure: if(expression1) statement1; else if(expression2) statement2; else if(expression3) statement3;... else(expression n) statement n; 40 10

#include <stdio.h> unsigned char c; c = 0; printf("start of program \n"); for(c = 0; c < 100; c++) printf("end of program \n"); while(1); if(c < 33) printf("0<c<33 "); else if ((c>32) && (c<66)) printf("33<c<66"); else printf("66<c<100"); 41 A switch/case statement is written in the following way. switch (expression) case constant1: statement1; statement2; case constant2: statement3; statement4; case constant3: statement5; statement6; default: statement7; 43 The switch case statement is used to execute a statement, or a group of statements selected by the value of an expression. This control statement is used in cases where; Only one variable (expression) is tested, all branches must depend upon the value of that variable (expression). The variable must be an integer type. Each possible value of the variable(expression) controls a branch. 42 unsigned char displayled(unsigned char blink) unsigned char display = 0; switch(blink) case 1 : display = 0b00000001; case 2 : display = 0b00000010; case 3 : display = 0b00000100; case 4 : display = 0b00001000; default : display = 0b00000000; return display; 44 11

Posted on website Assignment 2 Due: Tuesday October-3-2017 @2:30pm 45 12