Theory Lesson 2 Programming Theory Part 1 Programming Theory Part 1 Content • Data Types, Variables, Arrays and Type Conversions • Assignment and Arithmetic Operators • Boolean Expressions • Compound Operators Objectives • Understand the different data types • Know when to use specific data types • Know how to convert one data type to another using Arduino C • Know how to use the arithmetic operators and assign values to variables using Arduino C • Understand how the Boolean and comparison operators work and how to use them in Arduino C Binary A single binary digit (bit) has one of 2 possible values: Binary Multiple bits can be combined to form larger and more useful values: In most cases binary numbers are read from Right to Left • The Rightmost bit is called the Least Significant Bit (LSB) • The Leftmost bit is called the Most Significant Bit (MSB) 5 Binary The smallest group of meaningful bits is called a Byte • A byte is made up of 8 bits A byte can represent many different types of data • In this case the byte represents an unsigned integer • (positive whole numbers) Binary More bytes means more bits and a larger range of numbers • 1 byte = 8 bits = 255 max • 2 bytes = 16 bits = 65 535 max • 4 bytes = 32 bits = 4 294 967 295 max • 8 bytes = 64 bits = 18 446 744 073 709 551 615 max Binary What about negative numbers? Signed integers can represent positive and negative numbers To represent negative numbers a few things are needed: • 1 bit is reserved for the sign • 1 = negative • 0 = positive • Data bits of negative numbers are stored in 2’s compliment form* *2’s complement forms inverts all the bits and then adds 1 Binary Integers will only take you so far. With a bit more complexity a byte can represent a real number*. • Here the byte is broken down into 3 parts: • Sign bit • Exponent • Normalized Data (mantissa) In programming we call these floating-point** numbers *real numbers are normally required 16, 32, or 64 bits to be useful ** 8bit floating point numbers are called a mini-float 16bit floating point numbers are often called a Half-precision float 32bit floating point numbers are often called a Single-precision float 64bit floating point numbers are often called a double-precision float Binary A byte can also be used to represent alphanumeric characters like: ‘%’ , ‘A’ , ‘z’ or ‘5’ • There are different ways to represent or encode characters, but ASCII* one of the most widely used. • The ASCII encoding only needs 7bits of the byte, so bit 8 is always set to 0 *An ASCII table with most of the character is available later in the slides ASCII Table Binary Bytes can be used to represent Boolean* (true / false) values • A byte with a zero value = false • A byte with a non-zero value = true *Bool for short Data Types: Introduction So far, we have looked at how a single byte can represent different types of information These representations are called data types. When writing a program you use special keywords to tell the computer (or Arduino) how what data type to use and how to interpret the underlying binary information • Some data types require only one byte to represent data, but many datatypes require more than one byte. In the following slide we will look at some of the data type keywords that you can use in Arduino C *The exact keywords might differ between programming languages, but they most of the time there will be an equivalent. Data Type Unsigned Integer Data Types: Most Common Keyword Size (bytes) Data range Special Features byte 1 0 to 255 Zero and positive numbers only Signed Integer int 2 –32,768 to +32767 Supports negative values Single Precision Floating-point float 4 –3.4028235E+38 to +3.4028235E+38 Used for real numbers, supports negative values Character char 1 -128 to +127 0 – 127 are used to encode alphanumeric characters Boolean bool 1 0 and 1 0 = false Non-zero = true Instead of working directly with a memory address, keeping track of which addresses are in use, and how to interpret the data in each memory address data we can use variables Variables A variable allows: • us to give a meaningful name to memory locations • Allows the program to manage the memory • Allows the program to determine how to interpret the data Examples: Variables byte Pin6input; bool isReady; int A4Reading; char serialCharacter; float average; When naming variables there are some rules to consider: Variable Names 1. Variable names may not be the same as key words*. 2. Variable names may contain characters a through z and A through Z 3. Variable names may contain the underscore character (_) 4. Variable names may contain Digit characters 0 through 9 • But they can’t be used as the first character in the name *A keyword is any word that has special meaning to the C compiler. Example: int , setup, for , if Variable Names Arduino C might not care what you name your variable (as long as they are within the rules), but giving variables ‘good’ names will make you code easier to read and thus easier to trouble shoot. Here are some guidelines for creating good variable names: 1. Pick descriptive variable names • They should be long enough to give a clue as to what they do in, but short enough that you don’t get tired of typing it out. 2. Make use of a standard notation, like camel notation. • Here variable names begin with a lowercase letter with each the first letter of each sub-word being capitalized 3. Arduino C is case sanative. • This can be used to your advantage, but can also lead to errors if you are not careful. Some Example names that make use of the tips: • myFriend Variable Names • togglePrinter • reloadEmptyPaperTray • closeDriveDoor • CloseDriveDoor • Note: closeDriveDoor and CloseDriveDoor are not the same due to C being case sensitive. Value Assignment The Assignment operator ( = ) allows us to assign data to a variable. Examples: int a; Value Assignment a = 5; float _PI = 3.1415926; char c = ‘@’; bool isTrue = 0; Integer math Introduction Very fast to execute! Works like normal arithmetic, but with one exception: 1) 2) 3) 4) ( * + = Operators Example ) / - int % int quotient, remainder, result; sum = 5 + 6; // 11 product = sum * 3; // 33 quotient = product / 5; // 6 remainder = product % 5; // 3 • There are no fractions! • All answers are integers sum, product, difference; difference = quotient – remainder; // 3 % is the modules operator. It calculates the remainder of integer division = is the assignment operator. It is used to assign values (data) to variables. result = (sum + product) / quotient; Floating point math Introduction Slow to execute, especially if it needs to be done in software. Support fractions Operators 1) 2) 3) 4) ( ) * / + = Example float sum, product, difference; float quotient, remainder, result; sum = 5.0 + 6.0; // 11.0 product = sum * 3.0; // 33.0 quotient = product / 5.0; // 6.6 difference = quotient – 3.0; // 3.6 result = (sum + product) / quotient; /****************************************/ int a = 6; float b = 2.5, result = 0,0; result = a / b; Arrays An array is a list or collection of variables • of the same data type, • that are located next to each other in memory, • and that are accessed with an index number. You can create a array from almost all data types. When creating an array you add [] after the variable name Examples of creating arrays: int myInts[6]; int myPins[]; int mySensVals[6]; char message[6]; Arrays int marks[4]; Arrays marks[0] marks[1] marks[2] marks[3] marks[1] = = = = + 40; 55; 62; (marks[0] + marks[2])/3; Converting between data types Sometimes it is necessary to convert one datatype to another. int num1, num2; float result; num1 = 50; num2 = 13; The cast operator is used to convert between datatypes and forces calculations to be performed in the cast type. Cast operator: (datatype) //(float) casts num1 form int to float result = (float)num1 / num2; Advanced Arithmetic: Compound Assignment Operators Operator Description Operation Equivalent += Assignment by sum a += b; a = a + b; -= Assignment by difference a -= b; a = a - b; *= Assignment by product a *= b; a = a * b; /= Assignment by quotient a /= b; a = a / b; *= Assignment by remainder a % = b; a = a % b; Advanced Arithmetic: Increment And Decrement Operators In many cases you simply need to increment (add 1) or decrement (subtract 1) form a counter • E.g. counter = counter +1; • Or counter = counter – 1; Arduino C provides some special operators to assist us with increment and decrement operation • • • • pre-increment post-increment pre-decrement post-decrement Advanced Arithmetic: Increment And Decrement Operators pre-increment post-increment ++counter; counter++; The value of the counter is first incremented then used in the rest of the expression or statement The value of the counter is first used in the rest of the expression or statement then incremented int c = 5; int k; k = ++c; // k == 6, c == 6 int c = 5; int k; k = c++; // k == 5, c == 6 Advanced Arithmetic: Increment And Decrement Operators pre-decrement post-decrement --counter; counter--; The value of the counter is first decremented then used in the rest of the expression or statement The value of the counter is first used in the rest of the expression or statement then decremented int c = 5; int k; k = --c; k == 4, c == 4 int c = 5; int k; k = c--; // k == 5, c == 4 Advanced Arithmetic: Increment And Decrement Operators In some cases these operators may give unexpected results • Especially in cases when used as part of a binary expression in a if statement or loop However when used to simply increment or decrement a counter they are equivalent. counter++; ≈ ++counter; When dealing with complex expressions some rules need to be established to ensure the expression is resolved correctly. Precedence and Associativity rules to assist with this. Precedence and Associativity Precedence determines the order in which expressions are evaluated. • Lower levels execute first Associativity indicate the order in which two operators of same precedence are evaluated • Left to right • Right to left Level Operators Associativity () [] -> . (dot) Left to right ! ~ ++ -- + (unary) - (unary) * (indirection) & (address of) (cast) sizeof Right to left 3 * (multiplication) / % (modulus) Left to right 4 + (binary) - (binary) Left to right 5 << >> Left to right 6 < <= > => Left to right 7 == != Left to right 8 & (bitwise AND) Left to right 9 ^ (bitwise XOR) Left to right 10 | (bitwise OR) Left to right 11 && Left to right 12 || Left to right 13 ?: Right to left 14 = += -= *= /= %= &= ^= =| <<= >>= Right to left 1 2 Precedence and Associativity • What will the value of the test variable be after the following code has executed? Exercise int a = 5, b = 6; float c = 3.14; bool test = false; test += --b % a * (c - 0.14) * 15 ;