The C Programming Language Guide for the Robot Course work Module

Similar documents
A Fast Review of C Essentials Part I

General Syntax. Operators. Variables. Arithmetic. Comparison. Assignment. Boolean. Types. Syntax int i; float j = 1.35; int k = (int) j;

ME 461 C review Session Fall 2009 S. Keres

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C: How to Program. Week /Mar/05

DEPARTMENT OF MATHS, MJ COLLEGE

Chapter 2 - Introduction to C Programming

Have examined process Creating program Have developed program Written in C Source code

CS Programming In C

Introduction to C Language

ANSI C Programming Simple Programs

C Language Programming

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

Fundamental of Programming (C)

printf( Please enter another number: ); scanf( %d, &num2);

BLM2031 Structured Programming. Zeyneb KURT

Computer Organization & Systems Exam I Example Questions

CSE 351: The Hardware/Software Interface. Section 2 Integer representations, two s complement, and bitwise operators

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

EL6483: Brief Overview of C Programming Language

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

More on C programming

Creating a C++ Program

Programming for Engineers Introduction to C

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

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT- 3 Introduction to C++

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

Embedded Systems - FS 2018

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Full file at C How to Program, 6/e Multiple Choice Test Bank

CS16 Exam #1 7/17/ Minutes 100 Points total

C Programming Language. Microcomputer Architecture and Interfacing Colorado School of Mines Professor William Hoff

Computer System and programming in C

Computers Programming Course 6. Iulian Năstac

UIC. C Programming Primer. Bharathidasan University

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Variables and literals

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

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

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

Chapter 1 & 2 Introduction to C Language

CS 61C: Great Ideas in Computer Architecture Introduction to C

/* defines are mostly used to declare constants */ #define MAX_ITER 10 // max number of iterations

CS201 Some Important Definitions

Beginning C Programming for Engineers

C Syntax Out: 15 September, 1995

Course Outline Introduction to C-Programming

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

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

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

Fundamentals of Programming

Page 1. Where Have We Been? Chapter 2 Representing and Manipulating Information. Why Don t Computers Use Base 10?


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

Work relative to other classes

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion

Objectives. In this chapter, you will:

INTRODUCTION 1 AND REVIEW

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz

Review of the C Programming Language for Principles of Operating Systems

Chapter 12 Variables and Operators

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Arithmetic and Bitwise Operations on Binary Data

Computer Architecture and System Software Lecture 02: Overview of Computer Systems & Start of Chapter 2

EL2310 Scientific Programming

First of all, it is a variable, just like other variables you studied

DETAILED SYLLABUS INTRODUCTION TO C LANGUAGE

Unit 3. Operators. School of Science and Technology INTRODUCTION

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Programming, numerics and optimization

Lecture 4 CSE July 1992

Chapter 03: Computer Arithmetic. Lesson 09: Arithmetic using floating point numbers

Chapter 3: Operators, Expressions and Type Conversion

ISA 563 : Fundamentals of Systems Programming

Lecture 3. More About C

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

CS107 Handout 13 Spring 2008 April 18, 2008 Computer Architecture: Take II

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

If you note any errors, typos, etc. with this manual or our software libraries, let us know at

C Programming a Q & A Approach

These are notes for the third lecture; if 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.

Prepared by: Shraddha Modi

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Expression and Operator

Programming in C++ 5. Integral data types

C Programming Language

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Embedded Systems - FS 2018

EL2310 Scientific Programming

Data types, variables, constants

Transcription:

The C Programming Language Guide for the Robot Course work Module Eric Peasley 2018 v6.4 1

2

Table of Contents Variables...5 Assignments...6 Entering Numbers...6 Operators...7 Arithmetic Operators...7 Bitwise Logic Operators...8 Relational Logic operators...9 Assignment Operators...10 Type Conversion...11 Comments...11 Functions...12 void...12 The Main Function...13 Pre-Declaration...13 Global and Local Variables...14 External Variables...14 Flow Control...15 For Loop...15 While Loop...16 Do While Loops...16 If statement...17 Switch statement...18 Pointers...19 Type conversion to a pointer...19 Pass by Reference...20 Arrays...21 Passing Arrays to a Function...22 Arrays and Pointer Arithmetic...23 Structures...24 Pointers to Structures...25 Compilers Linkers and Make...26 Header files...27 Definitions and Macros...29 Program Structure and Layout...30 This guide is for the Robot Course Work Module. It does not contain a complete description of the C programming language. It only contains the syntax that is used in the Course Work Module. 3

4

Variables In C, a variable must be declared before it can be used. For example int a; unsigned long b; int and unsigned long are the types of the variables. This defines the size and the range of the variable. For the particular compiler we are using, the types are as follows. Type Size in bits Variable Types Range char 8 0 to 255 signed char 8-128 to 127 unsigned char 8 0 to 255 short (signed) 16-32768 to 32767 unsigned short 16 0 to 65535 int (signed) 32-2147483648 to 2147483647 unsigned int 32 0 to 4294967295 long (signed) 32-2147483648 to 2147483647 unsigned long 32 0 to 4294967295 long long (signed) 64 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 unsigned long long 64 0 to 18,446,744,073,709,551,615 float 32 1.175494351e-38 to 3.40282347e+38 double 64 init8_t 8-128 to 127 uinit8_t 8 0 to 255 2.22507385850720138e-308 to 1.79769313486231571e+308 init16_t 16-32768 to 32767 uinit16_t 16 0 to 65535 init32_t 32-2147483648 to 2147483647 uinit32_t 32 0 to 4294967295 init64_t 64 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 uinit64_t 64 0 to 18,446,744,073,709,551,615 5

The type char was originally intended to hold a character, but it can also be used hold an eight bit integer. If you wish, you can declare several variables at once. The following declares x, y and z to be of type int. int x, y, z; You can also set the initial value of a variable. Here the initial value of c is set to zero. unsigned char c = 0; Assignments Examples a = 42; b = 24 + a ; Each line is terminated with a semicolon. In C, the semicolon indicates the end of a statement. Entering Numbers The following are all ways of enter the same number, but using different number systems. Decimal (Base 10) c = 198; Binary (Base 2) c = 0b11000110; Hexadecimal (Base 16) c = 0xC6; You can also force a number to be of a particular kind. U or u after the number says treat as unsigned. c = 198U; L or l after a number says treat as a long c = 198L; Treat as an unsigned long. c = 198UL; 6

Operators Arithmetic Operators + Add - Subtract * Multiply / Divide % Remainder << Left Shift >> Right Shift Note : In this course the variables we use are all integers. Therefore, the results of division is truncated to a whole number. Example int a; int b; a = 5; b = (a + 6)*3; Left Shift Operator c = 0xD3; 1 1 0 1 0 0 1 1 a = c << 3; 1 0 0 1 1 0 0 0 Shift every binary digit to the left by n. This is equivalent to multiplying by 2 n. Right Shift Operator c = 0xD3; 1 1 0 1 0 0 1 1 a = c >> 5; 0 0 0 0 0 1 1 0 Shift every binary digit to the right by n. This is is equivalent to dividing by 2 n. 7

Bitwise Logic Operators ~ Bitwise NOT, every bit inverted. & Bitwise AND Bitwise OR ^ Exclusive OR These operations operate on each bit Examples of bitwise logic on unsigned chars a = 0b1011; 0 0 0 0 1 0 1 1 b = ~a; 1 1 1 1 0 1 0 0 Every bit in b set to the inverse of the corresponding bit in a. c = 0x0f; 0 0 0 0 1 1 1 1 d = b & c; 0 0 0 0 0 1 0 0 Each bit in d is the result of ANDing the corresponding bits in b and c. 8

Relational Logic operators > Greater than! NOT < Less than && AND >= Greater than or equal OR <= Less than or equal = = Is equal to! = Is not equal to These are used for comparing numbers in IF statements and WHILE loops. The results are either one for true or zero for false. Examples if ( left == 0 && right == 0 ) etc The condition is true if left AND right are both equal to zero. while ( a > 0) a--; Count down to zero. 9

Assignment Operators The increment operator a++ ; ++a ; is equivalent to a = a + 1; The position of the double plus sign determines when the variable is incremented. A double plus after the variable will increment after the rest of the expression has been executed. For example y = 5 * a++ ; is equivalent to y = 5 * a; Then a = a + 1; While a double plus before a variable will increment before the rest of the expression. y = ++a * a ; is equivalent to a = a + 1; Then y= 5 * a; The decrement operator works in a similar way. a ; a ; is equivalent to a = a 1; There are other assignment operators. a += 10; is equivalent to a = a + 10; a -= 10; is equivalent to a = a - 10; a *= 10; is equivalent to a = a * 10; a /= 10; is equivalent to a = a / 10; a %= 10; is equivalent to a = a % 10; a >>= 3; is equivalent to a = a >> 3; a <<= 3; is equivalent to a = a << 3; a &= 0b10; is equivalent to a = a & 0b10; a = 0x10; is equivalent to a = a 0x10; a ^= 0x10; is equivalent to a = a ^ 0x10; 10

Type Conversion Normally, all the variables used in any expression are of the same type. However it is sometimes necessary to convert a variable from one type to another. To do this you put the name of the type that you want to convert to, in brackets, in front of the expression. Example int a; unsigned long b; a = 2; b = (unsigned long)a*5; or b = (unsigned long)(a*5); // convert a to unsigned long // convert (a*5) to unsigned long Comments The text between /* and */ are comments. These are pieces of text that are ignored by the compiler, but make the program more understandable. You can also use // to indicate that anything following on this line is a comment. /* This is a comment */ // and so is this 11

Functions Functions are collections of code that can be called and executed from other parts of the program. Take for example a function called fname declared below : int fname (int a, int b) int c; // Local variables at the top c = a + b; // Executable code below return c ; The purpose of this function is to add together two integers. To use fname in your program, you would use something like this d = fname(3,5); Where d is of type int. When the function is called, 3 is copied into a and 5 is coped into b. The return line defines the value that the function gives back to the calling code. In this case the value in c is copied into the variable d. The int before fname in the declaration of the function defines the type of variable that the function returns. Functions can only return one item. void Sometimes function are required that don t return any value. In this case the dummy variable type void can be used. void f2 (void)... Void means empty. So in this case the function does need any parameters and does not return any value either. To use it you would insert the following into your code. f2(); 12

The Main Function All executable code within a C program must be within a function. The top level function is always called main. The main function is defined in this form. int main (void)... //Put your code in here Any other functions should be defined outside and below main. Pre-Declaration The C compiler works through the text of a program from top to bottom. So for the compiler to work correctly, it needs to know about any functions or variables before it is used. The convention in C is that main is the first function in the program, but you also predeclare each of the other functions before main. A pre-declaration is just a copy of the top line of the original definition, but with a semicolon at the end. For example, a pre-declaration of fname looks like this. int fname (int a, int b); // Pre-declaration of fname /* The Main Program */ int main (void)... // What ever. /* Definitions of other functions */ int fname (int a, int b) // The definition of fname int c; c = a + b; return c ; 13

Global and Local Variables Where a variable is declared determines where it can be used. A variable declared inside a function is local to that function and can only be used within the function. If a variable is declared outside of any function, then it is a global variable. These can be used in any function. /* global variables */ int a; unsigned long b; int main (void) /* local variables */ int c; unsigned char s; /* The program code */ a = 2; c = a + 5; Global variables are easier to read with the debugger. For this reason they tend to be used a lot more in this course than is normal. External Variables It is also possible to use global variables that have been define in another file. extern unsigned char s; Says that a variable s of type char exists and can be used in this file, but the actual declaration of the variable has been define else where in another file. 14

Flow Control For Loop The general form of a for loop is :- for( <initialise> ; <condition> ; <increment>) <statements> <initialise> <condition> <increment> <statements> What to set on the first loop. Must be true to execute loop. The change at the end of each loop. The code to be executed each time round the loop. Example of a for loop a = 0; for (x = 0; x < 10; x++) a += x; x = 0 The first time round the loop, x is set to zero. x < 10 The loop will carry on executing while x is less than 10. x++ After each loop, x is incremented by one. So this loop adds the integers 0 to 9. for( x = 10; x > 0 ; x ); Note the terminating semicolon. There are no statements to execute. This counts down from 10 to 1. It is a short delay. 15

While Loop A while loop will keep executing the code in the loop while a condition is true. For example a = 0; x = 0; while (x < 10) a += x; x++; Again, this loop adds the integers 0 to 9. While can also have an empty loop. c = 10; while( c!= 0); c is decremented until c is equal to zero. In C, zero is treated as false, any other positive number is true. So while(1) etc Will loop forever. Do While Loops Do while loops are like a while loop, except that the condition is tested at the end, instead of the beginning of the loop. do a = GPIOC->PDIR & 0b01000 ; while( a == 0); Wait for bit 3 of Port C to go low. 16

If statement This is used to execute a set of statements only if a condition is true. For example if ( a > b) vout = 0; // executed if a is greater than b There is another type of if statement that contains an alternative if the condition is false. if ( a > b) vout = 0; else vout = 0xff; // executed if a is greater than b // executed if a is not greater than b If a is not greater than b, the else part is executed 17

Switch statement A switch statement is used to select from a number of different options. In the example below, we use an unsigned char called a to choose which piece of code to runs. switch(a) case 0: break; // any statements to be executed //when a = 0 go in here // jump to the end of the switch statement case 1: // statements executed when a = 1 go in here break; // jump to the end of the switch statement case 5: break; // statements executed when a = 5 go in here // jump to the end of the switch statement case 10: case 11: case 20: // Code executed if a is 10, 11 or 12. break; // jump to the end of the switch statement default; break; // Code executed if a is not equal to any // of the above options. 18

Pointers The address operator, &, allows you to find the address of a variable. Here it is used to store the address of the variable x into p. p = &x; The variable p is called a pointer. A pointer is a variable used to hold the address of another variable. You can then write to the memory location pointed to by p. *p = 12; The operator * indicates the contents of the address in the following pointer. In this case, as the variable x is stored at the address pointed to by p, it sets the variable x to 12. For this to work, C needs to know what type of variable the pointer is pointing at. If p is a pointer to an int, it needs to be defined as follows : int *p; This says that the content of the address pointed to by p is of type int. In other words, *p is of type int. Type conversion to a pointer To write or read from a specified memory location, you cast the address into a pointer. p = ( int *) 0xf100; This turns the address into a pointer to an int, then stores the pointer into the variable p. Then you can use *p to read or write to the memory location. 19

Pass by Reference So far, the mechanism used to get information into and out of a function is called pass by value. Only the value of the number is transferred into the function and only one value is returned. Pass by reference means that you pass the location of the number in memory to the function instead of the value. int x; int y; add_sub(10, 6, &x, &y); etc void add_sub(int a, int b,int *sum, int *diff) *sum = a + b; // Store directly into address *diff = a - b; Here the address of x and y are passed to the the function. sum is a pointer to x and diff is a pointer to y. So that the function writes the result of the assignment directly into the variables x and y. Passing by reference is a two way process. It can be used to pass information into and out of a function. Functions in C can return only one value, so pass by reference is used as a method to get multiple results out of a function. 20

Arrays unsigned char data[64]; data[0] = a; a = data[63]; This declares an array with 64 elements of type unsigned char. The elements are numbered 0 to 63. Copies the variable a into element 0 of the array data. Sets a equal to element 63 of data. for(i = 0 ; i < 64 ; i++) data[i] = 0; Sets each element of data to zero one at a time. You can also specify the contents of an array when it is created. The example below shows how to create an array that contains the numbers 1, 2, 3 and 4. int myarray[4] = 1,2,3,4; This is the equivalent to int myarray[4] ; myarray[0] = 1; myarray[1] = 2; myarray[2] = 3; myarray[3] = 4; 21

Passing Arrays to a Function Using an array inside a function in C is not the same as in MATLAB. Instead of passing the whole contents of an array into a function, you pass a pointer to the array. For example, the following function finds the sum of the first three elements in an array. int sum3(int a[]) int s; s = a[0] + a[1] + a[2] ; return s; To use this function on the array called myarray, defined on the previous page, you pass the name of the array. x = sum3(myarray); The array name is also a pointer to the first element in an array. As a pointer is being used, you can also use this mechanism to change the content of an array. Any writes to the array inside the function will update the original array. void zero3(int a[]) a[0] = 0; a[1] = 0; a[2] = 0; 22

Arrays and Pointer Arithmetic A pointer is not exactly the same as the address. In some ways it is more like an array. For example, suppose that we have the following array. int a[10]; The symbol a is a pointer the first first element of the array a[0]. a + 1 is a pointer to a[1]. In general, x = *(a + k); is the equivalent to x = a[k]; When you add one to a pointer, you do not add one to the address. Instead you move to the address of the next variable in memory. As some variables require several address locations of storage, this is not necessary the next address in memory. For example :- if the variable p is a pointer to an int and p is pointed at an address 0xf100. p = ( int *) 0xf100; Then p + 1 will point to 0xf104. Four address locations are required to store an int, so the address will increase by 4. Warning The C compiler does not check that you are doing something stupid. Writing data to a memory location without knowing what you are writing to can cause all sorts of problems. You could overwrite another variable or crash the computer. For example, suppose we have defined the following variables int a[10]; int b; int *p; Then all the following will set a memory location to zero, but we do not know what is located in that memory address. p = &b; p++; *p = 0; *(a-2) = 0; a[10] = 0; As the last element is a[9]. 23

Structures To define a structure called mystructure, with three fields a, b and c, all of type unsigned int. struct unsigned int a; unsigned int b; unsigned int c; mystructure; To write to a field mystructure.a = 3*n + 24; You can use a structure field anywhere you could use a variable. y = mystructure.a + 2*mystructure.b + 3*mystructure.c ; If is often more convenient to define your own data type that can be used throughout your code. For example typedef struct unsigned int a; unsigned int b; unsigned int c; my_type; Then you could create three structures, all of the above type. my_type x; my_type y; my_type z; As before, you can use the fields of these structures where every you would use a variable. For example. z.a = x.c + y.b; 24

Pointers to Structures Supposing that we define a pointer to a structure. my_type *ps; ps = &x; Where my_type and x are as defined on the previous page. To access the field a of the structure, we could use. (*ps).a However, that is a bit cumbersome. Instead, C has its own notation for accessing a field of a point to structure. ps->a For example, the follow function adds the three fields together. int sum_fields(my_type *ps) int s; s = ps->a + ps->b + ps ->c; return s; 25

Compilers Linkers and Make As your program gets more complicated, you will find that you want to combine several C files into one program. Each.c file needs to be converted into machine code by the compiler. Then the machine code is linked together into one program ready to download into the microprocessor. main.c camera.c motor.c Source code Compiler Compiler Compiler main.o camera.o motor.o Machine code Linker Project.axf File to download If you had to do this by hand it becomes tedious. However, there is a program called make that will automatically do all the above for you. Make will only do what is absolutely necessary. It will only compile a.c file if the file has changed since it was last compiled. Selecting Build in Xpresso runs make to compile and link the whole project. 26

Header files The compiler will not know anything about any function defined within another file, unless you declare what the function is at the top of your file. There is however an easy way to do this using header files. For example, suppose that the function main is in a file called main.c. In addition you have another file called adc.c that contains two functions called adcinit and adcread. To use these functions in main, you first produce a header file called adc.h that contained the declaration for each for the functions. void adcinit(void); char adcread(void); Then you could include these declarations by adding the following to the top of main.c : #include adc.h Any command beginning with a hash (#) is picked out by the C preprocessor that is run before the compiler. The preprocessor will copy the whole of adc.h into main.c in place of the #include line. See the diagram on the next page. The filename in quotes means that this is a header file that you have written and can be found in the local directory. There are other header files that are provided by the manufacturer. These are all in a directory called include within the installation files. To use these files, you put the file name between angled brackets. #include <stdio.h> This header contains functions in the I/O library such as printf. 27

main.c #include adc.h adc.h void adcinit(void); char adcread(void); C preprocessor void adcinit(void); char adcread(void); The preprocessor has replaced the #include with the contents of the header file adc.h Compiler main.o Machine code version of main.c adc.o Linker Project.axf 28

Definitions and Macros There is another preprocessed command that can help to make your program easier to understand. The #define command searches your code for an item and replaces it with another item. For example #define TRUE 1 searches the program from TRUE and replaces it with 1. You could then write while(true) c++; Which will count up forever. A macro is a definition that contains an argument. For example, consider the two following definitions. #define LED 29 #define BIT(n) 1<<n BIT is a macro that produces a constant with the n th bit set and all other bits zero. The red LED is connected to bit 29 of port E. To toggle the LED on or off, we write 1 to bit 29 of the Port Toggle Output Register (PTOR) of port E. GPIOE->PTOR = 1<<29; We can do the same by using the BIT macro. GPIOE->PTOR = BIT(29); We can also use the LED definition with BIT. GPIOE->PTOR = BIT(LED); After processing with the C preprocessor, the three different lines of code above will all look the same. 29

Program Structure and Layout The following shows the how various components of a program fit together. Preprocessor commands Standard preprocessor commands Your preprocessor commands Predeclaration of functions other than main. Global variable declarations Main Local variables declarations Executable code Other Functions Most of this structure is automatically created when you start a new project. You will be adding your own.c files to a project. To use the microcontroller internal registers within these files, you must include the header file containing the definitions and register locations. #include "MKL46Z4.h" 30