Arduino Programming

From RoboWiki
Jump to: navigation, search
Tutorial 3. Arduino Programming

Tutorial: Programming
Related Topics

Download this tutorial's presentation PDF

Programming the Arduino can be simple and easy, though requires time if you do not have a programming background. This tutorial walks you though the tools needed and the language used. For the purposes of this tutorial, we assume you have no background in programming, but for those that do, the official Arduino website has better material.

Source(s): Jasa seo



The Arduino IDE: 1. Tools Bar, 2. File Tabs, 3. Text Editor, 4. Compiler Message Box / Serial Prompt

The Arduino software is a suite for use with the arduino Microcontrollers, which we use on our smaller robots. The tool is an IDE, or Integrated Development Environment. It contains a text editor, a compiler, and a serial communication terminal.

  • Windows and OSX
    • The Arduino programming suite can be found here, along with instructions on how to install.
  • Linux
    • You will need to have Sun Java installed in order for Arduino to work in linux; otherwise, it will fail to load. A resource for installing on Ubuntu Linux, with fixes to many common problems, can be found here. The "arduino" package is in the Ubuntu Universe repository. Arduino is also in the aur repository in Arch Linux.

Source(s): Arduino Programming solutions

Using the Arduino IDE

The Arduino IDE tool bar. From right to left: "Verify", "Stop", "New", "Open", "Save", "Upload to Arduino", "Serial Monitor". (Click for a larger image)

The Arduino IDE is a simplistic text editor with compiler and communication abilities with any Arduino board. The top series of buttons (1) are your tool bar. They contain several commands such as verify code, stop compilation, new file, open a file, save current file, upload to the Arduino, and monitor serial communication.

The next row (2) are tabs of all current open files. Some projects require multiple source files; this tabbing feature lets you quickly change back and forth between files.

The large text box (3) is the actual source editor. This editor, like any other text editor, has the same functionality but with some added features. For example, keywords of the Arduino programming language (Such as "for", "while", "int", etc...) are highlighted.

The last black box (4) is the I/O serial communication box in which messages can be sent to and received from the Arduino.


Programming is the process of writing a series of instructions that eventually get turned into an executable format for the Arduino microcontroller.

The arduino is programmed in the Processing language, but is more similar to C/C++ then pure-processing. The language is procedural, which is similar to following a series of mathematical functions. Each function takes some data, manipulates it, and returns something. An example could be that a function called "Move(x)" would move the robot for the given time "X" forward.

The language can be split into three major topics: Variables (number that change over time in your application), Loops (Repetitions that are needed for calculations or events), and Functions (blocks of code that can be repeated multiple times with varying inputs and outputs).


Variables and Arrays

To begin learning the language, take a look at the basics of variables. Variables are defined as such:

type variable_name = initial_value;

So, declaring an integer would be

int MyAge = 20;

There are many types a variable may be. "int", or integers, are for whole values (such as 1, 2, 3, etc.), "float" or "double" are for floating-point values (1.0, 2.3, 9.999, etc.). "chars" are for single character values (such as 'a', 'A', '1', etc.).

Arrays are the same basic concept are variables, but in larger quantities and ordered linearly. An array can be defined as:

type variable_name[size] = initial_value;

Arrays, in this language, do not have built-in manipulators, so sorting and resizing must be done by hand. A sample use of an array could be:

int OurAges[3] = {20, 21, 18};

To access an element within an array you can use the "[]" operator. This operator only requires an index. Please note that all arrays in this language start their indexing at element 0.

int OurAges[3] = {20, 21, 18};
OurAges[0] = 19; // Change the first element (index 0, value 20) to 19.
int SecondAge = OurAges[1]; // Retrieve the second element (index 1, value 21) and place it into "SecondAge"

Much more can be learned about arrays, and the closely related construct called "pointers" in the Pointers article.

Source(s): Programming solutions

Looping and Iterations

Loops are sometimes needed to repeat instructions or to move through certain data structures (such as arrays). Two major types of loops exist, the "for" loop and the "while" loop.

The "while" loop allows a section, or block, of code to execute while a certain statement is true. The syntax of a while loop looks like:

   code to loop

As long as the expression placed in the parentheses after the 'while' keyword is true, the loop will execute.

A "for" loop is a special version of a while loop which allows for easy iteration through arrays or other data structures. The for loop contains a section to create an iterator variable and a section that executes at the end of each loop. This allows for constructions like the following:

int arr[5];
for(int i = 0; i < 5; i++)
   arr[i] = 2*i+1;

The sample above will fill arr with the first 5 odd numbers. The iterator variable 'i' is created in the initializer part of the loop and is initialized to 0. The second part of the loop is the test section. This section acts just like the expression in a while loop. The third and final section is the section that executes after each loop. In our example, this section adds one to i with the ++ operator.


To create a function, the prototype would be:

type function_name(type first_argument, type second_argument, ...)
   return //(variable same as function's type);

So, a function to add two integers and return the value would be

int Sum(int firstNum, int secondNum)
   return (firstNum + secondNum); //notice that this returns an integer, which is Sum's type.

Likewise, a function that did not return a variable would be declared as "void".

Basic Body

When using the arduino, there are two functions that are absolutely needed: a "void setup()", and a "void loop()". Setup is called only once at the beginning of the program, and is used to initialize variables and hardware needed for the main routine, "loop". Loop runs continuously until the power is cut, and is where you want to place your logic.

A very simple program that gives an example of this by setting up the arduino and making the its LED blink can be found here. Notice, specifically, these two lines:

//in the pre-processor, before setup: 
int ledPin =  13;    // LED connected to digital pin 13
//in setup:
 pinMode(ledPin, OUTPUT);

The first line declares a constant, "ledPin", which is the actual hardware pin (labeled on the arduino itself) that has the LED connected to it. For coding clarity, it is recommended that when declaring constants such as this, you instead use:

const int LED_PIN = 13;

This is due to the fact that a variable declared as const cannot be changed, and an all-caps variable is universally recognized as a constant. An alternative is using

#define LED_PIN 13

This line simply substitutes a literal "13" for every "LED_PIN" in the program when the program is compiled.

The second line shows an example of the coder setting up the pin using the pinmode() function, and using the constant to address the pin number - this is much clearer than if he had just used "13."

DigitalRead and DigitalWrite

DigitalRead and DigitalWrite are two functions used in writing and reading values to pins on the arduino. These two functions find use in interaction with your hardware.

Looking again at the basic tutorial from above, the programmer uses DigitalWrite to write a value of "HIGH" to the pin, sending voltage to it, and in turn lighting up the LED. Then, after "sleeping", or pausing, one second, he sends a value of "LOW" to the pin, sending little or no voltage to it, and turning off the LED.

Mouse Maze Solution

Solving for a linear maze can be fun and challenging! We define a linear maze as a maze that has several hallways and turns, but does not have multiple paths (e.g.: two rooms connected to a single hallway) as well as has no floating rooms (a room that does not connect to any other structure). Wikipedia has a good article on possible solutions for mazes, but we include below sample pseudocode to help you get started:

A sample solution to the Mouse Maze Competition. Note the green and red arrows, representing solutions for the two possible maze configuration.
  1. Set motor speeds forward
  2. Do side wall collision detection
    1. Adjust wheel speeds to move in parallel to wall
  3. Do forward collision detection
    1. If the robot is close to the wall, check the side sensors. Rotate 90 degrees to an open face
    2. Else, do nothing
  4. Goto step 1

Building Schedule

If you or your team are building for a specific robotics competition during a semester format, make sure you follow our Tabletop Design Schedule. Contact any club executive to learn more about differences in the schedule for your respective semester.

Personal tools