EP1000

A Short Introduction to Programming

Programming Constructs

Programming Errors

Structured Programming

Structured programming can reduce the occurance of logical errors in any programming language. It is a technique tha specifies the way/method of writing code, which is easy to understand and follow and produces good results.

Structure programming allows us to

Structured programming is made up of THREE main structures

Structured Programming

You can write almost 90% of all programs using structured programming!

Documentation

One of the biggest problems in programming is good documentation.

 

The Arduino IDE

In this session, we will look at some of the specifics that we need to take note when writing code for out projects. In essence, we need to learn a bit about the “syntax” of the programming language.

The Arduino IDE (Integrated Development Environment) is a cross-platform application (runs on Windows, MacOS and Linux) which allows you to enter the source code for your application programming. The IDE includes

The Arduino IDE uses the GNU toolchain to convert the source code into machine-readable code and the program avrdude to convert the executable code into a text file that is loaded onto the Arduino board.

For our purposes, we will ignore the internal workings of the IDE and concentrate on how to write programs for our applications. This involves understanding the syntax of code i.e. the grammatical structure/format in which words and phrases are arranged to create the instructions. The syntax of Arduino code is very C/C++ like.

Sketch

#define LED_PIN 13                  // Pin number attached to LED.

void setup() {
    pinMode(LED_PIN, OUTPUT);       // Configure pin 13 to be a digital output.
}

void loop() {
    digitalWrite(LED_PIN, HIGH);    // Turn on the LED.
    delay(1000);                    // Wait 1 second (1000 milliseconds).
    digitalWrite(LED_PIN, LOW);     // Turn off the LED.
    delay(1000);                    // Wait 1 second.
}

Notes:

#define LED_PIN 13

void setup()

// Pin number attached …

 

Arduino Programming Language

Data Types

Data type What it stores # bytes
void used only in function declarations to indicate that the function does not return any value  
boolean stores true or false 1
char stores 1 character e.g. ‘A’ 1
unsigned char stores numbers from 0 to 255, no negatives 1
byte equivalent to unsigned char 1
int whole numbers from -32766 to +32767 (depends on processor 2
unsigned int whole numbers from 0 to +65535 2
word equivalent to unsigned int 2
long extended size whole number -2,147,483,648 to 2,147,483,647 4
short equivalent to unsigned int 2
float numbers with decimal point, ranging from -3.4028235E+38 to 3.4028235E+38 4
double equivalent to float 4

Notes

Constants

// floating point constant, note the following:
//   1. const keyword used
//   2. a data type is specified, storage space (2 bytes) is assigned
//   3. an identifier is used to indicate the address of the storage
//   4. you need to assign ('=') a value
//   5. end the statement with a semi-colon (;)
const float PI = 3.141516;

// pre-processor command
#define MYPI  2.141516
//   1. # indicates a pre-processor command, not an instruction
//   2. no data type is indicated
//   3. no storage space is used
//   4. whenever the pre-processor sees the word MYPI, 
//      it substitutes it with 3.141516, taking up code space

Variables

Operators

Operators are symbols that tells the compiler to perform a specific mathematical or logical operation with the operands.

Control statements

    ...
    swState = digitalRead(3);
    if (swState == Hi)
    {
        // true condition    }
        digitalWrite(13, HIGH);
        digitalWrite(12, LOW);
    }
    else {
        // false condition
        digitalWrite(13, LOW);
    }
    ...

Loops

Loops provide a means of performing a task or executing a block of statements repeatedly.

Functions

Arduino function

void setup() {
    pinMode(13, OUTPUT);
    pinMode(2, INPUT);
    pinMode(3, INPUT);
}

void loop() {
    int x = digitalRead(2);
    int y = digitalRead(3);
    result = sum(x, y);             // call the function sum()
    if (result > 0)
        digitalWrite(13, HIGH);
    delay(1000);
}

// function sum
// only in Arduino can the functions be declared after they are called.
int sum( int a, int b){         // function declaration
    int ans;
    ans =  a + b;
    return ans;                 // return value
}

Arduino IO Functions (Digital)

The Arduino Uno board has 14 pins which can be configured as digital I/O

The procedure in using the digital pins are

  1. use pinMode() to configure the port to be input or output. The port stays in this mode until another pinMode() is applied, reset occurs or powered off.
  2. use digitalRead() to read the input, or
  3. use digitalWrite() to output a value.

An extra mode INPUT_PULLUP can be applied on the digital I/O pins. This creates a 20K pull-up resistor to be enabled in the input mode.

Serial Communications

The Arduino IDE provides a very useful tool in debugging your programs and applications using the Serial Communications module. The Uno board connects the Serial port of the ATMel processor to the USB bust to provide serial monitoring, and hence a way of obtaining output via the Serial Monitor on the IDE.

The Arduino using Asynchronous Serial communications to communicate with the IDE. This means that data (usually 8bits) is sent one-bit-at-a-time through the serial interface using the RS-232 asynchronous protocol via the USB to your IDE.

The following program shows how you can use the Serial Communications interface to send messages to your IDE.

void setup(){
    Serial.begin(9600);     // setup Serial Library for 9600bps comms
    Serial.println("Hello world");      // send a start message
}

void loop(){
    // send the message "ok" every 5 seconds
    Serial.println("ok");       // send the message ok
    delay(5000);
}
  1. Compile and upload the code to the Arduino board
  2. On the IDE open the Serial monitor, you should see the welcome message and the ‘ok’ message appearing every 5 seconds.

You can use the Serial communcations functions to provide basic Serial output and input to you applications.

Reference: Serial Communications

 

References:

Arduino Programming

  1. TutorialsPoint: Learn Arduino for beginners
  2. Electronics Hub: Basic Arduino Tutorials for Beginners
  3. Adafruit - Simon Monk Arduino Getting Started
  4. [Arduino Getting Started](https://arduinogetstarted.com/

Online References

  1. Arduino IDE Reference
  2. Great books from Simon Monk:
    • Programming Arduino (2nd Ed)
    • Programming Arduino: Getting Started with Sketches (2nd ed.)

I/O Programming

  1. ElectroSome: Using Pushbutton Switches

 

Assignment 12

In this assignment, you will attempt to write simple programs with the Arduino IDE and Uno R3 board. You can test the programs on the simulator first before wiring and implementing the actual circuits on the physical Arduino board.

I have provided approximate timings for you so that you do NOT spend all your time (doing something you like and neglecting other modules!)

Time Task  
45 min Read the notes, follow up with the TutorialsPoint Site  
30 min Simulate and test your circuit using TinkerCAD  
60 min Physically wire-up and test your circuits using the Uno R3 and breadboard  

This may be a long assignment (for beginners). If in doubt check the simulation on TinkerCAD first before implementing it on the breadboard..

Complete the following programming assignments:

Programming assignments

  1. Simple LED control
    • connect a LED with a current limiting resistor (220 ohm) to port 6 of the Arduino Uno board.
    • write a program to blink the LED in a variety of patterns.
  2. Controlling 3 or more LEDs
    • using the same technique, connect 3 or more LEDs of different colors to the Arduino board using pins 6, 7, and 8.
    • write a program to produce running lights i.e. the LEDs are lit in sequence e.g. R -> G -> W -> R -> G -> W and so on.

Uno SW LED

  1. Adding a switch to the flashing lights
    • add a switch to the circuit in (2). You should use a pull-up resistor of 10K if you are operating in INPUT mode.
    • when the switch is pressed, the LEDs will light up. Pressing the switch again will turn the LEDs off.
    • write and test this program.
  2. Use the switch in (3) to control the type of light-up and flashing of the LEDs, for example,
    • initially, LEDs are all in the OFF state.
    • pressing the switch, turns on only the RED LED.
    • pressing the switch again, turns on only the GREEN LED
    • pressing the switch again, turns on only the WHITE LED
    • pressing the switch again, turns on all LEDs
    • pressing the switch again, turns off all LEDs returning to the first state.
  3. Modify your program in (4) to flash the LED(s) instead.

  4. Modify your program such that if you press the switch for longer than 3 seconds, the system switches off all LEDs and returns to the initial state.

Documentation

Remember to document your work on the github site, you should write

 

July 2020