Programming

Introduction to Programming in C and Arduino

Objectives

After this chapter you should be able to:

  • Identify When to Use Local, Global, and Static Variables
  • Correctly Use Arithmetical and Relational Operators
  • Identify When to Use If-Statements, While Loops, and For Loops
  • Correctly Implement If-Statements, While Loops, and For Loops

All Pictures in This Section Can Be Enlarged By Clicking on Them

All Vocab is Listed at the End of This Section


Constants and Variables



Constants are values in a program that cannot change throughout a program’s execution. When a constant is defined, a program essentially just sees the constant and pastes the defined value into the function instead. Constants can be initialized using pound-define (#define) and are usually declared in all capital letters. Variables are locations in memory for storing values and can change over time. All variables have a type (int, long, char, etc.) and a visibility: global or local. Further, variables in certain instances can be static.


Local and Global Variables


Type refers to what can be stored in a variable; different types can hold different values. For example, an int, or integer, can hold two bytes (or values from -32,768 to 32,767) while a char, or character, can hold one byte (or values from 0-255). For this reason, ints are usually used for numbers while chars are usually used for alphanumeric symbols.

Data Types and Sizes




Visibility refers to where or how the variable is declared; the two kinds of visibility are global and local. Global variables are declared at the top of a program and are accessible throughout the entire program and all related functions. Local variables are defined inside a certain function, state, or other small part of a program and are not accessible beyond the outer limits of whatever they are declared in.


In the picture on the right, notice the line highlighted in yellow and the Arduino error message. This will occur if you try to access a local variable outside of where it is defined.


Error in Arduino



Static variables do not change between invocations in the program in which they are used; they are similar to global variables in that way. Static variables can only be manipulated or used in the function in which they are declared, but they do not lose their value between multiple function calls.



Finally, it is important to remember that variables are case sensitive. The common format for naming a variable is called “camel case” and consists of the first (or only) word in lower case and any additional words beginning with an uppercase letter. Variable names never have spaces; underscores are an acceptable alternative.

Static Variables and Serial Output


Operators

Operators are used in programs for the manipulation of data and variables. They are used for arithmetic, bit-wise operations, and comparisons.





Arithmetical operators consist of adding (+), subtracting (-), multiplying (*), dividing (/), and modulo (%). Modulo gives the remainder after a division. For example, having an operation 5%3 would mean to divide 5 by 3 and output the remainder (2). Arithmetical operators can be combined as a sort of short-hand to make programs look cleaner: +=, -=, *=, /=. A short-hand operator can be used with two values where at least one is a variable: for example “a” and 5. The code would be written as “a += 5;” and it means “a” equals the sum of “a” and 5. Therefore, if “a” had been equal to 11 before that line, it would now be equal to 17. Each short-hand operator works much in this way.


Arithmetic Operators




Relational operators consist mainly of less than (<), greater than (>), is equal to (==), and not (!). Relational operators “less than” and “greater than” can be combined with “equals” to achieve “less than or equal to” and “greater than or equal to.” “Not” can be combined with any of “less than,” “greater than,” and “equal to.” It is also important to note that when comparing two values to see if they are equal, a program must use two equal signs; using only one equals sign will simply reassign your variable rather than comparing it.


Relational Operators




Logic

If-Statements

Syntax

if (argument) {
     //do something
}

What Are They?


If-statements are tools that execute other statements if a certain condition is met. If-statements can be stand-alone; this means that they are only looking for one condition and executing in that specific case. They can also be used with an else-statement that serves as a catch-all for every instance when the condition isn’t met.

Example:


Example Using If-Statement in Arduino

What will this code print? Click on it for the answer





When a function or program needs to check more than one condition, an else-if can be implemented.

if (argument) {
     //do something
}

else if (secondArgument) {
     //do something else
}

else {
     //do something different
}

Finally, sometimes there is a need to use an if-statement inside an if-statement. These are effective but not efficient. State machines are the cleaner way to accomplish the same goal. Find more information on state machines here

Loops



Loops are used in programming to allow program statements to repeat a definite or indefinite amount of times. The two main types of loops are while-loops and for-loops.


While-Loops

Syntax:


while (condition) {
     //do something
}
//more code to be run while condition is false

What Are They?


While-loops are a type of loop that continues as long as a Boolean statement is true. The program runs through the loop checking the condition before running through each time. When the condition is found to be false, the loop “breaks” or stops repeating those statements and moves on to the next statement or function in the program.

Example



Example of While-Loop Using Arduino

Click on program to see how variable values will change

Note: Print statements have been removed from this code for clarity


For-Loops

Syntax:


for (Initial Counter Value; Counter Limit; Counter Instruction) {
//do something
}

What Are They?



For-loops are loops that run a specified number of times before moving on to the next part of the code. For-loops have an index variable that simply keeps track of how many times the loop has run and either increments or decrements at the beginning of the loop. After adjusting the index variable, the loop then checks a conditional statement that compares the index to some pre-defined value; as long as the statement is true, the loop will run.

Example




Example of For-Loop Using Arduino

What will this code print? Click on it for the answer

Break and Continue


Break is a tool that can stop a loop at any point, usually given a certain condition. When break is triggered, the program will move to the first lines below the loop and execute them.


break;
Using Break with Arduino




Continue is a tool that can alter the progression of a loop given a certain condition. When a loop has a continue condition and the condition is met, the program will skip over all the rest of the code in that loop and jump back to the top of the loop. The loop will then run again from the top.


continue;


Using Continue in Arduino

Concept Questions


Int
Float
Char



Int
Float
Char



6
32,767
10



For-Loop
If-Statement
While-Loop




Section Vocab

Variables - locations in memory for storing values and can change over time

Char - Data type generally used for characters (or ASCII). Holds 1 Byte

Int - Data type use for integer numbers. Holds 2 Bytes

Unsigned Int - Data type used for larger, positive integer numbers. Holds 2 Bytes but can't be negative

Long - Data type used to hold very large integer numbers. Holds 4 Bytes

Float - Data type used for decimal numbers. Holds 4 Bytes and up to 6 decimal places

Visibility - Where a variable is defined and where it can be accessed in a program

Local Variable - Defined in a function. Can only be called in that function.

Global Variable - Defined in the program set-up. Can be called anywhere in the program

Static Variable - Variable value does not change between invocations

If-Statements - Will execute program code if a certain condition is true

While Loops - Will execute program code while a certain condition is true

For Loops - Will execute program code for a certain, set number of iterations

Break - Breaks a loop. Must be called in a loop.

Continue - Skips to the end of the iteration of the loop without running program lines under it. Loop then starts over