Home‎ > ‎CS 11M‎ > ‎

Variable Types and Serial I/O


Questions, Answers and Review

  • Questions from last class?
  • Questions about homework?

Key Terms for Today

  • A statement is a complete "line" of code. In C and C++ statements end with a semicolon. Some examples of statements are:
    digitalWrite(13, HIGH);
    cout << "Hello World" << endl;
    using namespace std;
  • A variable has a name and contains a value. Variables are declared with a storage type like:
    int myNumber;
    float myDecimal;
  • Variables may also be assigned:
    myNumber = 42; 
    myDecimal = 3.14;
  • When variables are used their contents takes the place of their name in a statement. For example:
    digitalWrite( LEDPin, HIGH );
  • A literal is a part of a statement that has an explicit value. Literals are most often numbers and strings. Here are some examples of literals: 
    12
    4.5
    "Hello World"
  • An expression is anything that can be used as a value. The most common expressions are variables and literals, but in C and C++ functions are also expressions (we'll talk about that later). 

Memory Concepts

Importance of Memory

  • Let us pretend that we have a friend, named Grace, and we want to remember her phone number: 555-2368
  • We can store our friend's phone number in our memory
  • We even give our friend's phone number a name, like "Grace's phone number"
  • We do not really know where in our brain we store Grace's phone number
  • However, whenever we need her phone number, we say to ourself, "What is Grace's phone number" and out pops 555-2368
  • Just like we store our friend's number in our memory, we can store it in a computer's memory
  • We store data in a computer program using a variable

    variable: the name of a place to store data in a computer's memory

  • Just like we do not know where in our brain we store a phone number, we do not know where in computer memory we store data
  • We simply give it a name and let the compiler decide where to store the data

Why Data Matters

  • Why should we care about variables or storing data?
  • Variables are the most important part of any computer program
  • Just like in real life, it is hard to do anything without memory
  • Consider a simple algorithm like adding two numbers:
    1. Get the first number
    2. Get the second number
    3. Add the first and second number and assign it to sum
    4. Display that sum is the result
  • How many variables did we need for this algorithm?
  • To find out, let us do some role playing
  • Imagine a conversation between Hal and Grace:
Hal: Hey Grace, I just learned to add two numbers together.
Grace: w00t!
Hal: Give me the first number.
Grace: 2
Hal: OK, give me the second number.
Grace: 3
Hal: OK, the answer for 2 + 3 is 5
  • After Grace says, "2", Hal has to store the number in his memory
  • The same things happens with the number, "3"
  • Even if the numbers were given in the same sentence, Hal would have to store the numbers somewhere in his memory
  • After adding the two numbers together, Hal has to store the result of the addition, at least temporarily, so he can state the answer
  • If we were to write a program to add two numbers together, the computer would have to use memory just like Hal
  • What sets a computer apart from other machines is its memory

Check Yourself

  1. A ________ is the name of a location to store data in a computer's memory.
  2. True or false: remembering data is rarely important when processing information.
  3. To add two numbers, we need to store at least, ________ pieces of information.
     a. 0
     b. 1
     c. 2
     d. 3

Memory organized by bytes

Review of Variables

  • Recall how a computer is organized
  • Main memory is organized as a long list of memory locations
  • Each location stores one byte and is identified by an address number
  • 1 gigabyte (GB) is about 1 billion bytes
    In RAM memory terms, 1 GB is 230, 10243 or 1,073,741,824 bytes

Storing Data

  • The main feature that separates computers from other machines is memory
  • To store and retrieve data in a program we use a variable
  • A variable is a name for a location in a computer's memory

Variables are a location in the computers memory

Variable Declaration

  • Here is an example C/C++ variable declaration:
    int num1;
    
  • When we declare a variable we tell the computer to set aside space to store data in its memory
  • Notice that a variable declaration has two parts:
    • int: the type of data the variable will store, integer values in this case
    • num1: the name of the variable, which we make up while coding
  • We pick variable names that are a sequence of letters and number
  • However, variables always start with a letter (preferably lower case)

Data Types

  • Like human memory, a computer must encode information before storage
  • As programmers we tell the computer how to encode information using data types
  • A commonly used data type is int which is shorthand for integer
  • An int is whole number with no fractions or decimal points

Assignment

  • After we declare a variable, we must assign the variable a value
  • To assign values, we use an assignment operator which is an "equals sign" (=)
  • The assignment is made in an assignment statement in this form:
    variable = expression;
  • Where:
    • variable: the name of the variables
    • expression: the data we want to store in the variable
  • An assignment statement assigns the value of expression (right side) to the variable (left side)
  • Examples:
    int num1;       // variable declaration
    num1 = 45;      // assignment
    int num2 = 12;  // declaration + assignment
    int total = num1 + num2;  // more complex expression
    
  • Notice that we can combine variable declaration with assignment
  • Good programming practice says we should assign a value when we declare a variable
  • Otherwise the value is undefined, though often 0, until the variable is assigned a value

Variables by Analogy

  • Storing values in a variable is like putting items in a box
  • For example, we declare a variable "a" and assign it the value: 1
    int a = 1;
    
  • We can think of the above statement as putting the value 1 in a box with the variable name "a", like the one shown below (image sources: David Goodger)

    value 1 in box a

  • We put names on a box
  • We put values inside of boxes
  • When we want to see the value inside a box we look at it with code like:
    cout << a; 
    
  • If we change the value of a variable, we are putting a new value in the same box, like:
    a = 2;
    

    value 2 in box a

  • Making a new variable and assigning one variable to another makes a copy of the value and puts it into the new box:
    int b = a;
    

    value 2 in box b value 2 in box a

  • We now have two different boxes that have independent values

Check Yourself

  1. The name of a location to store data in a computer's memory is known as a(n) ________.
  2. To specify the type of data stored in a variable, variable declarations include a(n) ________ ________.
  3. True or false: the "equals sign" (=) is the assignment operator in C++.
  4. The following code prints the value ________.
    int x = 42;
    cout << x;
    
  5. After executing the following statement, the value of number is ________.
    int number;

More About Variable Names

  • A variable name is a sequence of letters, numbers, or underscore characters
  • However, C++ has some limitations on variable names
  • Specifically, the first character must be either a letter or an underscore character ( _ )
    • Cannot be a number
    • A $ is allowed but its use is discouraged
  • Also, the variable name cannot be one of the C++ reserved words (keywords)
  • For a list of reserved words, see: C/C++ Keywords
  • Note that we cannot have spaces in a variable name
  • A space is NOT a letter, number or underscore character
  • Also, variable names are cAsE sEnSiTiVe
    • id, ID, iD and Id are all valid but different names

Programming Style: Variable Naming Conventions

  • Use meaningful names that are easy to remember
    • Well-chosen identifiers make it easier for other programmers (like the instructor) to understand your program
    • For example, the following is syntactically correct:
      a = b * c;
    • However, it hides the intent or meaning
    • Contrast this with:
      voltage = amps * resistance;
    • This tells other programmers the intent and meaning of the code
  • Use a consistent naming style, one of the following two commonly-used styles:
    1. Start with a lower-case letter and use uppercase letters as separators. Do not use underbars ('_').
      int myVar
    2. Use all lower case letters and use underbars ('_') as separators.
      int my_var
  • You must be consistent and only use one style in a program.
  • The instructor's preference is the first style.

Test Yourself

Which of the following are valid variable names?

  1. int myHello2;
  2. int 2myHello;
  3. int My_HeLlO;
  4. int my hello;
  5. int _a_very_long_variable_name_that_is_hard_to_read;
  6. int hel-lo;

More About Data Types

  • C++ requires that every variable has a data type
  • There are four general categories of basic data types in C++:
Category Explanation Examples
Boolean Logical values true or false true, false
Character Single letters, digits and special symbols 'A', '9'
Integer Numbers without decimal points 123, -987
Floating-Point Numbers with decimal points 1.23, -0.01
  • To specify a basic data type, we use a keyword that specifies the type
  • The most commonly used C++ data types are:
Type # of Bytes Use
bool 1 A true or false value.
char 1 All ASCII characters.
byte 1 Short integers from 0 to 255. Often used for communicating serial data.
int 2 Integers with a range from -32,768 to 32,767.
unsigned 2 Integers with a range from 0 to 65,536.
long 4 Integers with a range from -2,147,483,648 to 2,147,483,647.
float 4 Single-precision, floating-point numbers with 6 or 7 significant digits, +/- range, and exponents from about 10-45 to 1038.
double 8 Same as float. Normally would be 8 bytes and double precision compared to float with a greater range.
However, on Arduino AVR processor boards it is the same as float.
  • Note that the number of bytes used for storage depends on the system and compiler
  • The Arduino Uno has 2048 bytes of static dynamic memory (SRAM) to store variables

Examples of Variables with Data Types

bool isCool;
char letterGrade;
byte bugs;
int numStudents;
unsigned degreesKelvin;
float aBoat;
double pi;

Enforcing Data Types

  • The compiler verifies that a type is declared for a variable
  • Each variable can only store one type of data

    Data type: a set of values from which a variable may take its value

  • A data type is important because it tells the compiler how the programmer intends to use the data
  • For instance, we want some variables to store numbers and others to store text
  • We can think of a data type as a child's game where we match shapes to holes
  • C++ does not allow square data pegs in round memory holes
Matching shapes to holes

More information

  • Memory: Arduino tutorial information

Group Activity: Name that Data Type!

Exercise 1: Four-LED Binary Counter 

In this exercise we develop a 4-bit binary display using LEDs. We will be using the LEDs to indicate a 1 (on) or 0 (off) for the first 4 place values in the binary place value table. With this circuit, we can represent numbers from 0 to 15.

Parts List

  • Solderless breadboard
  • 4x LEDs
  • 4x resistors, in the range of 560 Ohms
  • Jumper Wires

Breadboard Layout

LED Construction Demo

  • Start with the Arduino unplugged.
  • Breadboard the circuit as shown in the video.
  • Make sure that the longer lead (positive) of each LED is connected to the Arduino pin and that the resistors connect the shorter lead (negative) to the GND strip (black wire).

Reference Diagrams and Test Code 

A diagram of the circuit in Fritzing is available from my CS-11M GitHub repository here: 


To view the circuit diagram for the LEDs open the CS-11M-Step1-LEDs.fzz file in Fritzing. When you're convinced that the wiring is correct test it using the sketch called TestProgram.ino.

Starter Code

Here's some code to get you started. This code turns all of the LEDs on (because 15 in binary is 1111). 

#include <ArduinoSTL.h>

using namespace std; 

const int LEDPins[] = {2, 4, 7, 8};

void setup() {
  Serial.begin(9600);
  for (auto pin : LEDPins) {
    pinMode(pin, OUTPUT);
  }
}

void numberToLEDs(int num) {
  for (int i = 0; i < 4; i++) {
    digitalWrite(LEDPins[i], bitRead(num, i));
  }
}

void loop() {
  numberToLEDs(15);
}

IMPORTANT: Copy-and-paste won't work unless you also include the ArduinoSTL library using the Sketch menu. 
  1. Start with a new sketch and save the program as bin4counter
  2. Copy the test code above into the bin4counter sketch.
  3. After compiling and uploading the above program, verify all the LEDs are on.
  4. Change the code in loop() to set the LEDs to a number of your choosing.
  5. Recompile and upload the modified program, and then verify all the LEDs show your number.

Programming the Binary Counter

  1. Add a new variable to the top of the program.
    int cnt = 0;
  2. After the loop, add code to update the cnt variable, like:
    cnt = cnt + 1;
    
  3. We want our counter to start over when it reaches 16, so add an if-statement to reset the count after updating the count variable:
    if (cnt > 15) {
      cnt = 0; // start over
    }
    
  4. After the if-statement, add a delay of 1 second.
  5. Compile and upload your code to verify it works correctly.
  6. Save your bin4counter.ino file to submit to Blackboard with the next homework.
When finished, please help those around you.

Summary

  • Computers store data and code in main memory
  • Variables are how we can store data in our programs
  • Variables can be assigned new values while our program executes
  • Variables must be declared before use.
  • To initialize a variable, declare a name and assign a value.
  • Simple assignment statements have a variable, equals sign and an expression:
    variable = expression;
  • The expression is computed before the assignment
  • All variables are stored in a binary format

Further Study:

Arduino Serial I/O

Introduction to Serial I/O

  • In computing input/output or I/O (or informally IO) is communication between a computer and other devices
  • Serial I/O is how we get Arduino to communicate with our PC
  • All Arduino boards have at least one serial port
  • A serial port is a connector by which a device that sends data one bit at a time may be connected to a computer
  • One way to transmit data through the serial port is with a USB cable
  • Like data is stored in a computer using binary numbers, data is transmitted in binary

Serial Data Transmission between an Arduino and PC


Source: LadyAda.net

Serial Monitor

  • The serial monitor allows our computer to display messages sent by the Arduino board
  • We have coded serial output before using cout
  • There are other serial commands that we will look at today, including getting input over the serial port
  • Using serial I/O, Arduino can receive input from a PC keyboard

Check Yourself

  1. A connector for transmitting data between devices is known as a serial ________.
  2. True or false: a USB cable can be used to transmit serial data.
  3. Data in a serial port is transmitted one ________ at a time.
    1. bit
    2. bite
    3. block
    4. byte

Serial I/O Setup

  • To get started, we open the serial monitor by pressing the special button or using the menus:
    Tools > Serial Monitor
  • We view the information in the large area of the serial monitor window
  • A PC can send information to the Arduino in the small text field at the top of the monitor

Opening the Serial Monitor from the Arduino IDE

Opening the Serial Monitor

Setting Up Serial Communication

  • We must set up the serial port in the setup() function of our Arduino program
  • We use the Serial.begin(baud) function, where baud is the communication speed
  • Example:
    Serial.begin(9600);
    
  • We must set the baud rate on the serial monitor to the same rate as our code

Serial Monitor Baud Rates

Serial monitor baud rates

Which Baud Rate?

  • We can use higher baud rates and our serial monitor will communicate faster
  • However, high speed communication is not always necessary
  • Baud rate of 9600 is often used and is something of a standard
  • Many serial peripherals such as GPS modules will have 9600 as a default baud rate

Check Yourself

  1. True or false: all Arduino boards have at least one serial port.
  2. True or false: we can use the serial monitor for Arduino to communicate with a PC.
  3. The highest baud rate shown in the above image is ________.
  4. In the following code the baud rate is set to ________.
    Serial.begin(9600);
    
  5. True or false: we should always set the baud rate to the highest speed available.

Line Endings

  • Not all letters in the computer's alphabet are visible 
  • Non printable characters play an important role
    • They tell the output device that text should start on a new line
    • They can change the output color or style 
    • They separate input 
  • Be sure that you tell the serial monitor to use the "Newline" line ending style as shown below:
Serial monitor example

Input and Output

  • Recall the main parts of a computer
  • Input sends information to the computer
  • Output is the computer sending information
  • We now review these parts starting with output

Output

  • We have been using cout to display information on the serial monitor
  • The command cout sends data to standard output, which is the serial port
  • The "<<" takes data from the right-hand side and sends it to the serial port 
    cout << "Hello, World!" << endl; 

  • Most basic data can be output to the console including
    • Variables (like num1)
    • Literals (like 12.34)
    • Expressions (which can include all of above)
  • We can display multiple values in one cout
  • However, each data item must be separated with a << operator
  • For example:
    int numberOfDragons = 3;
    cout << numberOfDragons << " dragons." << endl; 

  • Three values are output in order:
    • The value of the variable numberOfDragons
    • A literal string " dragons."
    • An end-of-line (newline) character
  • In the above example endl is a special word for an end-of-line (newline) character
  • Notice that the last letter of endl is an "el" and not a one
  • Another way to output an end-of-line (newline) is to use "\n"
  • For example:
    int numberOfDragons = 3;
    cout << numberOfDragons << " dragons.\n"; 

Input

  • So far we have used an assignment operator "=" to assign a value to a variable
    int numberOfDragons = 3;
  • Another way to assign a value to a variable is to read it from the console
  • The keyboard input console is called cin (console input)
  • We use the >> operator with cin to send data to a variable
  • For example:
    cin >> numberOfDragons;

In this example, whatever valid integer number the user types is stored in the variable numberOfDragons

Prompting Users

  • Good programming practice is to always "prompt" users for input like:
    cout << "Enter number of dragons: "; 
    int numberOfDragons; 
    cin >> numberOfDragons; 
    cout << "You entered " << numberOfDragons << " dragons\n"; 
  • Every cin should have a cout prompt before it

Check Yourself

  • The following code displays ________.
    int numberOfGames = 12;
    cout << numberOfGames << " games played.\n";
  • Before getting input from a user, common practice is to display a(n) ________.
  • True or false: the << and >> always point in the direction the data is flowing.

Arduino Only: Communicating Via the Serial Class

  • cin and cout are the C++ standard way of doing text-based I/O. 
  • They don't exist by default in Arduino (that's what ArduinoSTL is for)
  • In Arduino the Serial class is used instead. 
  • All the serial commands are contained in the Serial class
    • A class is a way to encapsulate logically related functions and variables
    • We will discuss classes later in the course
  • We can categorize most Serial class functions as either control, input or output
  • Control functions setup and test the serial connection
  • Input functions get information from a source, such as your PC
  • Output functions send information to a destination, such as the serial monitor on a PC

Some Commonly Used Serial Control Functions

Name Description
if (Serial) if (Serial) is used as an if-statement to test if the specified Serial port is ready.
available() Serial.available() gets the number of bytes available for reading from the serial port Receive buffer.
begin(baud) Serial.begin(baud) sets the data rate in bits per second (baud) for serial data transmission.
setTimeout(time) Serial.setTimeout(time) sets the maximum milliseconds to wait for serial data on some input functions. See documentation for the list of functions.

Some Commonly Used Serial Input Functions

Name Examples
parseFloat() Serial.parseFloat() returns the next valid floating point number from the Serial buffer.
parseInt() Serial.parseInt() returns the next valid integer number from the Serial buffer.
read() Serial.read() returns the first byte of incoming serial data, or -1 if no data is available.
readString() Serial.readString() reads characters from the Serial buffer into a string and returns the string.

Some Commonly Used Serial Output Functions

Name Description
print(data) Serial.print(data) writes data to the serial port as human-readable ASCII text.
println(data) Serial.println(data) writes data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n').

Check Yourself

  1. Of the following, the one that is not a category of Serial functions is ________.
    1. control
    2. graphical
    3. input
    4. output
  2. True or false: Serial.begin() is rarely called.
  3. To get an integer from your PC's keyboard, call the function Serial.________.
  4. True or false: by default, end of line characters are attached to serial input commands.

Exercise 2: Interactive Binary Counter

In this exercise we add user I/O to the Four-LED Binary Counter circuit.

Specifications

  • Start with the exercise from earlier
  • Open the bin4counter sketch and then save it as a new sketch named binio.
  • At the end of the setup() function, add the following commands to setup the serial connection and prompt the user:
    Serial.begin(9600);
    cout << "Enter a number 0 to 15";
  • Place the following code into the loop() function:
    cin >> cnt; 
  • Remove the code that adds 1 to cnt and the delay()
  • Compile, upload and run your code to verify it works correctly. 
  • When run, your code should prompt you for a number and then display the binary equivalent on the LEDs. If you have problems, ask a classmate or the instructor for help.
  • Submit your bin4io.ino file with the next homework.

When finished, please help those around you.

Wrap Up and Reminders

  • When class is over, please shut down your computer.
  • Complete unfinished exercises from today before the next class meeting
  • Bring your Arduino kits to the next class meeting (and every meeting)
Subpages (1): Lab 2: HEX Files
Comments