Arduino Language

The Arduino reference page contains valuable information and explains the individual Arduino functions in more detail. The Arduino language is based on C/C++. Arduino programs can be divided in three main parts: structure, values (variables and constants), and functions. the Arduino programming language is "case sensitive".

{ }

A block of code is defined with the { } tokens. { signifies the start of a block of code and } signifies the end.

Semicolons (;)

Each statement in C++ is ended by a semicolon. This is very roughly the equivalent of a sentence in a language like English. This tells the compiler where one operation ends and the next begins.

Comments

Comments are parts of the source code disregarded by the compiler. They simply do nothing. Comments allow you to make notes in the code itself.

//Comment out the rest of this line
 /*Comment
out a block of text
over many lines*/

Comments have several important uses:

  • Make notes to yourself
  • Make notes to others
  • Test removing bits of code without deleting them
  • Explain “magic numbers”

Here is an example of bad commenting:

memoryToInitialize = MemoryAvaliable(); // get amount of memory available
ZeroMemory(pointere, memoryToInitialize); // set mem to 0

Good commenting:

int boundary = 0; // upper index of sorted part of array
int insertPos = 0; // position to insert elmt in sorted part of array

Formatting

There is a reason why Bill Gates invented the Tab button. Hard to catch errors! Be consistent with your formatting. It makes reading and debugging your code much easier.

Here is an example of good formatting:

void loop()
{
    int num1,num2;
    double num3;
    string someString1 = “This is a string”;
    num1 = 5;
    num2+=num1;
}

Here is an example of bad formatting. Note how difficult it is to spot the error:

void loop() {
int num1,num2;double num3;
string someString1 = “This is a string”;
num1 = 5;num2; num2+=num1; }

Variables

Variables store data. There are several basic types that are commonly used.

Integer types: represents whole numbers

int numPeople;
numPeople = 4;
int value = -77;

Double and Float type: Represent floating point values (i.e. values with decimals)

double pi = 3.14159;
float factorOfSafety = 5.00;

Character type: Represent single character “values”. They are case sensitive.

char firstInitial = ‘a’;

Boolean type: Represent true/false conditions. Note that this is Arduino specific (C++ calls for "bool").

boolean isCorrect;
boolean isContinue = false ;

You can declare more than one variable at a time.

int numApples, numPears, numOranges;

Variable naming

It’s better to use descriptive names rather than ‘x’ or ‘v2’. You cannot use names that are already C++ keywords (double, else, true, for). The name has to start with a character.

Be careful when performing operations with multiple types:

int x = 5;
double y;
y = x/2;

Result? y = 2. Solutions if you want a double returned:

y = ((double ) x)/2;
y = x/2.0;

Procedures

There are two required functions in an Arduino sketch, setup() and loop().

setup(): function run once at the start of a program that can initialize settings

loop(): function called repeatedly until the board powers off. Use it to actively control the Arduino board.

void setup()

{
  // put your setup code here, to run once:
}

void loop()

{
  // put your main code here, to run repeatedly:
}

Includes

The hash sign (#) signifies the start of a preprocessor command. The include command is a specific preprocessor command that effectively copies and pastes the entire text of the file specified in the angled brackets into the source code. Includes make additional features/toolkits available. If you don’t include the right header, the compiler won’t understand the functions you are trying to use.

#include <servos.h>

Lets you use the servo features.

 #include <PololuQTRSensors.h>

Pololu offers headers with their reflectance sensors.

Define

You can use the #define directive to give a meaningful name to a constant in your program. This example illustrates the #define:

#define SOLENOID 5

Decisions

Most of these decision tools use Boolean expressions. These expressions test to see if the specified conditions are true or false.

Less than: <

Greater than: >

Equal to: ==

Not equal to: !=

Less than or equal to: <=

Greater than or equal to: >=

While

Execute the given code as long as the specified condition remains true.

var = 0;
while(var < 200){
  // do something repetitive 200 times
  var++;
}

Do

Very similar to a while loop. The check is just performed after each iteration.

do
{
  delay(50);          // wait for sensors to stabilize
  x = readSensors();  // check the sensors
} while (x < 100);

For

Most often used when you know exactly how many iterations you want to run.

Usage: for (start condition; end condition; increment)

// Dim an LED using a PWM pin
int PWMpin = 10; // LED in series with 470 ohm resistor on pin 10
void setup()
{
  // no setup needed
}
void loop()
{
   for (int i=0; i <= 255; i++){
      analogWrite(PWMpin, i);
      delay(10);
   } 
}

If

You also need a way to make decisions in code. If statements only execute code if the given conditions are found to be true. Note the different formatting. All are correct; some are easier to read and spot errors.

if (x > 120) digitalWrite(LEDpin, HIGH);
if (x > 120)
digitalWrite(LEDpin, HIGH);
if (x > 120){ digitalWrite(LEDpin, HIGH); }
if (x > 120){
digitalWrite(LEDpin1, HIGH);
}

Decisions can accommodate more than one if statement.

if (pinFiveInput < 500)
{
  digitalWrite(LEDpin1, HIGH);
}
else if (pinFiveInput > 500)
{
  digitalWrite(LEDpin2, HIGH);
}
else
{
  digitalWrite(LEDpin3, HIGH);
}

Several conditions can be tested in the same statement using and (&&)/ or (||) operators:

if (isClose==true && isSaved==true )
{
digitalWrite(LEDpin1, HIGH);
}
if (scoreA > 100 || scoreB > 100)
{
digitalWrite(SOLENOID, HIGH);
}

Serial Interface

Arduino libraries make it extremely easy to communicate with other controllers or computers. This interface displays serial data being sent from the Arduino board. This is also extremely helpful when debugging your code and you want to see what values sensors are reading.

Opens the serial monitor.

void setup()
{
    Serial.begin(9600); // Setup baud rate
}
void loop()
{
    Serial.println(”Give me input”); // output data
    while(Serial.availible() < 1)
    {    // if there's data waiting
        char input = Serial.read();    // get a byte of data

}

}

Good Programming

Each Arduino files should contain a quick read-me comment at the top:

Contact info

Requirements (software, hardware, etc)

Description of application

List of items termed as 'protected content‘ (music, 3D models, APIs and external pieces of code not written by author)

Library and Driver Dependencies Listing of libraries and versions

Here is a good example:

/**
 * @file: blinking LED example
 * @author: My Name (userid@mit.edu)
 * @date: 2/21/2011
 *
 * @description: blinks an LED every 1sec
 *
 * @hardware: 1 LED, resistor
 * @software: Processing
 * @libraries: no additional libraries
 * @protected content: modified from http://arduino.cc/en/Tutorial/Blink
**/
 

Code Management

Some simple guidelines to good programming:

  • Plan your code, write out a pseudo-code. Start out small and build the base code and go from there.
  • Compile and build your code often. Do not compile for the first time after writing over 300 lines of code.
  • Make your program modular, break your large system into small blocks which helps to make re-usability of block (component).
  • Avoid global variables if you can!

Links

Arduino Language

Arduino Notebook

CplusPlus.com