Tumblelog by Soup.io
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

September 30 2009

Meeting Announcement – 10/6/2009

Make:KC – Show & Tell

Technology for the fun of it.
Makers in Missouri and Kansas

When: Tuesday October 6, 2009

6:00 to 8:00 pm.

Where: HMS Beagle Science Store
180 English Landing Drive
Parkville, MO 64152


It’s Time To Make Some Noise!

This month our Show and Tell will set aside a portion of our time to introduce Circuit Bending. This is a great way for kids of all ages to get their hands into electronics for safe and inexpensive fun.

Our circuit bending session is kicking off a new activity to challenge others to build their own version of the themed activity. We will follow up at the next month’s Show and Tell session to see your creations. We hope to introduce a monthly or at least a quarterly challenge around various topics.

As usual we’re encouraging people to bring other projects in for the Show and Tell. Hope to see you there.

Meet us at October Skies – Rocket Science Day

Also, we are planning a booth at the HMS Beagle’s 4th Annual “October Skies” Rocket Science Day on October 3. If you’ve missed our Show and Tell sessions because of schedule conflicts, come out and get to know what we’re about.

Check us out on Google Groups at


September 25 2009

Robotic Amber Alert

Michael Overstreet is a robotics hobbyist in Kansas City. His humanoid  robot was stolen over the weekend. Last Sunday (Sept 20, 2009) his car was broken into and his robot along with his laptop was stolen.

Over the last year Mike has been active with the CCCKC group. More details are listed on their web site.


Please keep an eye out for his robot showing up at pawn shops and such. Here is a recent video of his robot in action.


September 24 2009

Hello Robot Brighton

Thanks for the mention from the UK’s @robotbrighton robotics group. Recently I read @fluffyemily’s RoboChick Rampant Robotic Rumpus blog post about the book “Making Things Talk“. This is a great book and it influenced my decision to explore the combination of Processing and Arduino through this web site.  The urge to purchase books is great and it’s easy to spend a small fortune on computer books. Another book worth adding to your bookshelf  is “Programming Interactivity“, I’m still forming my opinion on this book but in general I think it is useful.

I checked to see what was showing up on my site’s home page at the time of RobotBrighton’s mention and realized that a little explanation would be helpful. Most of the articles may be considered a Stream of Consciousness and when reading top-down consecutively the articles appear out of proper order and somewhat disconnected. I’m basing this site’s articles on a series of workshops I’m developing titled “Topics in Robotics, Electronics, and Communications”.

I started DIY Robotics Lab as a way to encourage people interested in this technology to begin exploring what they can do at home. So many of the robot kits used by high school students are too expensive for home use.

Presently much of this site is about programming using Arduino and Processing. I believe there are enough similarities when learning to program in one it will help you learn the other. Processing can provide an enjoyable way of interacting with our robotic creations. One series of articles begins with this Processing – Arduino Comparison article.

Another series is an example of low cost robotics projects spanning multiple web sites. Here is an article about our Robotic Labyrinth using a Wii Fit balance board. I saw this as a great way to get kids interested in robotics. An article on this site illustrates using Processing to interact with a simulated joystick. Since publishing that article I’ve added xBox 360 controller support through Processing to control the labyrinth. Another member of our labyrinth project has posted an article showing our labyrinth in action at the Missouri state fair. He also publish this article “Using a PC Joystick with the Arduino“. Since older game port joysticks can be bought at thrift stores for around $3 its another cheap way to encourage home based robotics labs. You can find more information about our labyrinth project at my personal blog SomeoneKnows.

Another series of articles on this site starts with Learning the C Language with Arduino. It explores using C while building circuits to blink LEDs.

I hope you enjoy the site and find the information useful. I would like to learn about your thoughts and comments. Thanks for stopping by.

(c) 2009 – Vince Thompson

September 21 2009

Some Pointers For Memory Allocation

This may be an article you’ll want to file away with a “Do Not Try This At Home” warning as we take a look into allocating memory and using Pointers from the C language. The Java and therefore Processing languages do not use pointers and you may actually find claims that pointers are error prone. It’s not that pointers are inherently problematic but programmers get careless in their use and create hard to find bugs in their programs. Since Arduino is based on the C language we have many of the C features to play with.

The Array Declarations – Processing vs Arduino article left off with a pointer declaration for ptrArray.  This article picks up from there by allocating a pointer to an array of integers.

Create a new Arduino sketch named Malloc:

#include < ctype.h >

int *ptrArray;
char *cmdString = {"Type - a, b, c or d to blink led"};
char *strFormat = {"command %c blinks %d times\n"};
char strMessage[40];
int delayTime;

void setup()
  ptrArray = (int *)malloc(sizeof(int)* 3);
  ptrArray[0] = 2;
  ptrArray[1] = 4;
  ptrArray[2] = 6;
  realloc(ptrArray,(sizeof(int)* 4));
  ptrArray[3] = 8;
  delayTime = 200;

void loop()
    int arrayPos;
    char command = tolower(Serial.read());
    arrayPos = command - 'a';

    switch(command) {
      case 'a':
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
      case 'b':
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
      case 'c':
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
      case 'd':
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);

void blinkLED(int nTimes)

  for (int i=0; i<nTimes; i++)
    digitalWrite(13, HIGH);
    digitalWrite(13, LOW);
  digitalWrite(13, LOW);

The pointer is declared on line 03, by placing the asterisk at the front of the variable name as in: *ptrArray

Line 03. int *ptrArray;
Line 12. ptrArray = (int *)malloc(sizeof(int)* 3);
Line 16. realloc(ptrArray,(sizeof(int)* 4));

Line 12 causes the program to allocate a block of memory where the integer array will reside using the malloc function. Because we’re creating an integer array we need to assist the malloc function by telling it the size of the data type by using the sizeof(int) function. Then multiply by by the array positions wanted, in this case 3, for the total number of bytes to allocate.

Line 16 serves no real purpose in this program other than to illustrate that variables can be dynamically reallocated using the realloc function. In this statement we provide the pointer to the array being resized, ptrArray, then the size of consecutive memory to allocate. In this case we are changing the size of the integer array from 3 to 4 integer positions.

Line 13. ptrArray[0] = 2;
Line 14. ptrArray[1] = 4;
Line 15. ptrArray[2] = 6;
Line 17. ptrArray[3] = 8;

Lines 13, 14, 15, and 17 simply assign an integer value into each of the array positions. The rest of the program uses the data values to determine how many times to blink the LED on pin 13 when you type in an a, b, c, or d character.

Line 01. #include <ctype.h> Line 27. char command = tolower(Serial.read()); Line 28. arrayPos = command - 'a';
Line 27 introduces tolower(), one of the standard C functions for string manipulation. This function guarantees upper case or lower case characters are always returned as lower case. To use this function requires including the ctype.h header file as shown on Line 01. Line 28 does a little arithmetic that takes an ASCII character representation passed through the serial connection and subtracts 97, the ASCII representation for ‘a’. The Arduino reference page links to an ASCII chart.
Line 33.sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);

Line 33 is making use of the C language sprintf() function. Arduino hides many of the C language functions to simplify the language more user friendly. Additional references from “The C Programming Language book“.

(c) 2009 – Vince Thompson

September 15 2009

Array Declarations – Processing vs Arduino

When I need a 20 second description of the Processing versus Arduino Languages I’ve said that Arduino is a subset of Processing. That analogy helps to quickly convey the idea that both languages have many similarities while indicating a difference in features. That analogy however is not accurate. Like both Processing and Arduino the Java language has deep roots in the C programming language. Unlike Arduino, Processing is built on top of Java with features that simplify its use for people not wanting to dive into a computer science degree. With these languages you can understand how to perform certain programming techniques quickly. To a great extent though, by combing Arduino and Processing when you learn to program in one you learn how to program in the other. Allocating and initializing arrays, however, is one place where the differences in these programming languages shows up.

Defining Arrays

When writing programs you work with data and use variables as a way to store that data. Arrays provide an essential way to define a single variable capable of holding a sequence of similar data. By using arrays you give the computer an easy way to navigate through each of the pieces of data programmatically.

I received the following question about array initialization:

It is my understanding that…
int[] array = new int[3];
array[0] = 1;
array[1] = 2;
array[3] = 3;
int[] array = {1, 2, 3};
…have the same effect. I am simply curious as to why the second example does not require the new function (also, would new be considered a function?).

Array References:

Processing Keywords

First a word about the Processing language’s keywords. When I pasted the supplied source code into Processing and pushed Run, the code ran without complaining about using “array” as the variable name. Using keywords as variable names can cause problems and should be avoided. One way to identify keywords is by the color coding in the editor. The word “array” is shown using the same color as other keywords “int” and “new”.

Invalid variable name.

Processing keyword used as variable name.

Array Declarations In Processing

In the following screen shot I’ve used the variable names “myArray”, “anotherArray”, and “vintageArray”. These variable names show up as black text in the editor.

Valid Processing Array Declarations

Valid Processing Array Declarations

int[] myArray = new int[3];
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;

int[] anotherArray = {1, 2, 3};

int vintageArray[];

To understand the methods of allocating a variable array it helps to know that Java is an object oriented language. Furthermore, all variable types in Java are objects. The first declaration:

line 01. int[] myArray = new int[3];

Using the keyword new is consistent with many object oriented languages as the way to allocate an instance of an object class. The new keyword is not a function, it is an operator. This feature in Processing is a result of using the Java language. The following breakdown shows how this statement is evaluated:

  • int[] identifies the variable type will be an integer array.
  • myArray is the variable name.
  • new is the operator used to allocate a new object type.
  • int[3] identifies the object class and the number of array positions.

Two things happen in the example code’s variable array declarations.

  • Allocate
  • Initialize

This statement on line 01 only allocated positions in your program’s memory to hold the data values, it does not initializing the data.

The array declaration on line 06 combines allocation and initialization of each array position value.

line 06. int[] anotherArray = {1, 2, 3};

This is a shortcut in the way this object is being declared. The Java back-end understands the shortcut and doesn’t require the new keyword.

The Processing language reference doesn’t describe the method on line 08 as shown when declaring the vintageArray variable.

line 08. int vintageArray[];

This method is available from Processing and Java’s heritage in the C language.

Array Declarations With Arduino

int myArray[3];
int initializedArray[] = {1,2,3,4,5};
int partialArray[10] = {1,2,3};
int *ptrArray;

void setup()

void loop()

Arduino differs from Processing by using the C language definitions for arrays.  From the array declarations with Arduino source code:

Line 01. int myArray[3];

The major change is where the square brackets “[" and "]” are placed. In the C language they are found just after the variable name as in Array[3] above.

Line 02. int initializedArray[] = {1,2,3,4,5};

This line allocates the variable initializedArray to allow up to five array positions. It then initializes the values with the numbers 1 through 5 in consecutive array positions.

Line 03.  int partialArray[10] = {1,2,3};

This line allocates the variable partialArray to allow up to ten array positions. It then initializes the first three values with the numbers 1, 2, and 3 in consecutive array positions.

Line 04.  int *ptrArray;

The statement on line 04 is a valid C language allocation of a pointer named ptrArray. The use of pointers is a topic for another article.

(c) 2009 – Vince Thompson

September 13 2009

Incrementing Variables Using ++

I received an email from Brendan, one of our 16 year old members attending the Make:KC meetings. He is looking into using the Processing language. One of his questions was about how variables are incremented using the ++ syntax.

  • The ++ syntax is for incrementing values – counting up by one each time.
  • The — syntax is for decrementing values – counting down by one each time.


A word about debugging

One thing I miss in the Processing and Arduino development environment is a way to step through a program line by line to debug a program as it’s running. Since we don’t have that feature the next best thing is by using print statements. The following programs are written to hopefully show you what is happening in the program as it is running.

Here is a short Processing program to illustrate incrementing:

Incrementing Variables in Processing

void setup()
 int a;
 int b;

 print("Initialize value: a = ");

 print("example 1: ++a is equal ");
 println("  this example increments 'a' by 1 before evaluating (using) the variable");
 println("  in the print statement\n");

 print("Reinitialize: a = ");

 print("example 2: a++ is equal ");
 println("  this example increments 'a' after printing its value");
 println("  The ++ incrementor only increases the value by 1 each time\n");

 print("Reinitialize: a = ");
 println("example 3: a += 1");
 print("  a equals ");
 println(a += 1);
 println("  This is another example of incrementing the variable by 1");
 println("  a += 1 is a simplified way of writing  a = a + 1\n");

 print("Reinitialize: a = ");
 print(" and b = ");
 println("example 4: a += b");
 print("  a equals ");
 println(a += b);
 println("  The += operator lets you change the incrementing value");
 println("  a += b is a simplified way of writing  a = a + b\n");


void draw()

When you look at Processing’s output view when you run the program you’ll see:

Initialize value: a = 0
example 1: ++a is equal 1
this example increments ‘a’ by 1 before evaluating (using) the variable in the print statement

Reinitialize: a = 0
example 2: a++ is equal 0
this example increments ‘a’ after printing its value
The ++ incrementor only increases the value by 1 each time

Reinitialize: a = 0
example 3: a += 1
a equals 1
This is another example of incrementing the variable by 1
a += 1 is a simplified way of writing  a = a + 1

Reinitialize: a = 0 and b = 5
example 4: a += b
a equals 5
The += operator lets you change the incrementing value
a += b is a simplified way of writing  a = a + b

To illustrate the similarities of programming in Processing and programming for an Arduino, consider this program.

Incrementing Variables in Arduino

void setup()
int a;
int b;


Serial.print("Initialize value: a = ");

Serial.print("example 1: ++a == ");
Serial.println("  this example increments 'a' by 1 before evaluating (using) the variable");
Serial.println("  in the print statement\n");

Serial.print("Reinitialize: a = ");

Serial.print("example 2: a++ == ");
Serial.println("  this example increments 'a' after printing its value");
Serial.println("  The ++ incrementor only increases the value by 1 each time\n");

Serial.print("Reinitialize: a = ");
Serial.println("example 3: a += 1");
Serial.print("  a equals ");
Serial.println(a += 1);
Serial.println("  This is another example of incrementing the variable by 1\n");

Serial.print("Reinitialize: a = ");
Serial.print(" and b = ");
Serial.println("example 4: a += b");
Serial.print("  a equals ");
Serial.println(a += b);
Serial.println("  The += operator lets you change the incrementing value\n");

void loop()

The only difference with an Arduino program is in order to display messages on your computer screen you need to send them through a serial connection using the “Serial.” prefix on the “print” statement. The variables get incremented the same way whether using Processing or Arduino.

July 17 2009

Making The Connection – Serially

Locating a Processing example program to communicate with an Arduino is not too hard to find. But making the serial connection work can be troublesome. Since Processing is supported across different operating systems your connection can work fine in Linux, for instance, but switch to Windows and it quits working. If you want to share your program with others the problem becomes even worse. The problem is usually a result of having the wrong serial port selected.

Editing your program each time you switch between operating systems or plug the Arduino into a different port is troublesome. When sharing the program with others it is not a good idea to expect them to edit the source code to get it working on their computers. What we need is a way to interactively select the serial port while the program is running.

Serial Connection Selection List

Serial Connection Selection List

Processing is a relatively easy language to learn with tutorials and a reference section on the processing.org web site. The Libraries reference includes information about the Serial library. The reference section has limited information on user input with Mouse events and Keyboard actions. Looking for common Graphical User Interface (GUI) features like text boxs, drop down lists, radio buttons are absent. That doesn’t mean these GUI features aren’t availaible.

Processing is built upon the Java Language. With very little effort many of the Java features can be used.  To add a drop down list you simply need to know what to ask for. The Java Choice component provides the desired feature. You don’t have to import any libraries because Processing is already aware of these Java components. To find more information about the Choice Class you need to look at Java’s documentation.

Choice guiChoice = new Choice(); //Choice component for GUI selections.

import processing.serial.*;  //Include the Processing Serial Library in this program

Serial port;  //Declare the variable 'port' as a member of the Serial class.

void setup()
int nKtr;
Choice guiChoice = new Choice();  //Choice component for GUI selections.

nKtr = Serial.list().length; //Find out how many serial connections are recognized

println("Serial length = " + Serial.list().length);

for (int i=0; i< nKtr; i++)
guiChoice.addItem(Serial.list()[i]);  //Add each serial port found to the selection

add(guiChoice); //Place the Choice selection box on the display area.

println("selected index = " + guiChoice.getSelectedIndex());

void draw()

This source code simply sets up a drop down list in a Processing display showing the available serial ports. The Choice list does not select the serial connection yet.

(c) 2009 – Vince Thompson

June 18 2009

Processing – Arduino IDE Comparison

What the Arduino programming environment does for microcontrollers the Processing programming environment does for your computer. The Integrated Development Environments (IDE) for Processing and Arduino are nearly identical. Better yet, learning to program with one gives you enough experience to begin programming with the other.

Processing - Arduino IDE

Processing - Arduino IDE

This side by side comparison shows similarities between the Processing IDE on the left and Arduino IDE on the right. This is no accident because Arduino’s programming tools are actually a subset of the Processing language.

Both programs use a startup() function to perform initialization procedures. The first difference is with the draw() function in Processing and loop() function in Arduino. Processing’s draw() function acts much like the Arduino loop() but continually updates the graphics displayed on the computer screen and responds to user interaction.

Joystick Simulation with Processing

If you’re building a control system for a robot, a new game or even controls in your house you probably need a way to interact with your program. The joystick is a common user input device to work with, however, the variety of types and device drivers can raise a few issues when working with multiple operating system.

In order to introduce joystick interaction for the Windows, Linux, and Mac operating systems we need a cross platform programming environment. The Processing Language gives us a way to simulate the joystick for each computing system.

After working with the Arduino and its programming environment, creating a program with the Processing Language has a familar look and feel.

Create a new Sketch in Processing called: JoystickSimulation

import processing.opengl.*;

 Program: Joystick

 This program simulates using a joystick by using a mouse and
 the graphics features of Processing.

 Author: Vince Thompson


int displayWidth = 640;
int displayHeight = 480;
int joyOutputRange = 90;  //Maximum value for full horiz or vert position where centered is 0.
int textHorizPos, textVertPos;  //Display positions for text feedback values.
int fontSpace = 12;

float curJoyDisplayWidth;
float curJoyDisplayHeight;

float maxJoyRange=200;     //Maximum joystick range
float curJoyAngle;     //Current joystick angle
float curJoyRange;     //Current joystick range
float joyDisplayCenterX;  //Joystick displayed Center X
float joyDisplayCenterY;  //Joystick displayed Center Y

float surfDisplayCenterX;
float surfDisplayCenterY;

float rSize;

boolean isMouseTracking=false;
color color1;
color color2;

void setup() {
   PFont font;
   size(displayWidth, displayHeight, OPENGL);
   joyDisplayCenterX = displayWidth/2;
   joyDisplayCenterY = 25 + maxJoyRange/2;
   curJoyDisplayWidth = maxJoyRange * .85;
   curJoyDisplayHeight = curJoyDisplayWidth;
   maxJoyRange = curJoyDisplayWidth / 2;

   surfDisplayCenterY=displayHeight* .65;

   stroke(0, 100);
   color1=color(0);  //Color = Black

   rSize = displayWidth/2;

   font = loadFont("Monospaced.bold-12.vlw");

void draw() 

   float joyHorizontalText, joyVerticalText;


   float dx = mouseX - joyDisplayCenterX;
   float dy = mouseY - joyDisplayCenterY;

   if(mousePressed && (mouseButton == LEFT))
      isMouseTracking = true;

   if(mousePressed && (mouseButton == RIGHT))
      isMouseTracking = false;

   if (isMouseTracking)
      curJoyAngle = atan2(dy, dx);
      curJoyRange = dist(mouseX, mouseY, joyDisplayCenterX, joyDisplayCenterY);
      curJoyRange = 0;

   ellipse(joyDisplayCenterX, joyDisplayCenterY, curJoyDisplayHeight, curJoyDisplayWidth);

   segment(joyDisplayCenterX, joyDisplayCenterY, curJoyAngle);
   ellipse(joyDisplayCenterX, joyDisplayCenterY, 20, 20);

   textHorizPos = 50;
   textVertPos = (int)(joyDisplayCenterY - 50);
   text("Horiz:", textHorizPos, textVertPos);
   textHorizPos += (4*fontSpace);
   joyHorizontalText = (joyOutputRange*(cos(curJoyAngle) * curJoyRange)/ maxJoyRange);
   text(nf(joyHorizontalText, 2, 1), textHorizPos, textVertPos);

   textHorizPos = 50;
   textVertPos += 12;  

   text("Vert:", textHorizPos, textVertPos);
   textHorizPos += (4*fontSpace);
   joyVerticalText = (joyOutputRange*(-(sin(curJoyAngle) * curJoyRange)/maxJoyRange));
    text(nf(joyVerticalText, 2, 1), textHorizPos, textVertPos);

    labySurface(joyHorizontalText, joyVerticalText);

void segment(float x, float y, float a)
   translate(x, y);
   if (curJoyRange > maxJoyRange)
      curJoyRange = maxJoyRange;

   line(0, 0, curJoyRange, 0);

void labySurface(float angleHoriz, float angleVert)
   float radHoriz;
   float radVert;

   radHoriz = radians(angleHoriz) * .15;
   radVert = radians(angleVert-60) * .15;
   translate(surfDisplayCenterX, surfDisplayCenterY, 0);
   rotateX(HALF_PI+ (radians(-60) * .15));
   box(rSize+5, rSize+5, 1);
   translate(surfDisplayCenterX, surfDisplayCenterY, 0);
   box(rSize, rSize, 8);

June 09 2009

Blinking Binary Bits and Bytes…

Looking At The Numbers.

Learning to make an LED flash is a great way to begin programming your Arduino, so take what you’ve learned with the LEDBlink program and add more LEDs. How many should we add, 3, 4, 7, 15 or more? Is there a special number of LEDs to choose? The Arduino Duemilanove has a total of 14 Digital pins and 6 Analog pins that we could use for a maximum of 20 individually controlled pins.

Lets take a look at how computers understand numbers, incidentally microcontrollers like those used by your Arduino understand numbers the same way. Arduino uses the Atmel Corporation’s 8-Bit family of microcontroller devices. Atmel manufactures a series of 8 or 16 bit devices. Most modern personal computers use either 32 or 64 bit hardware. This is beginning to suggest that a multiple of eight is important.

Maybe you’ve heard someone say that computers work with binary numbers which are a bunch of ones and zeros. Individually the “1″ or “0″ values are stored in binary digits that are called bits. The word bits is actually a contraction of the two words “binary” and “digits“. Our computers and microcontrollers both work with these ones and zeros in multiples of eight. Collectively these eight binary digits are known as a byte, so there are generally 8 bits per byte.

Bytes Are Important.

A Byte represents the smallest segment of memory containing data that an Arduino will read or write. A byte of data can save a positive whole number with a value ranging from 0 to 255. Lets create a program to show how a computer can count using binary numbers. Each LED will represent a single byte in an 8-Bit number.

Wiring the Breadboard

The breadboard gets wired up like the example from the “Learning the C Language with Arduino” article. This example adds more LEDs for a total of eight. The LEDs are attached to Digital pins 3 through 10. A total of eight LEDs and eight resistors are needed for this project.

Why are we starting with Digital Pin3? First, we are using the digital pins because they work like switches, either turning on (HIGH) or off (LOW). There is no significance to starting with pin 3 when any of the other digital pins would work just as well. Pins 0 and 1 carry a dual role. They act like other digital pins but also may handle serial communication’s TX and RX (transmit and receive) features.

Breadboard Layout 8 LEDs

Breadboard Layout 8 LEDs

Create a new program named:binaryCount

Type in the following code, typing the comments (shown in green) are optional. You could copy and paste into the program editor but typing your own code helps you learn the programming language too.

/*--- Binary Counting with 8 bits ---*/
//Associate LEDs with an Arduino Digital pin.

int led0Pin = 3;
int led1Pin = 4;
int led2Pin = 5;
int led3Pin = 6;
int led4Pin = 7;
int led5Pin = 8;
int led6Pin = 9;
int led7Pin = 10;

void setup()
   //Set up each of the pins for output only.
   pinMode(led0Pin, OUTPUT);
   pinMode(led1Pin, OUTPUT);
   pinMode(led2Pin, OUTPUT);
   pinMode(led3Pin, OUTPUT);
   pinMode(led4Pin, OUTPUT);
   pinMode(led5Pin, OUTPUT);
   pinMode(led6Pin, OUTPUT);
   pinMode(led7Pin, OUTPUT);

void loop()
   byte iVal; //we'll define this variable for use in the program.
   //A byte is an 8 bit variable.
   // begin counting up from 0 to 255

   for(iVal=0; iVal<255; iVal++) // loop through each of the values
   { // Light up LED if its corresponding byte is equal to binary va1ue.
      digitalWrite(led0Pin, (iVal &        B1)); // -------X Decimal value 1
      digitalWrite(led1Pin, (iVal &       B10)); // ------X- Decimal value 2
      digitalWrite(led2Pin, (iVal &      B100)); // -----X-- Decimal value 4
      digitalWrite(led3Pin, (iVal &     B1000)); // ----X--- Decimal value 8
      digitalWrite(led4Pin, (iVal &    B10000)); // ---X---- Decimal value 16
      digitalWrite(led5Pin, (iVal &   B100000)); // --X----- Decimal value 32
      digitalWrite(led6Pin, (iVal &  B1000000)); // -X------ Decimal value 64
      digitalWrite(led7Pin, (iVal & B10000000)); // X------- Decimal value 128

   digitalWrite(led0Pin, (iVal & B1));

Source Code Analysis

Line 4

Why is the first variable, led0Pin named with 0 instead of 1?

The short answer is the C Language starts counting beginning with the number 0. In the led0Pin through led7Pin variables the numeric character is irrelevant except to differentiate between the names. A later article will describe using variable arrays where this becomes important. This way of naming variables was done for some consistency with future examples.

Line 32

The ” for” statement is part of the C language’s control structures.

for(iVal=0; iVal<255; iVal++) // loop through each of the values

There are three parts to the for control loop:

  • Initialization – “iVal=0;” This assigns the value of 0 to the iVal variable. You need to end this portion with a semicolon.
  • Condition – “iVal<255;” This checks if the variable iVal is less than 255. While this condition is true the loop continues again. You need to end this portion with a semicolon.
  • Increment – “iVal++”  After processing the statements within the for loop the variable iVal is incremented by one. This portion does not use a semicolon.

In the iVal++ increment portion the plus plus characters “++“, this is the same as assigning iVal = iVal + 1 or adding one to the iVal variable each time the for loop finished.

Since the for() statement is part of the control structure you don’t put a semicolon at the end of this statement.

Lines 34 through 41

digitalWrite(led0Pin, (iVal &        B1)); // ——-X Decimal value 1

LED Bit Values

LED Bit Values

Bit values

As described above, we are using LEDs to represent each of the eight bits in a one byte value. Each bit signifies a value for that column. If all of the LEDs are off then the number it represents is zero (0). If only the right-most LED in the column labeled “1″ is lit up then the byte of data is equal to the number 1. If the left-most column labeled “128″ is the only one lit up then the byte of data is equal to the number 128. If all LEDs are lit up then the byte of data is equal to the number 255.

128 + 64 + 32 + 16 + 8 + 4 + 2 + `1 = 255

Any combinations of the eight LEDs that are turned ON or OFF represent a number from 0 to 255. Similarly, we can create a binary representation of the number by using a Bit Formatter. This is a value using the upper case letter B with a combination of only ones (1) and zeros (0) as shown below.

  • – - – - – - – X Decimal value 1  Bit Format:    B1
  • – - – - – - X – Decimal value 2  Bit Format:    B10
  • – - – - – X – - Decimal value 4  Bit Format:    B100
  • – - – - X – - – Decimal value 8  Bit Format:    B1000
  • – - – X – - – - Decimal value 16  Bit Format:  B10000
  • – - X – - – - – Decimal value 32  Bit Format:   B100000
  • -X – - – - – -  Decimal value 64  Bit Format:    B1000000
  • X – - – - – - – Decimal value 128  Bit Format: B10000000

The Bitwise AND “&” Operator

(iVal & B1)

If we have a the variable iVal which contains a value ranging from 0 to 255, how can we use that value to turn the pattern of LEDs on or off that the number represents? Because we’re only checking the iVal value against a single bit each time, the statement (iVal & B1) returns a TRUE (1) or FALSE (0) answer. The ampersand is a bitwise AND operator. In the example if the right most bit in the variable iVal is 1 AND the right most bit as specified by B1 are both 1, then the bitwise AND is 1 if they both aren’t set to 1 then the bitwise AND is evaluated as 0.

June 06 2009

Creating a New Arduino Sketch (Program)

How do I create a new Arduino Program?

Arduino’s programs are called Sketches, so how do I create one?

Select the Arduino menu item File -> New

Arduino File New

Arduino File New

You could start entering code right after creating the new sketch but if you are planning to save it anyway why not give it a name now?

Select the menu item File -> Save As… to give your new program a name and directory location.

Setting your Preferences

You can customize your Arduino development environment so anytime you create a new program it will automatically prompt for a program name.

From the Arduino menu select File -> Preferences

Arduino Preferences Dialog

Arduino Preferences Dialog

Select the “Prompt for name when opening or creating a sketch” checkbox. You can also change the default location to save your sketches.

June 05 2009

Correcting Arduino Compiler Errors

(Intended) Errors and Omissions

What happens after you select the Arduino menu item Sketch -> Verify/Compile and you get error messages that your program failed to compile properly. Sometimes the compiler warnings help you spot the problem code. Other times the error messages don’t make much sense at all. One way to understand the error messages is to create some intentional errors and see what happens.

Create a new program named: LEDBlink_errors

This is one time when it is better to copy the following code so we don’t introduce more errors into the program than are already there.

/*--- Blink an LED  ---//
//Associate LEDs with an Arduino Digital pin.
//The Arduino already has a built-in LED that we can use on Digital Pin 13.
int ledPin = 23;  \\We're using Digital Pin 23 on the Arduino.

void setup();
   pinMode(ledPin OUTPUT);   //Set up Arduino pin for output only.

   /The HIGH and LOW values set voltage to 5 volts when HIGH and 0 volts LOW.
   digitalWrite(ledPin, high); //Setting a digital pin HIGH turns on the LED.
   delay(1000):  //Get the microcontroller to wait for one second.
   digitalWrite(ledPin. LOW);  //Setting the pin to LOW turns the LED off.
   Delay(1000);  //Wait another second with the LED turned off.

If you run Verify/Compile command you should see a number of compiler error messages at the bottom of the dialog display.

Arduino Compiler Error Messages

Arduino Compiler Error Messages

Line 1 Error

Uncaught exception type:class java.lang.RuntimeException

java.lang.RuntimeException: Missing the */ from the end of a /* comment */

at processing.app.Sketch.scrubComments(Sketch.java:2008) …

/*— Blink an LED  —//

The error messages go on for several more lines without adding much information to help solve the problem. You will find a clue to the problem above the compiler message box stating:

Missing the */ from the end of a /* comment */“.

The article “Introduction to Programming the Arduino” describes the comment styles used by C programs. The error on line 1 is caused by mixing the comment styles. The comment begins with the “/*” characters but ends with “//” instead of the “*/” characters. Correct the line as follows:

/*— Blink an LED  —*/

Now, rerun the Verify/Compile command.

Line 4 Error

error: stray ‘\’ in program

int ledPin = 23; \\We’re using Digital Pin 23 on the Arduino.

This is another problem with incorrect commenting technique. In this line the “\\” characters are used to begin a comment instead of the “//” characters. The correct line follows:

int ledPin = 3;  //We’re using Digital Pin 3 on the Arduino.

Now, rerun the Verify/Compile command.

Line 6 Error

error: expected unqualified-id before ‘{’ token

void setup();

This is an easy mistake to make. The problem is the semicolon “;” at the end of a function declaration. The article “Learning the C Language with Arduino” contains a section about correct usage of semicolons. To correct this problem remove the semicolon as shown below:

void setup()

Now, rerun the Verify/Compile command.

Line 8 Error

In function ‘void setup()’:

error: expected `)’ before numeric constant/home/myDirectory/Desktop/myPrograms/arduino-0015/hardware/cores/arduino/wiring.h:102:

error: too few arguments to function ‘void pinMode(uint8_t, uint8_t)’ At global scope:

pinMode(ledPin OUTPUT); //Set up Arduino pin for output only.

The clue to this problem is found in the message error: too few arguments to function ‘void pinMode(uint8_t, uint8_t)’“. The message includes a list of the function’s arguments and data types (uint8_t). The error is complaining that we have too few arguments. The problem with this line of code is the missing comma between ledPin, and OUTPUT. The corrected code is on the following line:

pinMode(ledPin, OUTPUT); //Set up Arduino pin for output only.

Now, rerun the Verify/Compile command.

Line 11 Error

error: expected constructor, destructor, or type conversion before ‘(’ token


In this line the type specifier for the function is missing.

To fix this problem place the data type for the function’s return type. In this case we’re not returning any value so we need to add the keyword void in front of the loop function name. Make the following change:

void loop()

Now, rerun the Verify/Compile command.

Line 12 Error

error: function ‘void loop()’ is initialized like a variable


The block of code that makes up the loop function should be contained within curly braces “{“ and “}”. In this line a left parenthesis character “(“ is used instead of the beginning curly brace “{“. Replace the left parenthesis with the left curly brace.

Now, rerun the Verify/Compile command.

Line 13 Error

error: expected primary-expression before ‘/’ token At global scope:

/The HIGH and LOW values set voltage to 5 volts when HIGH and 0 volts LOW.

This line is supposed to be a comment describing what the program is doing. The error is caused by having only one slash character “/” instead of two “//”. Add the extra slash character then recompile.

Line 14 Error

error: ‘high’ was not declared in this scope At global scope:

digitalWrite(ledPin, high); //Setting a digital pin HIGH turns on the LED.

This error message is complaining that the variable “high” was not declared. Programming in C is case sensitive, meaning that it makes a difference if you are using upper or lower case letters. To solve this program replace “high” with the constant value “HIGH” then recompile.

Line 15 Error

error: expected `;’ before ‘:’ token At global scope:

delay(1000): //Get the microcontroller to wait for one second.

This error message is helpful in identifying the problem. This program statement was ended with a colon character “:” instead of a semicolon “;”. Replace with the proper semicolon and recompile.

Line 16 Error

error: expected unqualified-id before numeric constant At global scope:

digitalWrite(ledPin. LOW); //Setting the pin to LOW turns the LED off.

This error can be particularly troublesome because the comma “,” after the variable ledPin is actually a period “.” making it harder to spot the problem.

The C programming language allows you to build user defined types. The dot operator (period “.”) is part of the syntax used to reference the user type’s value. Since the variable ledPin is defined as an integer variable, the error message is complaining about the unqualified-id.

Line 17 Error

In function ‘void loop()’:

error: ‘daley’ was not declared in this scope At global scope:

Delay(1000); //Wait another second with the LED turned off.

This error was caused by the delay function name being spelled with an incorrect upper case character for the letter “d”. Correct the spelling using the lower case “d” and try the Sketch Verify/Compile again.

Line 18 Error

error: expected declaration before ‘}’ token



There is an extra curly brace at the end of this program. Delete the extra to correct this error.

June 04 2009

LEDBlink Arduino Program

Wiring the Breadboard

In this example we’re using a single LED on the breadboard wired to the Arduino. As shown in the example, attach a ground wire (black) to the Gnd location on the bottom of the Arduino. Connect the wire to a ground rail on the breadboard. Using additional black wires jump to the bottom ground rail on the breadboard to complete a circuit adjacent to the LED position on the breadboard.

Place the LED in the breadboard and connect the black ground wire between the ground rail and the cathode lead on the LED. Place a 150 to 220 ohm resistor in the breadboard. Attach another wire from one end of the resistor to the annode lead of the LED. Finally, attach a wire between the remaining end of the resistor and Digital Pin 3 on the Arduino to compelete the circuit.

 Breadboard Wiring LED Circuit

Breadboard Wiring LED Circuit

Programming the Arduino

Create a new program named: LEDBlink

Type in the following code, typing the comments (shown in green) are optional. You could copy and paste into the program editor but typing your own code helps you learn the programming language too.

/*--- Blink an LED  ---*/
//Associate LEDs with an Arduino Digital pin.
int ledPin = 3;  //We're using Digital Pin 3 on the Arduino.</code>

void setup()
   pinMode(ledPin, OUTPUT);   //Set up Arduino pin for output only.

void loop()
   //The HIGH and LOW values set voltage to 5 volts when HIGH and 0 volts LOW.
   digitalWrite(ledPin, HIGH); //Setting a digital pin HIGH turns on the LED.
   delay(1000);  //Get the microcontroller to wait for one second.
   digitalWrite(ledPin, LOW);  //Setting the pin to LOW turns the LED off.
   delay(1000);  //Wait another second with the LED turned off.

Learning the Language of Arduino

As described in the related article “Introduction to Programming the Arduino“, the programming language used for the Arduino is based primarily on the C language.

Language Reference



In the following program statement we are doing two things as we declare a user defined variable. First we are identifying the data type as being an integer number “int”. We also assigned a value to this variable, in this case we assigned the value 13 to the variable ledPin.

int ledPin = 13; //We’re using Digital Pin 13 on the Arduino.

Defining Functions


; semicolons

{} curly braces

[] square braces. Used to identify a specific value in a list of values called arrays. …elevator example, when you push a button to take you to the fifth floor. …floor[5]


One of the differences between programming languages like C and Visual Basic is the use of semicolons to end a statement.

When not to use semicolons.

When to use semicolons.

Standard Arduino Functions

We will be using millseconds (one thousandth of a second) with the following programs. The delay() function causes the program to wait the specified number of milliseconds.

delay(1000); //Get the microcontroller to wait for one second.

Microcontrollers as Time Keepers

Microcontrollers allow us to do things that would be difficult for us to do on our own. They can help with things like take a picture the instant lightning flashes in the sky or to photograph a balloon popping as soon as you hear it burst.

The Importance of Timing

Timing is an important part of working with microcontrollers. First, lets consider some units of time people are most familiar with. We measure time in terms of seconds, minutes, hours, days, months, and years. We use clocks and calendars to keep track of time.

Scientists think about the time to reach great distances in terms of the speed of light and measure distances in space in terms of light years.

What is the speed of light? Constant c = 299,792,458 meters per second in free space (vacuum) or 186,282.387 miles per second.

Circumference of earth at equator is 40,075,020 meters. At that rate the speed of light would circle the earth approx 7.48 times per second. To circle the earth only once it will take a fraction of a second to be more precise 1/7.48 th of a second or approximately 0.13 of a second.

From Very Large Time Units to Very Small

Microcontrollers work on the other end of a time spectrum – in very small fractions of a second. Although they are good at simply switching things on and off, microcontrollers are great as stop watches keeping track of very small time spans.

Time Keeping

An electronic watch uses a crystal to help it keep time. This is an oscillator that vibrates at the rate of 32,768 times a second or 32.768 Kilohertz (kHz).

The Arduino Duemilanove uses a time keeping oscillator too. This one operates at 16 million times a second or 16 Mega Hertz (MHz). That’s over 488 times faster than a watch crystal. This clock speed helps us measure some very small time intervals.

Units of Time at Fractions of a Second

Millisecond = 0.001 second 1 thousandth of a second. Microsecond = 1.0 x 10-6
or 0.000001 second 1 millionth of a second Nanosecond = 1.0 x 10-9
or 0.000000001 second 1 billionth of a second Picosecond = 1.0 x 10-12
or 0.000000000001 second 1 trillionth of a second

Some Events Occurring at a Fraction of a Second.

  • Car engine running at 1,000 RPM (revolutions per minute) is turning at a rate of 16.6 revolutions per second. This would be one revolution in 60 milliseconds (60 thousandths of a second).
  • People on average are only able to see changes occur about thirty times a second. That is the reason movie film and videos often update at 30 frames per second. This would be one frame every 33.3 milliseconds.
  • Household alternating current (AC) electricity in the United States switches polarity 60 times a second and 50 times a second in Europe. This would switch polarity one time every 16 milliseconds in the US and 20 milliseconds in Europe.
  • High speed video cameras running at 325,000 frames per second can be played back in slow motion allowing us to see what happens with things like bullets hitting an apple or allowing us to see what a rain drop looks like when hitting a pool of water. This would be one frame for each 0.325 millisecond or 325 microseconds (325 millionths of a second).
  • The speed of light travels about one foot in one nanosecond or one meter in approximately 3.3 nanoseconds (billionths of a second).

Arduino Time Functions

The Arduino programming language provides functions that handle timing features.

  • millis() returns the number of milliseconds (thousands of a second) since the Arduino began running or since the last number overflow.
  • micros() returns the number of microseconds (millionths of a second) since the Arduino’s program began running or the last number overflow.
  • delay(ms) causes the program to delay the specified number of milliseconds.
  • delayMicroseconds(us) causes the program to delay the specified number of microseconds.

Introduction to Programming the Arduino

The programming language used for the Arduino is based primarily on the C language. Some features of the C++ language may be used in more advanced programming features but are not used in this introduction.

Each program must include two parts for it to be valid, the setup and loop functions. Any statements included in a setup function are only run once by the program. Any statements in the loop function are executed over and over.

/*--- Minimum Arduino programming functions, setup and loop  ---*/

void setup()

void loop()

The first line in the above program is a comment. The comment is not really required but are helpful in explaining what a program is supposed to do.

/*— Minimum Arduino programming statements —*/
Comments can have two forms. The previous comment starts with the /* characters and continues until the ending characters */ are found.

/* This style of
comment can
cross multiple lines

The other comment form is with the double slash characters

// This is a comment too but is only on a single line in the program.

Comments with the // characters can begin anywhere on a line and are often used following a programming statement.

Verify and Compile

Using the Sketch → Verify/Compile command to check your work.

Arduino Sketch - Verify/Compile

Arduino Sketch -> Verify/Compile

If everything compiles successfully the Arduino’ programming environment shows the message “Done compiling”. When the sketch compiles without errors it also shows the message stating the Binary sketch size.

Sketch Successfully Compiled

Sketch Successfully Compiled

This simple program will compile properly but doesn’t do anything useful. It just shows the bare minimum needed to create a program.

About SomeoneKnows

December 15 2008

Instructable: DIY Servo Extensions.

Servos are great when building a robot and you want to be able to rotate back and forth like you’re looking for something. You may have sensors that scout around for another robot and putting it on top of a servo provides that mobility. Servos are also very useful when building a robotic arm and many other things.

One problem you’ll run into is wires that aren’t  long enough to reach from your controller to the servos. That is when you need servo extensions.

Arduino servo extensions

Arduino servo extensions

This Instructable page for DIY Servo Extensions will lead you through the process of making your own servo extensions.


December 04 2008

Online Electronics Textbooks

Lessons In Electronic Circuits is a free series of textbooks on electricity and electronics.

There is a series of six volumes focusing on:

  • DC circuits
  • AC circuits
  • Semiconductors
  • Digital
  • Reference
  • Experiments

Getting DIY Robotics Labs Started.

I’ve been a member of robotics clubs for several years and an active mentor with FIRST robotics teams in the Kansas City area. I’ve noticed while helping FIRST students that there is the lack of robotics at the personal level.  The FIRST robot kit of parts are too expensive for mom and dad to buy the same parts to play with at home. Also, many homeschool students don’t have access to the same level of robotics parts and resources for their studies.

Getting started with robotics doesn’t have to be overly expensive. This blog is dedicated to getting people started experimenting with robotics at home.

9250 c01f
Robot: VexingBehavior
Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!