Home‎ > ‎CS 11M‎ > ‎

Computer Organization and C/C++ Basics


Questions, Answers and Review

  • Questions from last class?
  • Questions about homework?

Computers and Programming Basics

Computer Instructions and Organization

  • A computer is really just a machine that stores data and follows instructions
  • Because a computer is a machine, it can be powerful but is stupid:
     Computer = powerful but stupid
  • A computer is powerful because it flawlessly executes billions of instructions per second
  • A computer is stupid because it only mechanically follows simple instructions

How a Computer Works

  • Computers have no insight or understanding
  • Computer operations are nothing like a human's thought
  • Instead a computer mechanically follows instructions
  • All computer instructions are very simple like:
    instruction 1: 1 + 1
    instruction 2: 2 < 0?
    instruction 3: ...
    instruction 4:
    instruction 5:
    ...

People Versus Computers

  • People should not be intimidated by computers
  • Any human is more intelligent than the most powerful computer
  • Humans develop the instructions for the computer to follow
  • The instructions that computers follow are called programs
  • The people who develop programs are called programmers
Computer overview 
  • Input Devices: send data to computer
  • Output devices: allows computer to send information to the user
  • CPU: controls which instruction to execute and processes data like:
    • Retrieve numbers from main memory
    • Perform simple arithmetic
    • Save numbers to main memory
  • Main Memory: data and program storage while program runs
  • Secondary memory: "permanent" storage using devices like hard disks, flash drives, cloud storage

Self Test 

  1. On a traditional computer identify where the following parts are located
    1. Input devices
    2. Output devices
    3. CPU
    4. Main memory
    5. Secondary memory
  2. Where are those things in Arduino? What makes Arduino different?

Check Yourself

  1. Computers are machines that ________.
    1. design computer programs
    2. think intuitively
    3. are imprecise and slow
    4. execute programs
  2. The Central Processing Unit (CPU) is primarily responsible for ________.
    1. performing program control and data processing
    2. ensuring data persists when electrical power is turned off
    3. enabling a human user to interact with the computer
    4. interconnecting computers that are separated by distance
  3. The purpose of main memory is to store both ________ and ________.
  4. True or false: computers can execute a large number of instructions in a fraction of a second.

More Information

Programming Languages

  • Recall how a computer is organized
  • The heart of a computer is the Central Processing Unit (CPU or processor)
  • The CPU processes all the computer instructions
  • The following is the Arduino Uno's CPU (an Atmel ATMega 328P)
Arduino CPU IC 

Processor Instructions

  • A processor executes extremely primitive machine instructions like:
    1. Move memory location 40000 into register r1
    2. Subtract the value 100
    3. If the result is positive, start processing at location 11280
  • These instructions are encoded as numbers such as:
    161 40000 45 100 127 11280
    
  • While the computer only understands binary, we are using decimal numbers for convenience

Assemblers

  • Each processor has its own set of machine instructions
  • Looking up numeric codes for instructions like these is tedious and error prone
  • To make programming easier, computer scientists first developed a program called an assembler
  • An assembler allows a programmer to assign short names for the machine codes like:
    movw r30, r24
    subi r30, 0x12
    breq .+8 
    
  • The assembler translates the names into the correct machine codes
  • While easier for humans to use, assemblers still have two problems:
    1. We still have to enter a great many primitive instructions to create a program
    2. The instructions change from one processor to another

Higher-level Languages

  • To make programming easier, computer scientists developed higher-level languages
  • Higher-level languages let us write more readable instructions like:
    if (interestRate > 100) {
        cout << "Interest rate error";
    }
    
  • Programmers call these instructions source code

Compilers

  • To translate these high-level instructions to machine instructions we use a compiler

    compiler: a program that translates source code into machine instructions

  • Another advantage of higher-level languages is we can move programs to another processor more easily
  • Moving programs to another processor requires someone to write a compiler
  • After the new compiler is available, we can recompile our program with (hopefully) no changes
  • There are thousands of higher-level languages
  • We use the Arduino IDE C++ compiler for this course

Early History of C++

  • C developed by Dennis Ritchie at AT&T Bell Labs in the 1970s
    • 1973 - UNIX kernel rewritten in C
    • 1978 - K&R C specified based on the book The C Programming Language
    • 1989 - ANSI C standard released
  • C++ developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s
    • 1979 - Stroustrup begins work on "C with Classes"
    • 1982 - Name changed to C++
    • 1983 - First used by AT&T
    • 1985 - First commercial use
    • 1988 - ANSI C++ standard released

Check Yourself

  1. True or false: computers can directly carry out C++ source code instructions.
  2. True or false: an assembler translates high-level language programs to a set of computer instructions.
  3. To translate source code to machine code we use a ________.
  4. For a high-level language like C++, which of the following statements are true?
    1. easier to program than machine code
    2. easier to program than assembler code
    3. easier for a human to read
    4. easier to move from one type of processor to another
  5. True or false: the ANSI standard for C++ was released after the ANSI standard for C.

More information

Arduino Compiler

  • The Arduino IDE uses a C++ compiler, specifically avr-g++
  • C++ includes C code, so we will learn both C and C++ for this course
  • When the Arduino IDE starts we see C/C++ source code like:
    void setup() {
      // put your setup code here, to run once:
    }
    void loop() {
      // put your main code here, to run repeatedly:
    }
    
  • Code in setup() runs one time
  • Code in loop() runs over and over forever
  • These two blocks of code are known as function definitions
  • Arduino requires us to have these two functions
  • We will eventually write more functions
  • For now think of the functions as boilerplate we must always include

Compiling Sketches

  • When we write a program, we start with source code
  • Source code is a text listing of C/C++ commands in human readable form
  • When we press the Verify button we start the compile process
    Verify button
  • Compiling means that we translate source code into machine code
  • Source code is the human understandable text inside the sketch
  • Machine code is what the computer understands
  • When compiling is successful, we will see a message at the bottom of the source code window like:

    Done compiling

  • We can see the flow of the compiling process in the following image
  • The executable program at the end can be uploaded to Arduino's flash memory

Compilation Process

Compilation process

Running a Compiled Program

  • To run or execute a program we press the Upload button Upload button
  • The compiled code is transferred to the Arduino's flash memory
  • After the upload process completes, the Arduino boards starts executing the code

Check Yourself

  1. Another word for "verifying" on the Arduino is ________.
  2. Code that humans type is known as ________ code.
  3. Code that computers understand is known as ________ code.

Using Arduino Libraries

The Arduino IDE gives you a convenient way to use other people's code, called libraries. One library in particular will be necessary for this class. 
Here's how to download a library:
  • Select: Sketch -> Include Library -> Manage Libraries...
  • That brings up the Library Manager window where you can search for libraries. 
    • Search for "STL"
    • You will see a library called "ArduinoSTL" that's written by me!
    • Select Install
After downloading a library you must add it to your sketch. To add the ArduinoSTL library to your sketch (after following the instructions above) do this:
  • Select: Sketch -> Include Library -> ArduinoSTL 
  • You should see a new line of code appear at the top of your sketch. 

Example: An empty sketch with ArduinoSTL included. 
#include <ArduinoSTL.h>

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

The ArduinoSTL library enables many core functions in C++ that are not available in the default Arduino environment. I created this library so that you would have the "full" experience with C++ so your code will look more like code written for a traditional computer. 

Using the Serial Monitor

  • Arduino has a tool to help us debug code called the Serial Monitor
  • The Serial Monitor allows our computer to display messages sent by the Arduino board
  • Information is transmitted using the USB cable
  • We view the information in the Serial Monitor window
  • We open the Serial Monitor by pressing the special button or using the menus:

    Tools > Serial Monitor

Location of the Serial Monitor Button on the Arduino IDE

Serial monitor button

Printing to the Serial Monitor

  • To transmit to the Serial Monitor, we add the following command to setup():
    Serial.begin(9600);
    
  • To print to the monitor, we add the following command to our code:
    cout << "Your text here." << endl;
  • The cout command expects the insertion operator ( << ) then arguments to be printed
  • We can print values like 123 or text
  • We must enclose any text we print in double-quote marks
  • Notice how the TX LED flashes every time cout is called
  • We will explore how to use the serial monitor in the next exercise

Everyone's First Program: Hello World!

#include <ArduinoSTL.h>
using namespace std; void setup() { Serial.begin(9600); } void loop() { cout << "Hello world!" << endl; delay(1000); }

More Information

C/C++ Language Basics

  • All Arduino sketches use the C/C++ programming language
  • We will start with the following fundamental concepts:
    • Sequence
    • Variables

Sequence

  • C/C++ code runs from top to bottom, left to right in a continuous sequence
  • This sequence is true for most programming languages
  • Example code sequence:
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);
    
  • The order that programming statements are executed is important to a successful program
  • The Arduino IDE numbers the lines to help us follow the flow

Check Yourself

  1. Of the following, the one that is NOT a fundamental C/C++ concept is ________.
    1. Sequence
    2. Style
    3. Variables
    4. Repetition
  2. For the following code, the last statement to execute is ________.
    1. digitalWrite(13, HIGH);
    2. delay(1000);
    3. digitalWrite(13, LOW);
    4. None of these
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);
    
  3. True or false: the Arduino IDE numbers the lines to help us follow the flow.

Memory organized by bytes

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
  • 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 delayPeriod;
    
  • 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
    • x: 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 ledPin;   // variable declaration
    ledPin = 13;  // assignment
    int delayPeriod = 1000; // declaration + assignment
    
  • 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

Example Code with Variables and Assignment

int ledPin = 13; int delayPeriod = 100; void setup() { pinMode(ledPin, OUTPUT); } void loop() { digitalWrite(ledPin, HIGH); delay(delayPeriod); digitalWrite(ledPin, LOW); delay(delayPeriod); delayPeriod = delayPeriod + 50; }
  • Notice the addition of two variables to the Blink program
  • The variables are substituted for the numbers
  • Using a variable allows us to change the numbers with fewer code changes
  • To change a pin number, we change one line instead of three
  • How many changes would have been required for the delay?
  • Note how two words are joined to create a single variable name

Arithmetic with Variables

  • We can do arithmetic with variables and numbers using +, -. * and /
  • Notice the changes in the Blink sketch
  • The delay starts at 100 ms
    int delayPeriod = 100;
    
  • The delay increases by 50 ms during each loop() call (cycle)
    delayPeriod = delayPeriod + 50;
    
  • The increased delay causes LED cycles to get slower
  • Press the Reset button to see the rate get faster again

Variable Scope

Variables give a chunk of computer memory a name. Use the variable name in your program to recall the value stored inside of it. The name can only be used in particular places, inside the scope of where the name was declared. Consider the following program: 

int file_var = 1;

void setup() {
 int setup_var = 2;
}
  
void loop() {
 int loop_var = 3;
}

There are three variables in this program. The program below is legal:

int file_var = 1;

void setup() { 
 int setup_var = file_var + 2; 
}
  
void loop() {
 int loop_var = file_var + 3;
}

Because file_var is declared in the global scope. You can use file_var anywhere in this sketch. The program below has an error:

int file_var = 1;

void setup() { 
 int setup_var = file_var + 2; 
}
  
void loop() {
 int loop_var = setup_var + 3;
}

The variable setup_var is declared inside of setup() therefore it can only be used inside of setup().

Exercise: Variable Arithmetic 

In this exercise we tell your Arduino how to do arithmetic!

Parts

  • Arduino board
  • USB cable

Starter Code

#include <ArduinoSTL.h>

using namespace std;

void setup() {
  Serial.begin(9600);
  int a = 7; 
  int b = 2;
  int numAdd = a + b; 
  cout << "a + b = " << numAdd << endl;
}

void loop() {
}
Specifications
  1. Start the Arduino IDE, copy the starter code above and paste it into the main IDE window.
  2. Save the project using the name arithmetic (File > Save As...) to a convenient location like the Desktop or the Arduino projects folder.
  3. Add the ArduinoSTL library.
  4. Compile the sketch to verify you copied the starter code correctly. When compiling is successful, you will see a message at the bottom of the source code window like:

    Done compiling

  5. Upload the code and open the Serial Monitor to view the output.

    Serial monitor

  6. Add code for subtraction of a, b like:
    int numSub = a - b;
    cout << "Subtraction: " << numSub << endl;
    
  7. Add code for multiplication and division as well.
  8. Compile and upload your code to verify it works correctly.

    You should now be able to see an output in the Serial Monitor like:

    a + b = 9
    a - b = 5
    a * b = 14
    a / b = 3
    

    If you have problems, ask a classmate or the instructor for help.

  9. Save your arithmetic.ino file to submit to Blackboard with the next homework.

When finished, please help those around you.

Summary

  • Computers mechanically follow simple instructions
  • A programming language is a way to provide those instructions to a computer
  • The language we use for this course is C/C++
  • We use the Arduino IDE to develop source code for our programs
  • Source code is a text listing of C/C++ commands in human readable form
  • To convert the source code to machine code, we use a compiler program
  • We start the compile process by pressing the Verify button on the Arduino
  • To execute the compiled program we upload the machine code to our Arduino
  • By default, C/C++ commands run from top to bottom, left to right in a continuous sequence
  • A variable is a name for a location in a computer's memory
  • We declare a variable with the type of data it store like the following:
    int delayPeriod;
    
  • Once we have declare a variable we store information in the memory using an assignment operator, like:
    delayPeriod = 1000;
    
  • We can do arithmetic with variables and numbers using +, -. *, and /, like:
    delayPeriod = delayPeriod + 50;
    

Wrap Up and Reminders

  • When class is over, please shut down your computer.
  • Complete unfinished exercises from today before the next class meeting
Comments