Archive for the ‘Processing Language’ Category

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
Advertisements

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

Making The Connection – Serially

July 17, 2009

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.list());
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() { } [/sourcecode] 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

Processing – Arduino IDE Comparison

June 18, 2009

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.

(c) 2009 – Vince Thompson

Joystick Simulation with Processing

June 17, 2009

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
 http://www.twitter.com/SomeoneKnows

<<<----*/

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;

  surfDisplayCenterX=displayWidth/2;
  surfDisplayCenterY=displayHeight* .65;

  smooth();
  strokeWeight(10.0);
  stroke(0, 100);
  color1=color(0);  //Color = Black
  color2=color(150);  

  rSize = displayWidth/2;

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

void draw()
{
  float joyHorizontalText, joyVerticalText;

  background(226);

  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);
  }
  else
  {
    curJoyRange = 0;
  }

  fill(200);
  noStroke();
  ellipse(joyDisplayCenterX, joyDisplayCenterY, curJoyDisplayHeight, curJoyDisplayWidth);

  stroke(0,100);
  segment(joyDisplayCenterX, joyDisplayCenterY, curJoyAngle);
  ellipse(joyDisplayCenterX, joyDisplayCenterY, 20, 20);

  fill(160,0,0);
  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)
{
  pushMatrix();
  translate(x, y);
  rotate(a);
  if (curJoyRange > maxJoyRange)
    curJoyRange = maxJoyRange;

  line(0, 0, curJoyRange, 0);
  popMatrix();
}

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

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

  pushMatrix();
  stroke(0);
  translate(surfDisplayCenterX, surfDisplayCenterY, 0);
  rotateX(HALF_PI+radVert);
  rotateY(radHoriz);
  fill(0,20,240);
  box(rSize, rSize, 8);
  popMatrix();

}

Line 58 Error

Chances are you tried running the sketch and get the following error message:

java.lang.NullPointerException
at java.io.DataInputStream.readInt(DataInputStream.java:370)
at processing.core.PFont.<init>(PFont.java:128)
at processing.core.PApplet.loadFont(PApplet.java:3517)
at Joystick.setup(Joystick.java:77)
at processing.core.PApplet.handleDraw(PApplet.java:1400)
at processing.core.PApplet.run(PApplet.java:1328)
at java.lang.Thread.run(Thread.java:619)
Exception in thread “Animation Thread” java.lang.RuntimeException: Could not load font Monospaced.bold-12.vlw. Make sure that the font has been copied to the data folder of your sketch.
at processing.core.PApplet.die(PApplet.java:2186)
at processing.core.PApplet.die(PApplet.java:2195)
at processing.core.PApplet.loadFont(PApplet.java:3520)
at Joystick.setup(Joystick.java:77)
at processing.core.PApplet.handleDraw(PApplet.java:1400)
at processing.core.PApplet.run(PApplet.java:1328)
at java.lang.Thread.run(Thread.java:619)

If this happens, the compiler is complaining because it doesn’t find the specified font. When you create a new Processing sketch it places it in a new folder. The font needs to be added to the data folder.

Creating the font file is accomplished by selecting Tools -> Create Font … from the Processing Menu.

Processings Tools-Create Font... selection

Processing's Tools->Create Font... selection

This brings up a dialog box to make your font selection.

Selecting the Monospaced.bold font

Selecting the Monospaced.bold font

Locate the Monospaced.bold font type then change the font size selection to 12, when done press the OK button.

(c) 2009 – Vince Thompson