Tuesday, November 5, 2013

Introduction to Arduino Programming (Workshop 2) - Detailed Guide

Workshop Contents

I. C, C++, and the Arduino IDE

II. Variables
III. Methods
IV. Conditional
V. Loops
VI. I/O
VII. Demo - Pseudo Code Version
VIII. Demo - Code and Testing

I. C, C++, and the Arduino IDE


Programming on the Arduino is done with a variant of the C Language specific to the Arduino IDE. There are a few small differences, mainly regarding added functionality to relate to the Arduino properly, but for the most part programming is done in what can be thought of as C Language. 


C is the oldest programming language that is widely used today (created in 1972) and is a terrific language to start off with. It is considered a "High Level" language, meaning that on the spectrum of programming languages, it is closer to the English Language than machine code (all 0s and 1s). C is also very fundamentally similar to C++, Java, and many other modern languages, making it relatively easy to jump into one of these other languages from C. 


C isn't by any means a perfect language - there are a good handful of things that it can not do or that it is not good at doing, bit it is still an incredibly versatile, powerful language that works perfectly for programming Arduinos.


There are several key components to programming in C; this guide will cover those from a theoretical perspective that should be applicable to several other languages. The examples used will be in C to demonstrate proper C syntax.


Note: You can add comments to your code by putting two backslashes before any thing that isn't code. This way you can type notes in the program that don't affect the actual program. This is a good way for anyone reading the code to understand in plain English what is going on. It becomes more and more valuable as the program gets bigger and more complicated.


//This is a comment. 


/*

This is also a comment.
*/

Look for comments in the example code for further explanation.





II. Variables

The first programming element in C is called the variable. A variable is a block of storage that stores a value that can be changed without changing it's representation in the program. For instance, you could have the number '5' assigned to a variable called 'number.' Whenever you use 'number' in your program, it really means '5.' It's possible to simply put the actual, hard programmed number '5' in your program, but it is essential to be able to change values as a program runs, something the programmer cannot properly account for by putting every literal value into the code. 


There are many types of variables. Each stores a specific type of data. Types cannot be converted from one to another (usually):


Integer (int) - a simple integer value, positive or negative. When declaring a variable of type integer the abbreviation 'int' is used.

Double (double) - a decimal based number, positive or negative. Whole numbers can still be represented as doubles but they will have zeros for the decimal place (5.00).
Character (char) - individual letters and other characters.
String (String) - multiple characters. Strings in C should be handled as arrays of characters.
Boolean (bool) - a binary value, either true or false. 
Array - an ordered collection of any of the previous types of variables.

Variables must be declared (created) to be used. To declare a variable the type and a name for the variable are used, followed by a semicolon to end the line. The variable can be unassigned (no value) or assigned with an equals sign and a value:


[type] [name]; OR [type] [name] = [value];


int count; //declare variable called count of type int

double value = 5.4;
char letter1 = 'a';

An array is an ordered collection of a single type of things. An array is declared like the type it stores except brackets and a value are added at the end of the name to set the number of spots the array has for value. The easiest way to fill an array is at the beginning:


int arr1[10] = {4,2,3,4,7,6,0,1,10,11};         (Notice I set the value to 10 and have 10 values placed.)


arr1[0] returns 4

arr1[1] returns 2
arr1[15] returns an ERROR

It's important to remember that you can access values of the array by putting a number in the brackets after the name, but remember that the first member of the array is accessed with 0, and the last is accessed with the size of the array minus one.


III. Methods


A method is a unit of code that performs a set task (or tasks) when called upon. It's a great way to organize your code so code isn't repeated every time its is needed, making the program better organized and easier to read. Methods are declared with the output type (optional), name, and input type(s) and name(s):


[type] [name]([type] [name], [type] [name], ...)

{
     [content]
}

int add(int val1, int val2)
{
     int val3 = val1 + val2; //make a new int and set it to the sum.
     return val3; //return the value
}

The first type is the return type of the method - a possible value the method returns. If the method doesn't need to return anything type "void." After the name there are always parenthesis  and if there are any input variables, then these are inserted here with either types and names. To manipulate these inside the method, use the names listed in the input parameters.

int sum = add(1,4);


When used like the above example after the add method was declared, sum will now be equal to 5 because add took those two numbers, added them together, and returned the sum.


IV. Conditional


A conditional statement tests something and then does something else if the test returns true and doesn't do something if the test returns false. There are three types of conditionals - if, else if, and else. To use any of these statements an if statement must be used first, followed by any number of else if statements, and ending with an else statement if desired:


if ([condition]) //if something is true...

{
      [content] // ...do this
}
else if ([condition]) //if not, then if this is true....
{
      [content] //...do this
}
else //as a last, catch-all case (if nothing before it was true)
{
      [content] //do this
}

Conditions often compare two things - 'x < y,' 'y > x,' etc. One key condition is if two things equal each other - in this case you can't use a single equals sign. Two must be used (==) because one indicates an assignment, not a comparison. Two equal signs mean a comparison is made.

V. Loops


One of the most power programming tools available to the user is loops. A loop completes a sequence multiple times. There are three types of loops - the while loop, the do while loop, and the for loop.


while ([condition])
{
        [content]
}

A while loop is similar to a single if statement, except it repeats the sequence repeatedly until the condition becomes false. Once it becomes false (or if it starts false) the program move on to the next line.

do
{
       [content]
} while ([condition]);

The do while loop is just like the while loop except it executes its content once and then checks the condition to see if it's true or not before repeating it again.

For loops can be tricky but they are the most powerful option for a loop - they run a set number of times using an incremental variable.

for ([initialize/set/declare variable to increment]; [condition to check variable against]; [increment variable])
{
      [content]
}

Start with this standard for loop:

int count3 = 0;
for (int i = 0; i < 100; i++)
{
     count3 = count3 + 3; // Add three to count3 100 times overall.
}

It starts with integer i = 0, checks to see if i is less than 100, adds one to i (i++ is the same as i+1) and then completes the content. This way the loop runs for a certain controlled number of times (100). Pay attention to your starting and ending values for incrementing - here 0-100 results in 100 iterations, but 1-100 would result in only 99.

VI. I/O


I/O is pretty simple. Here are a few commands to start with:


digitalWrite(led, HIGH); //sets a digital pin to HIGH (on)
serial.print("Test"); //prints to the serial monitor
serial.println("Test); //prints to the serial monitor and goes to the next line
serial.read(); //reads from the serial monitor input
serial.parseInt(); //reads in an integer from the serial monitor input
VII. Demo - Pseudo Code


In the next part there is a program that will be run to demonstrate a number of programming principles outlined in this guide. This part of the guide explains what the code does and how it works from a lighter, more theoretical perspective. It is important to think of how a program should work in simple English before converting it into code.

The example program is a number guesser. Basically a random number is generated, the user sets the number of guesses that may be attempted, the user guesses, and the program gives feedback - too high, too low, correct number, or out of guesses.

Part 1 - Setup the Program

Start the serial monitor connection and setup the random number generator.

Part 2 - Setup the Game

Make a random number, ask for the number of guesses to be set, read in the user's input, and prepare to start taking guesses.

Part 3 - Read in Guesses

As for a guess, read what the user provides, and establish it as the guessed value.

Part 4 - Test the Guess

Check the random value compared to the guess and return feedback, monitoring the number of tries remaining.


That's the program! With a fundamental understanding of how the program is put together, go ahead and read through the code to understand how it works line by line and then try the code out and see how it runs. You'll run it by plugging your Arduino into your computer and compiling and uploading the code onto the Arduino. Finally, open the Serial Monitor to play the game.

VIII. Demo - Code and Testing


void setup()

{
    Serial.begin(9600);
    randomSeed(analogRead(0)); //Pull a random value off of an analog pin to get a truly random value.
}

void loop()

{
  int value = random(0, 100); //Get a random number between 0 and 100, the desired range.
  int tries = 0;
  Serial.println("A random number between 0 and 100 has been generated. Enter the number of guesses allowed (0-9) and press ENTER: ");
  while (Serial.available() == 0) {}  // Wait for the user to input something.
  while (Serial.available() > 0) //When there is something types in...
  {
    tries = Serial.parseInt(); //Read in the guess number
  }
  int guess;
  bool win = false; //an indication of the winning status
  for (int i = tries; i > 0; i--) //Counting down the number of attempts...
  {
    Serial.print("Guess a number: ");
    while (Serial.available() == 0) {}  
    while (Serial.available() > 0)
    {
      guess = Serial.parseInt();     
    }
    Serial.println(guess);
    if (guess > value) //Greater than
    {
        Serial.println("Your guess is high.");
    }
    else if (guess < value) //less than
    {
        Serial.println("Your guess is low.");
    }
    else //equal to
    {
        Serial.print("You guessed correctly! The number was ");
        Serial.print(value);
        Serial.println(".");
        i = 0;
        win = true;
    }
  }
  if (win == false) //if you didn't win
  {
       Serial.print("You are out of guesses! The number was ");
       Serial.print(value);
       Serial.println(".");
  }
}


Once you've got the hang of the code, try changing the code and experimenting with it to understand it even further!

No comments:

Post a Comment