RobotGeek 101 : Coding Primer

This primer is an introduction for those who have never programmed before or need to brush up on basic programming concepts. The RobotGeek 101 lessons will show these concepts in-depth, but having a brief intorduction to them can make the lessons much easier.

Wiring / C++

There are many programming languages in the world, and many of them share the same programming concepts we'll go over in this primer. The Arduino Language (based on Wiring) is implemented in C/C++, so anyone with C or C++ experience should be right at home.

In the Arduino Language you will be writing lines of code. Each line tells the Geekduino to perform a certain task. Some tasks may result in turning lights on, reading input from buttons and knobs, or sending messages to displays. Some commands are simple mathamatical operations. Some commands literally tell the Geekduino to 'do nothing' for a period of time.

By carefully crafting these lines of code, you can do some incredible things.Whether you want to make your own flashlight or control a custom autonmous robot, you can make it happen with the Arduino Language.

Arduino Integrated Development Environment

The Arduino Integrated Development Environment (also known as the Arduino IDE) is a software tool that you will use to work with your Geekduino. The Arduino IDE wraps up multiple tools to help you program and manage your projects, compile /verify your code, and upload it to your Geekduino.

In the Arduino IDE, each project is called a Sketch. A Sketch contains all of the code that you want to upload to your Geekduino. Sketches can be easily shared and ported to other platforms.

The Arduino IDE will verify/compile your sketch by translating your code into a HEX file. This file can then be uploaded onto the Geekduino. Once you've uploaded the Sketch to the Geekduino, the Geekduino will run the Sketch until you reprogram the Geekduino. Even if you power down the Geekduino, it will start running the sketch again as soon as you power it on. Just remember that the Geekduino powers down, it will start the program from the beggining, and may lose data that it created while it was running.

The Geekduino can only run one sketch at a time. To run multiple sketches you would either need multiple Geekduinos, or to combine multiple sketches into one sketch.

You can also program your board in other environments such as Atmel Studio, MBlock and CodeBender to name a few. RG 101 will focus on using the Arduino IDE.

You will be programming your Geekduino/Arduino

Comments

Comments in code are a tool that you can use to document, explain and even organize your code. Comments are a special kind of programming contruct, because they have no effect on the code. If you remove all of the comments from a sketch, the code will behave exactly the same as the code with comments.

In Arduino, comments come in two types - single line comments and multi-line comments.

Single Line Comments

Any line that starts with // is considered a comment.

//this is a single line comment

Comments do not have to be on a line by themselves. If a comment starts after a line of code, the main code will still be executed

int delay = 1000; //this line sets the delay time for the LED to blink to '1000'

Remember, the comment has no bearing on how the code actually functions. The following line will function exactly the same as the previous line

int delay = 1000; //May had a little lamb

However this is a bad comment, as it doesn't add any useful information to the code. Good comments should make the code easier to understand.

Multi Line Comments

/* This is an example of a multi-line comment
   Multi Line comments are often used ...
   -at the begining of a sketch
   -before a function
   -before a complicated block of code
 */

Sometimes you will find multi line comments that are styled to look nicer

/********************************************************
 * This is an example of a styled multi-line comment.
 * As long as the comment starts and ends with the
 * correct characters there are no rules to comments
 *  
 *********************************************************/

Variables

You can think of a variable like a box that stores a piece of data.

Every variables has a type, a name and a piece of data. Here's an example of a line that created an Integer type variable named age

int age;

By defualt, an integer has a value of '0' so this variable now is set to '0'. If we wanted to start the variable off set to a different number, we would use the asignment operator = to set a value.

int hoursOfWork = 10;

Let's take a more in depth look at the properties of a variable.

Type

The Variable's type defines what kind of data it can hold. By defining different data types, we can hold different ranges of number.

  • int - Integer 
 Can hold -32768 to 32767
  • byte - Byte 
Can hold 0 to 255
  • bool - Boolean 
Can Hold 0 to 1
  • long - Long 
Can hold -2,147,483,648 to 2,147,483,647
  • float - Floating Point 
Used to numbers with decimals
  • char - Character
 hold single letters

Data types that can hold more data take more space in your Arduino's memory, so it's a good idea to use the smallest data type that supports your data. Just be careful - trying to put data that is to big into a variable can cause a variety of problems.

The following data types have the same meaning as data types we have already gone over (these keywords may imply different data sizes for other Non-Arduino platforms)
  • word - Same as unsigned int
  • short - Same as int
  • double - Same as float
  • word - Same as int

Name

There are some rules you need to follow when naming your variables. If you don't follow these rules your code will not work. Variable names can use:

  • Underscore (_)
  • Capital Letters(A-Z)
  • Underscore Letters(a-z)
  • Digits(0-9)

Some Additional Rules:

  • Variables cannot use characters not listed above (no spaces, commas, or other special symbols)
  • Variable Names need to start with an underscore or a letter (they cannot start with numbers)
  • Variables should not be the same name as reserved keywords or functions (these will show up as a differetn color in th IDE)

There are multiple conventions / guidelines for naming variables - these aren't rules and won't effect how the code runs, but they can make it much easier to read and debug your code.

  • Give variables meaningful names - if you have a variable that holds the postion value for a servo, servoValue is a much better variable than sv
  • Use capitalization or underscores to space out muliple words like servoValue or servo_value

Data

As we mentioned before, variables have a defult value that they are set to if you don't explicilty set your data. So this line

int hoursOfWork;

Will be the same as this line

int hoursOfWork = 0;

The first time a variable shows up in our code, we need to explicitly list the data type (in this case, int). But later in the code, we will only need to list the variable name. So if we wanted to intialize our variable to 28 when we first called it, we would use the code

int hoursOfWork = 28;

But later int he code if we wanted to change the data in the variable, we would only need the following code

hoursOfWork = 18;

Arithmetic Operators

Arithmetic operators are simple mathematical operations you can perform in the Arduino Language. You can take the results of the operations and store them in variables. Let's look at the basic arithmetic operations.

= Assignment

We've already seen the asignment operator in variables - the basic concept is that the Source data on the right is assigned to the destination variable on the right.

hoursOfWork = 10;

Now the variable hoursOfWork contains the value 10.

+ Addition

We can use other arithmetic operators on the left side of the assignment. For example we can use the + to add two numbers

hoursOfWork = 10 + 2;

Now the variable hoursOfWork contains the value 12. We can also add numbers to other variables.

extraHours = 2;
hoursOfWork = 10 + extraHours;
    

In this example the variable hoursOfWork contains the value 12. We can even refrence the destination variable in the source.

hoursOfWork = 10;
extraHours = 2;
hoursOfWork = hoursOfWork + extraHours;
    

In this case the variable hoursOfWork still contains the value 12.

- Subtraction

Just as you would expect the - operator lets you subtract 2 numbers

hoursOfWork = 10;
extraHours = 2;
hoursOfWork = hoursOfWork - extraHours;
    

In this case the variable hoursOfWork contains the value 8.

* Multiplication

The * operator lets you multiply 2 numbers

daysWorked = 5;
hoursPerDay = 8
hoursOfWork = daysWorked * hoursPerDay;
    

Now hoursOfWork contains the value 40.

/ Division

The / operator lets you divide 2 numbers

hoursOfWork = 40;
hoursPerDay = 8
daysWorked = hoursOfWork / hoursPerDay;
    

Now daysWorked contains the value 5.

% Modulo

The % operator gives you the remainder when dividing 2 integers.

hoursOfWork = 43;
hoursPerDay = 8
extraHours = hoursOfWork % hoursPerDay;
    

Now extraHours contains the value 3, the remainder of 43/8.

Functions

Think of a function as a sub-program within your code. Calling a function can insert code into your program modularly and easly. Functions can make code easier to deal with by allowing you to re-use code.

Some functions like digitalWrite and digitalRead are built into the Arduino core. Other functions are added via libraries. You can even easily add your own custom functions right into your Arduino sketch.

All functions have a name and areturn type . Functions may have zero, one, or more parameters

The functions name is a unique identifier so that it can be called.

A return type is the kinda of data a function will return. For example, analogRead has a return type of int because it returns an integer whenever it is called. If a function doens't return data (like digitalWrite) then the return type is void,meaning that the function does not return data.

A functions parameters are the data you send to the function when you call it. For example digitalWrite(13, HIGH); has 2 parameters - '13' is the pin number and 'HIGH' is the pin state. A function can have 0, 1, or more parameters.

Comparison Operators

If / Else

For Loops

While Loops

Switch

Variable Modifiers

By putting certain keywords in front of a variable type, the variable will be treated differently, giving you different results.

unsigned

Putting unsigned before an int or an long will make it so the variable can only hold positive values. The benfit of this is that you will have an increaded range of positive values you an work with. For example, an normal int can hold values from -32768 to 32767. But an unsigned int can hold values from 0 to 65535.

Similairly a long can hold values from -2,147,483,648 to 2,147,483,647, but an unsigned long can hold values from 0 to 4,294,967,295.

const

The const keyword is used to define a variable as read only. This might seem counter-intuitive at first (why would a variable not be able to change?)

There are times that you want to store data in a variable that you know will not change. For example, the number of a pin on the Geekduino - this number will not change once the sketch has begun running. Putting the pin number in a variable can make your code cleaner and easier to update or edit. But normal variables fill up the Arduino's RAM. By using the const keyword, the variable is stored in Flash memory, saving space in RAM for other variables that need it.

static

To understand static, you need to learn about variable scope. Normally, if you create a variable in a function, the variable get re-created every time the function is called. But sometimes you want the variable to stay the same over multiple calls.

At it's core, static is a tool for causing a variable in a called function to remain over mutliple calls of the function. Often time Arduino Sketches will use global variables - that is, all functions have access to the variables.

Hackaday has a great article on the staticcode> keyword.

volatile

Volatile is a keyword used orimarly for variables that interact with interrupts. Again, Hackaday had a awesome article on the volatile keyword.

PROGMEM

PROGMEM isn't really a keyword, but it can work like one. the 'const' keyword stores data in Flash because the Arduino's compiler is smart enough to decide to do so. The PROGMEM keyword however forces the data to go into flash, so there's no possible ambiguity. the 'const' keyword works well for individual variables but it's not so great with arrays and strings - there's where PROGMEM steps in.

PROGMEM Reference on Arduino.cc

Further Reading and Informaiton

Feedback Form


Search