Archive for September, 2009

Hello to the UK’s Robot Brighton

September 24, 2009

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

Some Pointers For Memory Allocation

September 21, 2009

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()
{
  Serial.begin(9600);
  ptrArray = (int *)malloc(sizeof(int)* 3);
  ptrArray[0] = 2;
  ptrArray[1] = 4;
  ptrArray[2] = 6;
  realloc(ptrArray,(sizeof(int)* 4));
  ptrArray[3] = 8;
  Serial.println(cmdString);
  delayTime = 200;
}

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

    switch(command) {
      case 'a':
        blinkLED(ptrArray[arrayPos]);
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
        Serial.println(strMessage);
        Serial.println(cmdString);
      break;
      case 'b':
        blinkLED(ptrArray[arrayPos]);
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
        Serial.println(strMessage);
        Serial.println(cmdString);
      break;
      case 'c':
        blinkLED(ptrArray[arrayPos]);
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
        Serial.println(strMessage);
        Serial.println(cmdString);
      break;
      case 'd':
        blinkLED(ptrArray[arrayPos]);
        sprintf(strMessage, strFormat, command, ptrArray[arrayPos]);
        Serial.println(strMessage);
        Serial.println(cmdString);
      break;
      default:
        blinkLED(0);
    }
  }
}

void blinkLED(int nTimes)
{
  
  for (int i=0; i<nTimes; i++)
  {
    digitalWrite(13, HIGH);
    delay(delayTime);
    digitalWrite(13, LOW);
    delay(delayTime);
  }
  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

Array Declarations – Processing vs Arduino

September 15, 2009

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;
}
AND
{
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 is 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. See Some Pointers For Memory Allocation.

(c) 2009 – Vince Thompson

Incrementing Variables Using ++

September 13, 2009

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.

References:

A thought 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;

 a=0;
 print("Initialize value: a = ");
 println(a);

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

 a=0;
 print("Reinitialize: a = ");
 println(a);

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

 a=0;
 print("Reinitialize: a = ");
 println(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");

 a=0;
 b=5;
 print("Reinitialize: a = ");
 print(a);
 print(" and b = ");
 println(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 as 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.begin(9600);

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

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

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

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

a=0;
Serial.print("Reinitialize: a = ");
Serial.println(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");

a=0;
b=5;
Serial.print("Reinitialize: a = ");
Serial.print(a);
Serial.print(" and b = ");
Serial.println(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.

(c) 2009 – Vince Thompson