Sunday, October 9, 2011

Processing Class 6: 3D and Libraries

Hello Class! I hope you all had a great week. Here is a brief of what I want to cover today:

3D in Processing
- How to change the Processing rendering engine to handle 3D graphics: MODE in size()
- Using the 3D Primitives: box() and sphere()
- Using pushMatrix() and popMatrix() to adjust placement of 2D shapes in 3D: translate(), rotateX(), rotateY(), rotateZ()

Libraries
- What is a library in Processing
- Where to find available libraries and how to find their reference
- How to include a library in a sketch
- How to download and setup a library to work with the Processing application


3D in Processing
While it is important to learn how to draw in Processing using 2D shapes, at some point you are going to want to break into the z-axis. The z-axis represents depth or distance from the user, assuming the user is facing the display. Many of the commands we have been using for 2D shapes such as line() and point() include ways of handling the z-coordinate along with the x and y. Before you can utilize any z-coordinate, you will need to set the render engine in Processing to understand and handle 3D. You set the render engine inside the call to size() inside of setup(). Normally, when sketching in 2D, you only need to use size() to set the width and height of the sketch. When wanting to incorporate 3D, you need to set another 3rd parameter, MODE. The MODE allows you to choose P3D, a Processing based 3D render engine, or OPENGL, a render engine that utilizes calls directly to the graphics card. You will need to look closely at the differences each render engine creates in the look and function of your sketch. Each has a different look and feel and some 2D elements, such as stroke and lines, do not always appear as you might expect.

Lets all take a look at what 3D looks like in Processing by first checking out the examples. Open Examples/3D/Camera and take a look at the 3 sketches inside. These 3 sketches point out how the camera works inside your sketch.
Now open Examples/3D/Image, these sketches show how image data can be used in a 3D environment. Extrusion is especially nice as it moves the position of points based on the brightness of the pixel in the reference image. It is possible to do this with a webcam as well.
Make sure to also take a quick look at the Textures folder and as well as the Transform folder. Rotate1 and Rotate2 examples in Transform show how pushMatrix and popMatrix can be used to create 3D images.

Most of these examples use the P3D render native to the Processing language. However, a few utilize the OPENGL library. Next we are going to learn how to use libraries to add functionality to your sketches.

Libraries
Simply put, Libraries add things your sketch can do. A library is code that was written to work within Processing, and is specific to a certain task, such as: talking to an Arduino, evaluating sound or creating sound, robust typography control, exotic file type export.

The Processing download includes several libraries which are available upon install. Any other libraries will need to be downloaded and saved into a libraries directory. The libraries directory(folder) needs to be located inside of your sketch folder, the folder where Processing looks to find your sketches(by default it is located in your documents folder). Download the library from the web and place the library folder inside of your libraries folder. Make sure and support Examples files are stored inside the library folder in a folder named "examples".

When you want to include a library in your sketch, simply mouse over the "Sketch" drop down menu item at the top of the screen, and select "Import Library…". This will in turn open another drop down menu, listing all of the available libraries. When you click a desired library, a bit of code is added to the top of your sketch on to what ever tab is open. For example, when I choose to include the OpenGL library, the code looks like this:
import processing.opengl.*;

Now lets take a look at some of the examples included with the libraries included in Processing.

Sunday, October 2, 2011

Processing Class 5: Images, Video and Saving

Hello Class. This week we are going to revisit nested for loops to move through images and grab data. We are also going to explore how to use video, both local files and a webcam. After we get through that we will learn how to save out versions of our sketches for others to see.

Images:

Processing has a native data type specific to images called PImage. Anytime you want to work with an image you need to use a PImage. The PImage object has multiple properties. Some of them are an array of pixel color value, width, and height. Images that are made up of a grid of pixels are called raster graphics.

Video:

Video requires using the video library from processing. We will explore basic use so that we have a better understanding of how to use libraries for next weeks class.

Sunday, September 25, 2011

Class 4: Arrays, Functions and using Images

Today's class will cover two very important concepts: Arrays and Functions. Afterwards, I will show you how use images in your sketches.

An array is a list or group of data. You can have an array of any type of data. For example, you want to move 10 rectangles around the screen using random incremental movements between -1 and 1(brownian motion). Instead of creating 10 variables for the x location and 10 for the y location, you can use two arrays, one for the x locations and 1 for the y locations. All of the variables are the same type and their purpose is the same.

Each variable(variables in an array are referred to as elements) in an array is associated with an index number that describes in position in the array. The first element in an array is [0] and the second is [1] and so on. When you create an array you must identify the length or number of elements in the array. You cannot access a value higher than the length of an array. If you try you will receive the Null Pointer error.

Arrays are a little different to create than normal variables. Here are a few ways to create them:
int[] numbers = new int[3];// creates an int array of 3 empty elements
int[] numbers = {10,20,30};// creates an int array of 3 elements and sets values

The power of arrays really comes to life when you use them in combination with for loops. A for loop can increment which element is being accessed/used and you can set the 'test' of the for loop to the length of the array. Every array has a variable that stores its length, the total number of elements. It can be accessed like this, arrayName.length.
int[] numbers = {10,20,30};// creates an int array of 3 elements and sets values
for(int i = 0; i < numbers.length; i++){
    println(numbers[i]);
}
// prints 10 20 30 each on their own line

Functions
Functions are a way of compartmentalizing code. Functions allow you to reuse code without having to copy and paste lines in multiple areas of your code. For example, switching back and forth from a white stroke and black fill to a black stroke and white fill.
stroke(255);
fill(0);
// to…
stroke(0);
fill(255);
Instead of having to copy and paste two lines of code each time, you could write two functions and call those commands in one line of code.
void whiteStrokeBlackFill(){
stroke(255);
fill(0);
}
// and…
void blackStrokeWhiteFill(){
stroke(0);
fill(255);
}
// to execute the functions…
whiteStrokeBlackFill();// turns the stroke to white and the fill to black
blackStrokeWhiteFill();// turns the stroke to black and the fill to white
();// turns the stroke to white and the fill to black

You can increase the usefulness of a function by setting values when you run the function. These values are called parameters. Parameters can be any data type. Here is an example:
void printNumber(int num){
println("number = " + num);
}

Sunday, September 18, 2011

Class 3: For Loops, new Shapes and more Math!!!

Hello 3rdWard! I hope you had a great week and are ready of another action packed class of Processing.

Today we are going to be focusing on a very important concept: For Loops.

What is a for loop? A for loop is a way of repeating the same commands a specified number of times.
What does it look like? It looks like this:
for(init; test; update){
statements
}
How does a for loop work? The parenthesis setup the structure of a for loop by defining the init, test, and update. The statements inside the block(a block is defined as the arguments inside curly braces{}) run continously as long as the test evaluates as true. The init assigns the initial value of the variable used in the test. The update is used to modify the variable after each iteration of the block. A for loop works like this:
1. The init statement is run
2. The test is evaluated to true or false
3. If the test is true, continue to step 4. If the test is false, jump to step 6
4. Run the statements within the block
5. Run the update statement and jump to step 2
6. Exit the structure and continue running the program

For Loops are very useful in programming graphics as they allow you to make many many iterations very easily.

Shapes:

Here are some cheat sheets that will break down the order in which you need to state your vertices to create a shape the way you want to.


Sunday, September 11, 2011

Processing Class 2: Variables, Math, and Logic

Hello everybody. I want to start off this week by taking a look at the awesome self portraits and monsters you all made. Congratulations, you are officially programmers now :) You successfully created compositions using the shape primitives, changing both the stroke(outline) and fill(shape) colors and mastered the idea of the coordinate system that is in place in Processing. This is not trivial, you have created meaning and subject with math as your tools. The reason I wanted all of you to create an annoyingly tedious character is so you develop an understanding of the coordinate system as well as the way in which order of commands changes composition and a familiarity with the shape building blocks. Next weeks homework will be to add a level of interaction to your monster/self portrait. I will go into this in more detail later….muwahhhahh.

Break down for what you will understand at the end of this class:
You will understand how to setup your sketches to allow for animation and interaction.
You will understand how to create variables, assign values to them and recall those values.
You will understand how to use mathematical operators(+,-,/,*,%, and more) allowing you to use math to arrive at values.
You will understand how to use conditional structures to control the flow of your programs.

As with last week, we are going to take a look at examples that come with Processing. This way you will be able to review when you are home as well as follow along on your machine in class.

Setting up your sketch
Last week we learned how to create a basic sketch in Processing. These sketches only display one frame that never changes. From now on we are going to be interested in multiple frames, because that way we can create animation and interaction.

Here is how I want you to setup your sketches from now on:

/*****************************************
* Header Title: elaborate the title here
* more details of sketch here
* include any credits to other people
* Your Name - date when created
*****************************************/

// declare your variables here

// setup() only happens once at the beginning of the sketch
void setup(){
// this is where you set the initial properties
size( 400, 400 );// size() should always go inside setup()
smooth();// smooth() usually only needs to go here
}

// draw() happens over and over and over
void draw(){
background(0);// apply the background first
// now draw or evaluate anything you want
}

* note: blogger lost the rest of lesson so I will be borrowing from Ben and Casey for the short term. I will go back and change this so as to not be directly using there words. But for now...
Data and Variables
What is data? Data often consists of measurements of physical characteristics. For example, Casey’s California driver’s license states his sex is M, his hair is BRN, and his eyes are HZL. The values M, BRN, and HZL are items of data associated with Casey. Data can be the population of a country, the average annual rainfall in Los Angeles, or your current heart rate. In software, data is stored as numbers and characters. Examples of digital data include a photograph of a friend stored on your hard drive, a song downloaded from the Internet, and a news article loaded through a web browser. Less obvious is the data continually created and exchanged between computers and other devices. For example, computers are continually receiving data from the mouse and keyboard. When writing a program, you might create a data element to save the location of a shape, to store a color for later use, or to continuously measure changes in cursor position.

Data types
Processing can store and modify many different kinds of data, including numbers, letters, words, colors, images, fonts, and boolean values (true, false). The computer stores each in a different way, so it has to know which type of data is being used to know how to manage it. For example, storing a word takes more room than storing one letter; therefore, storing the word Cincinnati requires more space than storing the letter C. If space has been allocated for only one letter, trying to store a word in the same space will cause an error. Every data element is represented as sequences of bits (0s and 1s) in the computer’s memory. For example, 01000001 can be interpreted as the letter A, and it can also be interpreted as the number 65. It’s necessary to specify the type of data so the computer knows how to correctly interpret the bits.
Numeric data is the first type of data encountered in the following sections of this book. There are two types of numeric data used in Processing: integer and floating- point. Integers are whole numbers such as 12, -120, 8, and 934. Processing represents integer data with the int data type. Floating-point numbers have a decimal point for creating fractions of whole numbers such as 12.8, -120.75, 8.125, and 934.82736. Processing represents floating-point data with the float data type. Floating-point numbers are often used to approximate analog or continuous values because they have decimal
37resolution. For example, using integer values, there is only one number between 3 and 5, but floating-point numbers allow us to express myriad numbers between such as 4.0, 4.5, 4.75, 4.825, etc. Both int and float values may be positive, negative, or zero.
The simplest data element in Processing is a boolean variable. Variables of this type can have only one of two values—true or false. The name boolean refers to the mathematician George Boole (b. 1815), the inventor of Boolean algebra—the foundation for how digital computers work. A boolean variable is often used to make decisions about which lines of code are run and which are ignored.
The following table compares the capacities of the data types mentioned above with other common data types:
Name Size Value Range
boolean 1 bit true or false
byte 8 bits -128 to 127
char 16 bits 0 to 65535
int 32 bits -2,147,483,648 to 2,147,483,647
float 32 bits 3.40282347E+38 to -3.40282347E+38
color 32 bits 16,777,216 colors

Variables
A variable is a container for storing data. Variables allow a data element to be reused many times within a program. Every variable has two parts, a name and a value. If the number 21 is stored in the variable called age, every time the word age appears in the program, it will be replaced with the value 21 when the code is run. In addition to its name and value, every variable has a data type that defines the category of data it can hold.
A variable must be declared before it is used. A variable declaration states the data type and variable name. The following lines declare variables and then assign values to the variables:
int x;// Declare the variable x of type int
float y;// Declare the variable y of type float
boolean b;// Declare the variable b of type boolean
x = 50;// Assign the value 50 to x
y = 12.6;// Assign the value 12.6 to y
b = true;// Assign the value true to b

As a shortcut, a variable can be declared and assigned on the same line:
int x = 50;
float y = 12.6;
boolean b = true;

More than one variable can be declared in one line, and the variables can then be assigned separately:
float x, y, z;
x = -3.9;
y = 10.1;
z = 124.23;
When a variable is declared, it is necessary to state the data type before its name; but after it’s declared, the data type cannot be changed or restated. If the data type is included again for the same variable, the computer will interpret this as an attempt to make a new variable with the same name, and this will cause an error:

int x = 69; // Assign 69 to x
x = 70; // Assign 70 to x
int x = 71; // ERROR! The data type for x is duplicated

The = symbol is called the assignment operator. It assigns the value from the right side of the = to the variable on its left. Values can be assigned only to variables. Trying to assign a constant to another constant produces an error:
// Error! The left side of an assignment must be a variable
5 = 12;
When working with variables of different types in the same program, be careful not to mix types in a way that causes an error. For example, it’s not possible to fit a floating- point number into an integer variable:
// Error! It’s not possible to fit a floating-point number into an int
int x = 24.8;

float f = 12.5;
// Error! It’s not possible to fit a floating-point number into an int
int y = f;

Variables should have names that describe their content. This makes programs easier to read and can reduce the need for verbose commenting. It’s up to the programmer to decide how she will name variables. For example, a variable storing the room temperature could logically have the following names:
t
temp
temperature
roomTemp
roomTemperature

Processing also includes a few variables that are specific to the sketch. Two we will be using are width and height. Width stores the value of the width of the sketch and height stores the height of the sketch.

Math: Arithmetic

In programming, the visual properties of an image on the screen are defined by numbers, which means that the image can be controlled mathematically. For example, a rectangle might have a horizontal position of 10, a vertical position of 10, a width and height of 55, and a gray value of 153. If the gray value is stored in the variable grayVal and 102 is added to this variable, the gray value will become 255 and the shape will appear white on screen.


The +, -, *, /, and = symbols are probably familiar, but the % is more exotic. The % operator calculates the remainder when one number is divided by another. The %, the code notation for modulus, returns the integer remainder after dividing the number to the left of the symbol by the number to the right.


Modulus can be explained with an anecdote. After a hard day of work, Casey and Ben were hungry. They went to a restaurant to eat dumplings, but there were only 9 dumplings left so they had to share. If they share equally, how many dumplings can they each eat and how many will remain? It’s obvious each can have 4 dumplings and 1 will remain. If there are 4 people and 35 dumplings, each can eat 8 and 3 will remain. In these examples, the modulus value is the number of remaining dumplings.

The modulus operator is often used to keep numbers within a desired range. For example, if a variable is continually increasing (0, 1, 2, 3, 4, 5, 6, 7, etc.), applying the modulus operator can transform this sequence. A continually increasing number can be made to cycle continuously between 0 and 3 by applying %4:
x 0 1 2 3 4 5 6 7 8 9 10
x%4 0 1 2 3 0 1 2 3 0 1 2


When working with mathematical operators and variables, it’s important to be
aware of the data types of the variables you’re using. The combination of two integers will always result in an int. The combination of two floating-point numbers will always result in a float, but when an int and float are operated on, the result is a float.

Integer values can be assigned to floating-point variables, but not vice versa. Assigning a float to an int makes the number less accurate, so Processing requires that you do so explicitly. Working with an int and a float will upgrade the int and treat both numbers as floating-point values, but the result won’t fit into an int variable.


Operator precedence, Grouping
The order of operations determines which math operators perform their calculations before others. For example, multiplication is always evaluated before addition regardless of the sequence of the elements. The expression 3 + 4 * 5 evaluates to 23 because 4 is first multiplied by 5 to yield 20 and then 3 is added to yield 23. The order of operations specifies that multiplication always precedes addition regardless of the order in which they appear in the expression. The order of operations for evaluating expressions may be changed by adding parentheses. For example, if an addition operation appears in parentheses, it will be performed prior to multiplication. The expression (3 + 4) * 5 evaluates to 35 because 3 is first added to 4 to yield 7, which is then multiplied by 5 to yield 35. This is more concisely expressed in code:
x = 3 + 4 * 5; // Assign 23 to x
y = (3 + 4) * 5; // Assign 35 to y
In many cases, parentheses are necessary to force elements of an expression to evaluate before others, but sometimes they are used only to clarify the order of operations. The following lines calculate the same result because multiplication always happens before addition, but you may find the second line more clear.
x = 10 * 20 + 5; // Assign 205 to x
y = (10 * 20) + 5; // Assign 205 to y
The following table shows the operator precedence for the operators introduced so far. Items at the top precede those toward the bottom.

Multiplicative * / %
Additive + -
Assignment =

Decisions and Controlling Flow of Programs

The programs we’ve seen so far run each line of code in sequence. They run the first line, then the second, then the third, etc. The program stops when the last line is run. It’s often beneficial to change this order—sometimes skipping lines or repeating lines many times to perform a repetitive action. Although the lines of code that comprise a program are always positioned in an order from top to bottom on the page, this doesn’t necessarily define the order in which each line is run. This order is called the flow of the program. Flow can be changed by adding elements of code called control structures.
Relational expressions
What is truth? It’s easy to answer this difficult philosophical question in the context of programming because the logical notions of true and false are well defined. Code elements called relational expressions evaluate to true and false. A relational expression is made up of two values that are compared with a relational operator. In Processing, two values can be compared with relational operators as follows:

Expression Evaluation
3> 5 false
3< 5 true
5< 3 false
5> 3 true

Each of these statements can be converted to English. Using the first row as an example, we can say, “Is three greater than five?” The answer “no” is expressed with the value false. The next row can be converted to “Is three less than five?” The answer is “yes” and is expressed with the value true. A relational expression, two values compared with a relational operator, evaluates to true or false—there are no other possible values. The relational operators are defined as follows:

Operator Meaning
> greater than
< less than
>= greater than or equal to
<= less than or equal to
== equivalent to
!= not equivalent to

The following lines of code show the results of comparing the same group of numbers with different relational operators:
println(3 > 5); // Prints "false"
println(5 > 3); // Prints "true"
println(5 > 5); // Prints "false"
println(3 < 5); // Prints "true"
println(5 < 3); // Prints "false"
println(5 < 5); // Prints "false"
println(3 >= 5); // Prints "false"
println(5 >= 3); // Prints "true"
println(5 >= 5); // Prints "true"
println(3 <= 5); // Prints "true"
println(5 <= 3); // Prints "false"
println(5 <= 5); // Prints "true"

The equality operator, the == symbol, determines whether two values are equivalent. It is different from the = symbol, which assigns a value, but the two are often used erroneously in place of each other. The only way to avoid this mistake is to be careful. It’s similar to using “their” instead of “there” when writing in English—a mistake that even experienced writers sometimes make. The != symbol is the opposite of == and determines whether two values are not equivalent.
println(3 == 5); // Prints "false"
println(5 == 3); // Prints "false"
println(5 == 5); // Prints "true"



println(3 != 5); // Prints "true"
println(5 != 3); // Prints "true"
println(5 != 5); // Prints "false"


Conditionals
Conditionals allow a program to make decisions about which lines of code run and which do not. They let actions take place only when a specific condition is met. Conditionals allow a program to behave differently depending on the values of their variables. For example, the program may draw a line or an ellipse depending on the value of a variable. The if structure is used in Processing to make these decisions:
if (test) { statements
}
The test must be an expression that resolves to true or false. When the test expression evaluates to true, the code inside the { (left brace) and } (right brace) is run. If the expression is false, the code is ignored. Code inside a set of braces is called a block.


Logical operators
Logical operators are used to combine two or more relational expressions and to invert logical values. They allow for more than one condition to be considered simultaneously. The logical operators are symbols for the logical concepts of AND, OR, and NOT:
Operator Meaning
&& AND
|| OR
! NOT

The following table outlines all possible combinations and the results.
Expression Evaluation
true && true true
true && false false
false && false false
true || true true
true || false true
false || false false
!true false
!false true

Sunday, September 4, 2011

Processing Class 1: Hello World!

Let me start off by saying I am super excited to teach you all Processing. I have been wanting to teach Processing to a group for awhile now and I am finally getting the chance. That said, lets get to it.

Getting Started:
What is Processing? Processing is an environment for programming graphics that was designed to be friendly to non programmers, yet still offer power to advanced users. It was originally created by Ben Fry and Casey Reas but has been contributed to by hundreds of users world wide. Under the hood, Processing is based on Java and any Java code can be implemented along with Processing code. In fact, Processing handles wrapping a ton of Java to make it super easy for you to get up and running without a lot of hassle. For this reason Processing files are called sketches, to relay the ideology of a quick coding attempt at a problem or idea. Don't let the term sketch fool you, a Processing sketch can be a full fledged application written in thousands of lines of code, but it can also only be one line.

What are we going to cover today:
Get to know the Processing Website and all it has to offer.

After we review the website we will get to know the Processing development environment. This is where you will create your Processing sketches.

Then we will get our hands wet with Processing by going over the examples that I have loaded to your Documents/Processing/Class_1 folder.

These images correspond to the sketches that we will be reviewing. The orange notes were included using illustrator and will not reflect in the sketch when you run it.

  1. background(0);
  2. ellipse(250, 250, 200, 200);
  3. rect(200, 200, 100, 100);



  1. point(50, 50);
  2. line(100, 50, 200, 50);
  3. curve(200, 50, 300, 50, 450, 100, 450, 300);
  4. rect(50, 100, 200, 300);
  5. ellipse(350, 150, 100, 100);
  6. triangle(300, 400, 300, 250, 450, 325);
  7. quad(38, 431, 486, 420, 469, 463, 30, 476);



  1. white/black
  2. black/white
  3. none/black
  4. red/none
  5. green/red
  6. blue/green
  7. olive/mint green
  8. brown/white
  9. khaki/orange



  1. strokeWeight(0.1);
  2. strokeWeight(5);
  3. strokeWeight(20);
  4. strokeJoin(MITER);
  5. strokeJoin(BEVEL);
  6. strokeJoin(ROUND);
  7. strokeCap(SQUARE);
  8. strokeCap(PROJECT);
  9. strokeCap(ROUND);




For further learning I highly recommend the book that was written by the creators, Processing: A Programming Handbook for Visual Designers and Artists.

For homework, please post at least one sketch to the class group on OpenProcessing.org. The requirements are to make a self portrait or a monster. Here is the class group.


Saturday, April 2, 2011

Final Class: Arduino and Physical Computing

Hello class! Time sure has flown by, much like how fast this class will go by with all of the cool things we are going to learn today.

Here is a brief break down of the things to do:
  1. Review array code from last week and discuss in depth what arrays are and how they are to be used.
  2. Learn how to control an RGB LED.
  3. Use a potentiometer attached to the Arduino to adjust the speed of a movie playing in Processing.
  4. Control a drawing program with values sent from Arduino.
Let us start by reviewing Arrays from last week.

Arrays and For Loops:

Arrays are a way of declaring multiple of the same type of variable in a row in memory. Usually they are used with the idea that the values are multiples of the same type of object. What I mean is while the value of the photocell is an integer it doesn't make sense to include it in an array of integers that represent the digital pins used to power LEDs. Arrays are declared a little differently then other variables. Here are a few ways to declare an array:

int myInts[6];// this creates an array that has 6 places but does not define what the values are
int myPins[] = {2, 4, 8, 3, 6};// this creates an array of 5 places and defines the values
int mySensVals[6] = {2, 4, -8, 3, 2};// this creates an array of 6 places but only defines the first 5 values

This is how you access the values that are stored in the arrays above:

myPins[0], where the value would equal 2.

The number inside of the square brackets [ ] indicates which element to access. Arrays are 0 based, meaning the first element is considered the 0 place not the 1st place.

Here is how you change the value of an element of an array:
myPins[1] = 9;// now the values for myPins look like this: {2, 9, 8, 3, 6}

The real power of arrays is unleashed when combined with for loops. The structure of a for loop is a little confusing at first, but once you understand how to use them they are essential. Basically a for loop is a way of repeating a command a determined number of times. You can use an array to count from any number by any number to any number. This makes it perfect for working with arrays because instead of manually putting 0-4 inside of the [ ] to access the values of myPins array, you can use a variable.

Here is a for loop that prints the values of myPins array to the serial monitor:

for(int i = 0; i < 5; i++){
Serial.print(myPins[i]);
Serial.print(", ");
}
Serial.println();

This snippet of code will display the values with a comma and space between each value and then a line break after the last element has been printed. I recommend that you take a look at the for loop link above. The guys at Arduino have a wonderful description of how the mechanics work.

RGB LED Control:

RGB LEDs are actually 3 LEDs in one. In our case 1 red, 1 blue and 1 green LED all with the same ground pin. The RGB LED you have has a clear lens and 4 leads. The leads are as follows:
The longest lead is the ground.
The lone lead next to the longest is the red LED.
The first lead on the other side of the longest leg is the green LED.
The opposite lead from the red lead is the blue LED.

Create this circuit and then load the code that is in your class4 folder.

Start by loading the class4/rgb_LED sketch. With this sketch there are two modes: animate_rainbow and contol_rainbow. The sketch begins running animate_rainbow(), which runs the LEDs through a ROYGBV looping color animation. Commenting animate_rainbow() and uncommenting control_rainbow will allow you to use the potentiometer as a control for which color is displayed.



Using Arduino and Processing together:

First off, what is Processing? From the processing website:

Processing is a programming language, development environment, and online community that since 2001 has promoted software literacy within the visual arts. Initially created to serve as a software sketchbook and to teach fundamentals of computer programming within a visual context, Processing quickly developed into a tool for creating finished professional work as well.

As a programming language, Processing is built from Java and has a strong visual output capability. When we open up the Processing IDE you will notice a strong resemblance to the Arduino IDE. This is because they were meant to work together and the founders of both languages worked together to make them look and work similar. The similarities are greater than skin deep, with Processing having a huge community following offering up tons of code resources.

There are a few ways to work with Arduino and Processing, but I am going to demonstrate only one way today. If you are interested you can check out the Arduino library available in Processing. The library allows you to make Arduino calls directly from Processing.

Today we are going to send a byte through serial to Processing and use that value to adjust the speed of a looping movie. Let's start off by making a simple circuit with the Arduino using a potentiometer and 2 different colored LEDs. The potentiometer will give us a value and the LEDs will give us an idea of what that value is before it gets to Processing. Go ahead and make the circuit in the following image. This is to help differentiate between when the video will be playing forwards and backwards.


Now load the sendSerial sketch in the Arduino class4 folder.

The code maps the value of your potentiometer to light up one LED with one half of the values and light tup the other with the other half of values. The center position of the potentiometer will render both LEDs off. These results mimic how the Processing will react to the values of the potentiometer.


Open Processing and load the serial_control_VideoPlayback sketch in the for Arduino_class4 folder.
Now with the Arduino plugged into the usb slot, go ahead and press the play button in Processing. You will notice that when you change the potentiometer, the speed at which the movie is playing will change. It is a lot of fun to manipulate computer programs with physical objects!


Now load the serial_control_diameter sketch in the for Arduino_class4 folder in Processing. Using the same functionality of the Arduino code, we now have different functionality on the computer. Now when turning the potentiometer you can control the diameter of an ellipse that is being drawn where our mouse is.


Saturday, March 26, 2011

Class 3

Today's class is going to be an exciting one. We have some new concepts to work with that are a little hard at first to understand but are very powerful. Here is a look at what we are going to learn today:
  1. Review Sine Wave homework
  2. Thresholds and calibration review (lab)
  3. Arrays and for loops
  4. Control Multiple LEDs with ease using arrays and for loops(lab)
  5. Add movement with Motors (lab)
Sinewave:



Thresholds and Calibration:

Most sensors do not generate a range of values from 0-1023 under normal working conditions. To accurately map a sensor you need to know the thresholds of the sensor. Each sensor will have a minimum and maximum threshold. Let's use a photocell to change the brightness of an LED. To do this first we will need to determine the minimum and maximum threshold of the photocell. Create the circuit below and then upload the code onto the Arduino or load the class3/autoCalibration sketch.


Once the program has been uploaded, look for the LED attached to pin 13 to light up. You now have 5 seconds to let the sensor take a hands free reading and also take a hands on reading. In the case of the photocell, let it be exposed to the ambient light of the room(this will serve as the maxThresh) and then cover up the sensor with your finger(this will serve as the minThresh). Once the pin 13 LED has turned off the loop() code will execute and you will see wonderful PWMing of a red LED.


Arrays and For Loops:

Arrays are a way of declaring multiple of the same type of variable in a row in memory. Usually they are used with the idea that the values are multiples of the same type of object. What I mean is while the value of the photocell is an integer it doesn't make sense to include it in an array of integers that represent the digital pins used to power LEDs. Arrays are declared a little differently then other variables. Here are a few ways to declare an array:

int myInts[6];// this creates an array that has 6 places but does not define what the values are
int myPins[] = {2, 4, 8, 3, 6};// this creates an array of 5 places and defines the values
int mySensVals[6] = {2, 4, -8, 3, 2};// this creates an array of 6 places but only defines the first 5 values

This is how you access the values that are store in the arrays above:

myPins[0], where the value would equal 2.

The number inside of the square brackets [ ] indicates which element to access. Arrays are 0 based, meaning the first element is considered the 0 place not the 1st place.

Here is how you change the value of an element of an array:
myPins[1] = 9;// now the values for myPins look like this: {2, 9, 8, 3, 6}

The real power of arrays is unleashed when combined with for loops. The structure of a for loop is a little confusing at first, but once you understand how to use them they are essential. Basically a for loop is a way of repeating a command a determined number of times. You can use an array to count from any number by any number to any number. This makes it perfect for working with arrays because instead of manually putting 0-4 inside of the [ ] to access the values of myPins array, you can use a variable.

Here is a for loop that prints the values of myPins array to the serial monitor:

for(int i = 0; i < 5; i++){
Serial.print(myPins[i]);
Serial.print(", ");
}
Serial.println();

This snippet of code will display the values with a comma and space between each value and then a line break after the last element has been printed. I recommend that you take a look at the for loop link above. The guys at Arduino have a wonderful description of how the mechanics work.

Let's put it into action so you can see how easy they are to use. Create the circuit below and then follow along in class to code it. I have included the code in class3/ledArray_switch. I will be coding this live in class so that you can see how to create such code. Feel free to follow along by typing or watching.


Here is the next circuit to create. This is almost the same circuit except we have switched out the switch for a potentiometer. We will use PWM on these LEDs based on a reading from the potentiometer.



Now let's swap out the potentiometer for the photocell.



Working with Motors

The arduino can allow you to control much more than LEDs. In fact you can use the arduino to physically change your environment by using motors. There are many different types of motors, but the most common are brush DC motors, servo motors, and stepper motors.

Brush DC motors : These are the most common motors. You will find them inside of toys, fans, blenders, printers, drills… the list goes on and on. The motor has two terminals, a positive and negative terminal. Simply apply power to one terminal and ground to the other and the motor will spin. Reverse which terminal gets power and ground and the direction reverses. An easy way to control the direction and power source of a motor is to use an H-Bridge.
DO NOT RUN THIS CIRCUIT/SKETCH IF YOU DO NOT HAVE AN EXTERNAL POWER SUPPLY FOR THE MOTOR. Using only the 5v from the Arduino from USB is a great way to break your Arduino.

This is how you wire your Arduino to an H-Bridge to a motor.
The code for running this circuit can be found here on the class pasteBin account.



Stepper Motor : Stepper motors break down a full rotation into a number of steps. Rather than continually rotating like a DC motor, the stepper increments in steps or fractions of a rotation. While you can also use an H-Bridge to control a stepper it is easiest to use the EasyDriver stepper controller.

Servo Motor : Servos are similar to Steppers, in that you tell it to go to a certain angle and it will stop at that angle. The difference is that most packages only have a rotational range of 180 degrees. Servos are used a lot in RC cars, boats and planes to control the steering mechanisms. At its heart a servo is a DC motor with circuitry to understand how far it has rotated. It also usually has gearing to increase its torque.

Servos are incredible easy to use with the arduino. They have three wires, power, ground, and signal. A PWM signal is sent down the signal line and the servo uses that to determine where to rotate to. Arduino has a library that makes this all very easy for us. Build the circuit below and we will control the servo with a potentiometer.



Saturday, March 19, 2011

More fun with Arduino! PComp with Arduino Class 2

Here is a short list of the topics we will cover for class 2:

How to comment code and why it is important.

Variables: What they are and how to use them.

Basic Programming Structure

Lab: Inputs from sensors and intro to Pulse Width Modulation (PWM ~)

Where to find components/tools/cool stuff



Commenting (code):

Commenting code is an important part of making sense of what is going on in the code, especially when you come back to your program at a later date. Using comments, you can leave descriptions of the processes and variables used in your program. There are two kinds of commenting, line commenting(//...) and block comments(/*...*/).

Line commenting occurs each time you place two forward slashes in your code. The rest of the text on the line with the slashes is disregarded by the compiler. This is a great way to turn off one line of code but still have it available for a later time. Block comments use a combination of */ to begin the comment and */ to end the comment. Anything inside of those characters will be disregarded by the compiler. This allows you to turn off big chunks of code and create proper code descriptions.

/*

This is a block comment. Everything inside of the "/*" and "*/" is commented out.


*/

// this is also a comment




Variables:

Variables are a way of storing and accessing values in a program. There are many different types of variables, each type has a limit to how big of a number or even what type of number can be stored inside.

The standard variables available to us through Arduino are:

boolean: boolean isButtonPressed = false;

A boolean holds one of two values, true or false. (Each boolean variable occupies one byte of memory.)


char: char incomingLetter = 'a';

A data type that takes up 1 byte of memory that stores a character value. Character literals are written in single quotes, like this: 'a'.


byte: byte ledPin = 13;

A byte stores an 8-bit unsigned number, from 0 to 255.


int: int potValue = 1023;

Integers are your primary datatype for number storage, and store a 2 byte value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).


word: word earthCircumference_inMiles = 24860;

A word stores a 16-bit unsigned number, from 0 to 65535. Same as an unsigned int.


long: long seconds_in_a_year = 31536000;

Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647. Often used to reference time passed in milliseconds.


float: float pi = 3.14159;

Datatype for floating-point numbers, a number that has a decimal point. Floating-point numbers are often used to approximate analog and continuous values because they have greater resolution than integers. Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are stored as 32 bits (4 bytes) of information.


double: double phi = 1.618;

Double precision floating point number. Occupies 4 bytes. Same thing as a float.


String: String userName = "Matthew Richard";

Strings are represented as arrays of type char.


array: int ledPins[] = {3,5,6,9,10,11};

An array is a collection of variables that are accessed with an index number. Arrays in the C programming language, on which Arduino is based, can be complicated, but using simple arrays is relatively straightforward.



Program Structure:

It is important to have a standard structure when writing a program. A structure will make it easy for you and others to locate all of the components of your program.

The first part of the program should be a description of what the program is using block comments.


The second section is where you place all of your variables. Start with constants first and then group them according to their purpose. Don't forget to leave detailed comments.


The third section is for the setup() function. Void setup() is where you initialize your digital pins and communication lines.


The fourth section is for the loop() function. Void loop() is what gets executed by the microcontroller on every loop or frame. This will get repeated over and over until the microcontroller is turned off.


The fifth section(not depicted) is used for functions you create.


Sensors - how to read the world around you


At its core Arduino was designed to help gather information about the world for use in projects and art. The way we get that information with electronics is by using sensors. Sensors come in two basic flavors, digital and analog. Digital sensors send information as HIGH or LOW, or encoded in a serial protocol. Analog sensors work by changing the voltage of a circuit that is then compared to a standard. The change in voltage is the value attributed to the sensor.


The Switch and Serial Monitor:




The Switch and LED:




The Potentiometer and Serial Monitor:


PWM - introduction to Pulse Width Modulation:



Pulse Width Modulation is a process of taking a digital pin(on/off) and creating a gradient value or change. By pulsing the pin on and off in varying square waves you can achieve a range of values which can be used to "dim" an LED. I say "dim" because really the LED is being turned on and off so fast that our eyes perceive it as dim.


The Potentiometer and LED:




The Photocell and LED:


Two Potentiometers and One LED:




Where to find components/tools/cool stuff:

At some point you are going to need to add to your project. If you need it local your only options are a RadioShack or a small electronics seller in China Town. The address is 269 Canal Street and the store is located in the back. If you don't need it today, then you have a much wider option for price and availability online. I have included some of my most frequented online stores along with what they stock.

Local:

RadioShack - common components, wires and tools

269 Canal Electronics - rarer components, call and ask, not cheap, in China Town

Electronics:

SparkFun Electronics - Hacker/Hobbyist Electronics and Arduino

Adafruit

- Hacker/Hobbyist Electronics and Arduino

Evil Mad Science - Arduino and cheap LEDs

MaceTech - LED control for Arduino

Electronics Goldmine - Close out prices on electronic parts and tools, mostly older

All Electronics - Close out prices on electronic parts and tools, mostly new

Jameco - Professional Electronic Parts and ICs

Mouser - Professional Electronic Parts and ICs


Robotics:

Pololu - Motor controllers and sensors

LynxMotion - Servo housings and metal robot kits


Hardware/Materials:

SmallParts - small mechanic components and hand tools



McMaster Carr - all sorts of awesome building materials and tools, delivers fast