Nothing Special   »   [go: up one dir, main page]

Processing and Arduino Workshop Material PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 583

Environment

Environment-Toolbar Buttons
The toolbar buttons allow you to run and stop programs,
create new sketches, open, save and export:
1. Run . Compiles the code, opens a display window,
and runs the program inside.

2. Stop Terminates a running program, but does not


close the display window.

3. New Creates a new sketch.

4. Open Provides a menu with options to open files.


Another way of opening files is dragging and the file
icon to text editor area or processing icon.

5. Save Saves the current sketch to its current location.

6. Export Exports the current sketch as a Java applet


embedded in an HTML file.
Your First Piece of Code

void setup(){
size(200,200);
}

void draw(){
background(125);
float x=mouseX;
float y=mouseY;
println("Mouse x=" + x + "..... Mouse y=" + y);
line (x,y,100,100);
}
Environment-Menu Bar

The menus provide the same functionality as the tool


bar in addition to actions for file management and
opening reference materials.
Environment-Menu Bar-Default Examples

Under Examples you can find already made codes that you
can use as the base of your experiments and achieve the
desired result by changing these base codes.

This is what programmers call hacking. Meaning that you do


not start a piece of software yourself. You use other’s
software and change parts of it, to make it work your way
Hacking the Default Examples

For example lets go to examples , under basic, under


transform, choose arm, and run the code.
Hacking the Default Examples

Let’s say we want the background color white and we want to


double the size of the applet.
Hacking the Default Examples

size(400,400);
Hacking the Default Examples

background(255);
Hacking the Default Examples

Your code

Preexisting Code

Hacking the code


Exporting as a Java Applet on a Webpage

The export feature packages a sketch to run within a


Web browser.

When code is exported from Processing it is converted


into Java code and then compiled as a Java applet.
Exporting as a Java Applet on a Webpage

When a project is exported, a series of files are written to


a folder named applet that is created within the sketch
folder.

All files from the sketch folder are exported into a single
Java Archive (JAR) file with the same name as the
sketch.
Exporting as a Java Applet on a Webpage

index.html is a webpage that contains the java applet and


a link to actual code that results in the supported
interaction.

If you have a website you can use this feature to place


your programs online as a part of your website.
Exporting as a Java Applet on a Webpage

To see and change the html code on internet explorer go


to view>Source

You can edit the html file in a text editor and save it again
as html file to see the result of the changes that you have
made
Exporting as a Application

In addition to exporting Java applets for the Web,


Processing can also export applications for the linux,
Macintosh, and Windows platforms.
Exporting as a Application

When “Export Application” is selected from the File menu,


folders will be created for each of the operating systems
specified in the Preferences. Each folder contains the
application, the source code for the sketch, and all
required libraries for a specific platform.
Printing the Code

Page setup and print are the same as any conventional


text editor program.
Printing the Code

You can print the code that you have , using print menu
option
Setting Preferences

This is where you define the default address for your


sketches to be saved
Edit Menu-Managing the Code

Commands on the edit menu control the text editor

Find option is really useful when you have a huge


number of code lines and you want to find a specific
variable to change it. It is good to memorize the shortcuts
for it:
Ctrl F for Find and Ctrl G for Find next
Sketch Menu- Running/Presenting the Code

Present is kind of a cool command too, when you choose


to run an application in presentation mode, it covers the
whole screen.

They are times that you are checking your code to find
out which part is not working and you run it tens of times.
It save you a lot of time if you know the shortcut for it.

For presentation it is Ctrl+Shift+R And for Run command


it is CTRL+R
Sketch Menue- Running/Presenting the Code

Presenting is useful when you are finally ready to setup your screen based installation, this way
the piece will cover the whole screen
Getting Help-Help Menu

Help menu give you different options and direct you to


different web pages on the Processing website
Getting Help-Online Reference

Reference will direct you to a comprehensive index of different


processing commands and functions online

You can choose to view the abridged or extended version of the


list.

You find all the information that you need for any command or
code element in this list.
Getting Help-Online Reference

In the online index you can click on a command to be


directed to a page with complete explanation and
examples of use of that command
Processing-Syntax

Each programming language has specific


linguistic details, that defines how the
commands should be written. This set of rules
is called the syntax of that programming
language.
Processing-Syntax-Comments

Comments are ignored by the computer but are important


for people. They let you write notes to yourself and to
others who read your programs.

// Two forward slashes denote a one-line comment.

/*
A forward slash followed by an asterisk allows the
multi-line Comment to continue until the opposite
*/

All letters and symbols that are not comments are


translated by the compiler
Processing-Syntax-Functions

Functions allow you to execute all types of actions.

A function’s name is usually a lowercase word followed by


parentheses.

The comma-separated elements between the parentheses


are called parameters, and they affect the way the function
works.

Example:

// The size function has two parameters: width and height


size(200,200);
/* Sets the background of the display window in range of 0
(black) to 255 (white) */
background(102);
Processing-Syntax-Functions

Comment

// The size function has two parameters: width and height

size(200,200); Statement Terminator

Function Parameter Omitting the semicolon at the end of a


statement, a very common mistake, will
result in an error message, and the
program will not run.
Processing-Syntax-Functions

// ERROR! The B in “background” is capitalized

Background(200);
Processing is Case Sensitive, it differentiates between uppercase and lowercase characters;
therefore, writing “Background” when you mean to write “background” creates and error.
Processing-Syntax-Expressions

Expressions are often combinations of operators such as +,


*, and / that operate on the values to their left and right.

Expressions can also compare two values with operators


such as > (greater than) and < (less than). These
comparisons are evaluated as true or false.
Expression Value

5 5

122.3+3.1 125.4

((3+2)*-10) + 1 -46

6>3 true

54 < 50 false
Processing-Printing Expression Results

The functions print () and println () can be


used to display data while a program is running

These functions write text inside the console

You can print the result of expressions or actual


sentences to the console using these
commands

println("Hello World!");
println(5*24-(5/2.34));
println("The Result is "+100*10);
Interactivity and Data

In design and implementation of an interactive piece the first step is coming up with an
appealing scenario:

What is it that you want your piece to do?


What feature of the environment you want your system to be responsive to?
What physical property of your environment you want to sense or measure?
Which sensor I have to use?
Which feature of the environment I want to change based on the sensed data?
Which actuator I need to use to change the intended feature or property of
environment?
How do I want to relate the input and out put of the system?

As a result in the schematic design of the piece you decide which type of data you want
to read from environment and which type of data you want to write back to environment
or actuators of the environment
Diagram by Kostas Terzidis
Has Video
Has Video
Interactivity and Data

Any interactive object or space is made up


of three elements:

First is the physical interface, the stuff that you


touch, hear, or see.

Second is the software interface, the


commands that you send to the object or space
to make it respond.

Third is the electronical interface which are the


electronical parts that communicate with the
system and each other through sending data
and receiving data in form of electrical pulses.
Interactivity and Data

A microcontroller has no physical interface that humans can


interact with directly.

It is just an electronic chip with input and output pins that can
send or receive electronical pulses.

Using a micro controller is a three-stage process:

1. You connect sensors to the input pins to convert physical


energy like motion, heat and sound into electrical energy

2. You attach motors, speakers, and other devices to the


outputs to convert electrical energy into physical action

3. You write a program to determine how the input changes


affect the outputs which is basically reading the changes in
input data and aplying changes in output data
Interactivity and Data

Every thing that you sense from or send to an environment is in the form of data
Processing-Data-Variables

What is data? Data often consists of


measurements of physical attributes.

In software, data is stored as numbers and


characters. Even Sounds, pictures and videos
are stored in computer as a series of numbers

Computers are continually receiving data from


the mouse and keyboard.
Processing-Data-Variables

What is a Variable? A variable is the container


in which the computer program stores the value
of a data.

The values that are stored in a variable can


change through out the time that the program is
running

A variable has three different attributes:


Type, Name, Value
Processing-Data-Variables

What is a Data Type? 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.
Processing-Data Types

Data Types

Numerical Non-Numerical

Integer:
Float: Boolean: Character: String:
…,-4,-3,-2,-
-1.45, 4.0,24.56 true, false ‘a’, ‘G’, ‘~’ “Hello World!”
1,0,1,2,3,4,…
Processing-Data Types
Boolean variable is often used to make decisions . About which lines of code are
run and which are ignored.
For example, imagine that you write a piece of code that turns on the light in a room of
it detects that it is dark outside and there is not enough light coming from the window:
The pseudo-code would be as follows:

A Boolean variable called “is it night yet?” is initiated

check the value of “is it night yet?” variable

if the value of “is it night yet?” is true , to turn on the light

if the value of “is it night yet?” is false, not to turn on the light
Processing-Variable Declaration/Assignment

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. 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. Once a variable is
declared, you can assign values to it.
Processing-Variable Declaration

int peopleCount;
Data Type Variable Name
Processing-Variable Assignment

Assignment Operator

peopleCount = 127;
Variable Name value
Processing-Variable Assignment

Assignment Operator

peopleCount = 127;
Variable Name value
Processing-Variable Assignment

Assignment Operator

peopleCount = peopleCount+1;
Variable Name value
Processing-Variable Declaration

float temperature;
Data Type Variable Name
Processing-Variable Assignment

Assignment Operator

temperature = -32.8;
Variable Name value
Processing-Variable Declaration

String buildingName;
Data Type Variable Name
Processing-Variable Assignment

Assignment Operator

buildingName = “Al&D”;
Variable Name value
Processing-Variable Declaration

boolean isItNight;
Data Type Variable Name
Processing-Variable Assignment

Assignment Operator

isItNight = true;
Variable Name value
Processing-Variable Assignment/Decleration

Assignment Operator

String buildingName = “Al&D”;


Data Type Variable Name value
Processing-Multiple Variable Decleration

int days, peopleCount, room;


Data Type Variable Name
Variable Name Variable Name
Processing-Variable Assignment/Decleration
Printing Variable Values to Console
// This is where you declare and initiate variables
int a = 7; //integer is any whole number : ... -5,-4,-3,-2,-1,0,1,2,3,4,5,...
float b = 14.3; // float is any number with decimal part : 1.00, 14.78, -6.5
String c = "Nashid";
// String is any alphabetical combination, when declaring use double quotes
char d = 'N';
// char is any character, when declaring use single quotes
println("a = "+ a);
println("b = "+ b);
println("c = "+ c);
println("d = "+ d);
print("a+b = ");
println(a+b);
print("a-b = ");
println(a-b);
print("a*b = ");
println(a*b);
print("a/b = ");
println(a/b);
Processing-Graphical Elements-Frame Size
size(height , width);

size(100,100);

size(200,100);
Processing-Graphical Elements-Background
background(GrayValue);
background(Red,Green,Blue);

background(100);

background(255,0,0);

The Gray and RGB values can be any number from 0 to 255
Processing-Graphical Elements-Background

If you do not know the gray or RGB values of the color


that you want you can use the photoshop color picker to
find them.
Processing-Graphical Elements-Drafting

The Display window is like a canvass that you can


create/draw any graphical entity or composition on it. X

Like any other drafting environment the first step to create


shapes is to specify their coordinates or positions

A position on the screen is comprised of an x -coordinate Y


and a y-coordinate.

In Processing, the origin is the upper-left corner of the


display window.
Processing-Graphical Elements-Shapes

In Processing there are different commands to create and place


different shapes on the provided canvas:

point(x,y);

point(40,50);
Processing-Graphical Elements-Shapes

In Processing there are different commands to create and place


different shapes on the provided canvas:

line(x1,y1,x2,y2);

line(20,30,70,80);
Processing-Graphical Elements-Shapes

In Processing there are different commands to create and place


different shapes on the provided canvas:

triangle(x1,y1,x2,y2,x3,y3);

triangle(10,10,40,40,25,60);
Processing-Graphical Elements-Shapes

In Processing there are different commands to create and place


different shapes on the provided canvas:

rect(x,y,w,h);

rect(10,30,60,30);
Processing-Graphical Elements-Shapes

In Processing there are different commands to create and place different shapes
on the provided canvas:

rectMode(CENTER);// The specified x and y is the center of the shape


rect(20,30,30,30);
rectMode(CORNER);// The specified x and y is the upper left corner
rect(20,30,30,30);
Processing-Graphical Elements-Shapes

In Processing there are different commands to create and place


different shapes on the provided canvas:

quad(x1,y1,x2,y2,x3,y3,x4,y4);

quad(38, 31, 86, 20, 69, 63, 30, 76);


Processing-Graphical Elements-Shapes

In Processing there are different commands to create and place


different shapes on the provided canvas:

ellipse(x,y,w,h);

ellipse(40,30,40,30);
Processing-Graphical Elements-Shapes

In Processing there are different commands to create and place different shapes
on the provided canvas:

ellipseMode(CENTER);// The specified x and y is the center of the shape


ellipse(50,50,40,40);
ellipseMode(CORNER);// The specified x and y is the upper left corner
ellipse(50,50,40,40);
Processing-Graphical Elements-Shapes

In Processing there are different commands to create and place different shapes
on the provided canvas:

beginShape();
curveVertex(10,10);//Specifies the direction at the first point
curveVertex(10,30);
curveVertex(20,30);
curveVertex(45,85);
curveVertex(70,20);
curveVertex(75,40);
curveVertex(10,10);//specifies the direction of the curve at the last point
endShape();
Processing-Graphical Elements-Shapes

In Processing there are different commands to create and place different shapes
on the provided canvas:

beginShape();
vertex(10,10);
vertex(10,30);
vertex(20,30);
vertex(45,85);
vertex(70,20);
vertex(75,40);
vertex(10,10);
endShape();
Processing-Graphical Elements-Shapes
Further Reading on Shapes and Graphics
Processing-Graphical Elements-Attributes

In Processing there are different commands to


change the visual attributes of the graphics:

noFill(); noFill();
fill(grayValue); rect(10,10,20,20);
fill(grayValue , transparency); fill(255);
fill(Red , Green , Blue); rect(20,20,20,20);
fill(Red , Green , Blue , transparency); fill(200);
rect(30,30,20,20);
fill(150);
rect(40,40,20,20);
fill(100);
rect(50,50,20,20);
fill(50);
rect(60,60,20,20);
fill(0);
The parameters can rage between 0 and 255 rect(70,70,20,20);
Processing-Graphical Elements-Attributes

In Processing there are different commands to


change the visual attributes of the graphics:

noFill(); background(255,0,0);
fill(grayValue); fill(255,255);
fill(grayValue , transparency); rect(10,10,20,20);
fill(Red , Green , Blue); fill(255,200);
fill(Red , Green , Blue , transparency); rect(30,30,20,20);
fill(255,150);
rect(50,50,20,20);
fill(255,100);
rect(70,70,20,20);

The parameters can rage between 0 and 255


Processing-Graphical Elements-Attributes

In Processing there are different commands to


change the visual attributes of the graphics:

noFill(); background(255);
fill(grayValue); fill(255,255,0);
fill(grayValue , transparency); rect(10,10,20,20);
fill(Red , Green , Blue); fill(255,0,0);
fill(Red , Green , Blue , transparency); rect(30,30,20,20);
fill(255,150,0);
rect(50,50,20,20);
fill(100,200,50);
rect(70,70,20,20);

The parameters can rage between 0 and 255


COLOR in Computer Graphics
1. Working with color on screen is different from working with color on paper or canvas.
2. The most common way to specify color on the computer is with RGB values, where R stands for RED and G
stands For GREEN and B stands for Blue
3. An RGB value sets the amount of red, green, and blue light in a single pixel of the screen. If you · look
closely at a computer monitor or television screen, you will see that each pixel is comprised of three
separate light elements of the colors red, green, and blue; but because our eyes can see only a limited
amount of detail, the three colors mix to create a single color.
4. For example, adding all the colors together on a computer monitor produces white, while adding all the
colors together with paint produces black (or a strange brown). A computer monitor mixes colors with
light. The screen is a black surface, and colored light is added. This is known as additive color, in contrast
to the subtractive color model for inks on paper and canvas. This image presents the difference between
these models:
COLOR in Computer Graphics
1. The intensities of each color element are usually specified with values between 0 and 255 where 0 is the
minimum and 255 is the maximum amount of the colored light that can be added to mix
R G B

Red 255 0 0

Magenta 255 0 255

Blue 0 0 255

Cyan 0 255 255

Green 0 255 0

Yellow 255 255 0

White 255 255 255

Black 0 0 0
RGB Versus HSB
1. You can use RGB (RED,GREEN,BLUE) or HSB(Hue,SATURATION,BRIGHTNESS)values of a color.
2. Processing uses the RGB color model as its default for working with color.
3. The colorMode () function sets the color space for a program:

colorMode(RGB) ; //set the color space to RGB


colorMode(HSB) ; //set the color space to HSB
HSB in Processing
// Change the hue, saturation and brightness constant
colorMode(HSB);
for (int i = 0; i <100; i++) {
stroke(i*2.5, 255, 255);//stroke(hue,Saturation,Brightness)
line(i, 0, i, 100);
println(i);
}

//Change the saturation. hue and brightness constant


colorMode(HSB);
for (int i = 0; i < 100; i++) {
stroke(132, i*2.5, 204); //stroke(hue,Saturation,Brightness)
line(i, 0, i, 100);
}

//Change the brightness. hue and saturation constant


colorMode(HSB);
for (int i = 0; i < 100; i++) {
stroke(132, 108, i*2.5); //stroke(hue,Saturation,Brightness)
line(i, 0, i, 100);
}
Shift from one color to another color In RGB
// Shift from blue (61,159,204) to green (153,207,61)in RGB mode
colorMode(RGB);
float r=0;
float g=0;
float b=0;
for (int i = 0; i < 100; i++) {
r = 61 + (i*0.92); // You want to go from 61 to 152 in 100 step: 61+i/100*(153-61)=Value at step
i
g = 159 + (i*0.48);// You want to go from 159 to 207 in 100 step: 159+i/100*(207-159)=Value at
step i
b = 204 - (i*1.43);// You want to go from 204 to 61 in 100 step: 204+i/100*(61-204)=Value at
step i
stroke(r, g, b);
line(i, 0, i, 100);
println(r);
println(g);
println(b);
}
Shift from one color to another color In HSB
// Shift from blue to green in HSB mode blue(200,100,100)/green(80,100,100)
colorMode(HSB,360,100,100);
// the range of hue is 1 to 360, the range of Saturation and Brightness is 1 to 100
for (int i = 0; i < 100; i++) {
float newHue = 200 - (i*1.2);
stroke(newHue, 100, 100);
line(i, 0, i, 100);
Processing-Graphical Elements-Attributes

In Processing there are different commands to


change the visual attributes of the graphics:

noStroke();
stroke(grayValue);
stroke(grayValue , transparency);
stroke(Red , Green , Blue);
stroke(Red , Green , Blue , transparency);

The parameters can rage between 0 and 255


Processing-Graphical Elements-Attributes

In Processing there are different commands to


change the visual attributes of the graphics:

strokeWeight(pixels); noFill();
strokeWeight(2);
stroke(255,0,0);
rect(10,10,30,30);
strokeWeight(4);
stroke(0,255,0);
rect(30,30,30,30);
strokeWeight(8);
stroke(0,0,255);
rect(50,50,30,30);

The parameters can rage between 0 and 255


Why the values range between 0-255?

In computer science every piece of information


is saved in memory in the form of a series of 0s 0 0
and 1s.

The smallest unit of data is called a bit that can 1 0


store a 1 or a 0 in it.

If we have two bits the possible combinations


that can be stored is 2*2 which is four 0 1

In the same manner if you have three bits the


possible combinations that can be stored is 1 1
2*2*2 which is 8
Why the values range between 0-255?

Byte is an information holder which consists of


8 bites so the number of possible combinations
is 2*2*2*2*2*2*2*2 or 2^8 which is 256.

If we start from number 0 , the list of numbers


that can be stored in a byte is 0 through 255.

To figure out what is the actual number that is


stored in a byte, follow the following formula:

1 0 1 1 0 1 1 0

* 2^7 + * 2^6+ *2^5+ *2^4+ *2^3+ *2^2+ *2^1+ *2^0


1*128+0*64+1*32+1*16+0*8+1*4+1*2+0*1
Why the values range between 0-255?

1 1 1 1 1 1 1 1

•2^7 + * 2^6+ *2^5+ *2^4+ *2^3+ *2^2+ *2^1+ *2^0


=
1*128+1*64+1*32+1*16+1*8+1*4+1*2+1*1
= 255 // White
Why the values range between 0-255?

0 0 0 0 0 0 0 0

•2^7 + * 2^6+ *2^5+ *2^4+ *2^3+ *2^2+ *2^1+ *2^0


=
0*128+0*64+0*32+0*16+0*8+0*4+0*2+0*1
= 0 // Black
Processing-Graphical Elements-Attributes
Further Reading on Shape Attributes
Processing-Parametric Design

Function(parameter01,parameter02,…);

rect(x,y,w,h);

Has Video
Processing-Parametric Design

void setup(){
size(300,300);
background(255);
}
void draw(){
background(255);
int rectW=mouseX-10;
int rectH=mouseY-10;
rect(10,10,rectW,rectH);
}
Processing-Parametric Design
Processing-Program Flow

Any code in processing is executed line by line


from top to bottom. Thus the program flow or
the sequence in which the lines of code are
executed is linear and from top to bottom.

ellipse(30,30,50,50);
rect(25,25,50,50);

rect(25,25,50,50);
ellipse(30,30,50,50);
Processing-Program Flow-setup(),draw()

There are ways to manipulate the sequence of the program flow. One of them is
specifying which part of code is run once and which part is run repeatedly.

void setup(){
//this is the block of code that is run once
}

void draw(){
//this is the part of code that is run repeatedly while the applet is running
}
Processing-Program Flow-setup(),draw()

There are ways to manipulate the sequence of the program flow. One of them is
specifying which part of code is run once and which part is run repeatedly.

void setup(){
size(200,200);
background(255);
}

void draw(){
// background(255);
line(100,100,mouseX,mouseY);
}

*** Adding a background function to the draw causes the screen to redraw and
erases the trace of the movement of the graphics on the screen
Processing-Program Flow-setup(),draw()

There are ways to manipulate the sequence of the program flow. One of them is
specifying which part of code is run once and which part is run repeatedly.

void setup(){
size(200,200);
background(255);
}

void draw(){
background(255);
rect(mouseX,mouseY,30,30);
}
Program Flow-Conditional Statements
Another way to manipulate the program flow is using conditional statements. In conditional
statements you specify that if a certain condition is met then a certain part of code is executed
and otherwise the compiler skips that part of the code.

if ( Logical Expression){

// this is where you put the code that you want to execute if the first condition is met
}

else if ( Logical Expression){

// this is where you put the code that you want to execute if the second condition is met

}else{

// this is where you put the code that you want to execute if the second condition is met

}
Program Flow-Conditional Statements
Another way to manipulate the program flow is using conditional statements. In conditional
statements you specify that if a certain condition is met then a certain part of code is executed
and otherwise the compiler skips that part of the code.

if ( Logical Expression){

// this is where you put the code that you want to execute if the first condition is met
}

else if ( Logical Expression){

// this is where you put the code that you want to execute if the second condition is met

}else{

// this is where you put the code that you want to execute if the second condition is met

}
Conditional Structures- Relational Expressions

A relational expression is made up of two values that


are compared with a relational operator:
Expression Evaluation
3>5 False
5>3 True
5=3 False

A relational expression evaluates to True or False


> Greater Than
< Less than
>= Greater than or equal to
<= Less than or equal
== Equivalent to
!= Not Equivalent
Logical Operators
Logical operators are used to combine two or more relational expressions or to invert logical values
Operator Meaning Explanations
&& And The logical AND operator allows the entire relational statement to be
true only if both parts are true.
|| Or The logical OR operator makes the relational expression true if only
one part is true.
! Not The logical NOT operator inverts the logical value of the associated
boolean variables. It changes true to false, and false to true.
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
Program Flow-Conditional Statements
Another way to manipulate the program flow is using conditional statements. In conditional
statements you specify that if a certain condition is met then a certain part of code is executed
and otherwise the compiler skips that part of the code.

void setup(){
size(300,50);
background(255);
}

void draw(){
background(255);
println(mouseX);
if (mouseX<100){
fill(255,0,0);
}else if (mouseX>200){
fill(0,0,255);
}else{
fill(0,255,0);
}
rect(mouseX,5,40,40);
}
Program Flow-Multi Conditional Statements
You can use a combination of multiple conditions in a if statement:

AND: if (mouseX<50 && mouseY>30)

OR: if (mouseX<50 || mouseY>30)

NOT: if ( !(mouseX<50))

Checking Equality: if (mouseX==50)


Program Flow-Nested Conditional Statements
You can have one condition in another condition:

if(Conditional Expression){

if(Conditional Expression){
// The code in case that the outer condition and the inner condition are both met
}
}
Program Flow-Nested Conditional Statements
You can have one condition in another condition:

void setup(){
size(100,100);
background(255);
}

void draw(){
background(255);
println(mouseX);
if (mouseX<50){
fill(255,0,0);
if (mouseY<50){
strokeWeight(5);
}else{
strokeWeight(1);
}
} else {
fill(255);
strokeWeight(1);
}
rect(mouseX,mouseY,10,10);
}
Program Flow-For Loop
Another way to manipulate the program flow is using loops. In a loop structure you specify a
number of times that you want a block of code to be executed.

for( initiate a variable for counter; check counter value; change counter value after each loop){

//Here you put the block of code that you want to repeat

for( int i=0; i<100; i++){


//Here you put the block of code that you want to repeat
}
Program Flow-For Loop

Another way to manipulate the program flow is using loops. In a loop structure you specify a
number of times that you want a block of code to be executed.

void setup(){
size(100,100);
background(255);
}

void draw(){
//background(255); //Using Background in an iterative loop gives the impression of animation
for( int i=0; i<10; i++){
rect(i*10,10,5,5);
}
}
Repetition
1. Computers are excellent at executing repetitive tasks accurately and quickly.
2. Iterative structures are used to compact lengthy lines of repetitive code.
3. The for structure performs repetitive calculations and is structured like this:

for (init; test; update) {


statements
}
3. The parentheses associated with the structure enclose three statements: init, test. And
update.
4. The statements inside the block are run continuously while the test evaluates to true.
5. The in it portion assigns the initial value of the variable used in the test.
6. The update is used to modify the variable after each iteration through the block.
7. A for structure runs in the following sequence:
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(int i=0; i<50; i++){ line(i*2,10,i*2,90);}

for(int i=0; i<100; i=i+2){line(i,i,i,50);}

for(int i=0; i<100; i=i+2){line(i,10,random(100),90);}

for(int i=100; i>0; i=i-2){rect(0,0,i,i);}

for(int i=0; i<100; i=i+5){rect(i,0,3,99);}

for(int i=0; i<700; i=i+2){line(i,50,i,sin(radians(i*3))*30+50);}

for(int i=70; i>0; i=i-4){ellipse(50,50,i,i);}

for(int i=70; i>0; i=i-4){ellipse(i,50,i,i);}


Mathematical Operations-Shortcuts

x++; //Equivalent to x = x + 1
y--; //Equivalent to y=y-1
z+=5; //Equivalent to z=z+5
w-=5; //Equivalent to w=w-5
u*=2; //Equivalent to u=u*2
v/=3; // Equivalent to v=v/3
Program Flow-For Loop-Nested Loops

Another way to manipulate the program flow is using


loops. In a loop structure you specify a number of times
that you want a block of code to be executed.

void setup(){
size(100,100);
background(255);
}

void draw(){
background(255);
for( int i=0; i<10; i++){
for( int j=0; j<10; j++){
rect(i*10,j*10,5,5);
}
}
}
Program Flow-For Loop-Nested Loops

Another way to manipulate the program flow is using


loops. In a loop structure you specify a number of times
that you want a block of code to be executed.

void setup(){
size(100,100);
background(255);
}

void draw(){
background(255);
for( int i=0; i<10; i++){
for( int j=0; j<10; j++){
print(i*10+ ","+ j*10 + " - ");
}
println();
}
}
Program Flow-For Loop-Breaking a Loop

Sometimes you want to get out of a loop before the


number of times that a loop is supposed to repeat itself if
a certain condition is met

for( int i=0; i<10; i++){

if( Conditional expression){


break;
}
}
Program Flow-For Loop-Breaking a Loop

Sometimes you want to get out of a loop before the


number of times that a loop is supposed to repeat itself if
a certain condition is met

void setup(){
size(100,100);
background(255);
}

void draw(){
background(255);
for(int i=0; i<10; i++){
if ( i*10>mouseX ){
break;
}
rect(i*10,10,10,10);
}
}
Program Flow-For Loop-Skipping a Loop
Sometimes you want to skip the action of a loop if a
certain condition is met but still continue the loop after
that for the specified times in the loop structure

void setup(){
size(100,100);
background(255);
}

void draw(){
background(255);
for(int i=0; i<10; i++){
if ( i*10>mouseX ){
break;
}
if ( i*10==30 ){
continue;
}
rect(i*10,10,10,10);
}
}
Program Flow-Switch/Case-
Multiple conditions
Sometimes a condition can have different alternatives
and you want to react to each case differently. In this
situation you can use a switch/case structure:

switch(expression) {

case label:
statements

case label:
statements

default:
statements
}

* the label can be an integer or a character


Program Flow-Switch/Case-
Multiple conditions
Sometimes a condition can have different alternatives
and you want to react to each case differently. In this
situation you can use a switch/case structure:
void setup(){
size(500,100);
background(255);
}

void draw(){
int mouseInput=mouseX/100;
println(mouseInput);
switch (mouseInput){
case 0:
fill(50);
break;
case 1:
fill(100);
break;
case 2:
fill(150);
break;
case 3:
fill(200);
break;
default:
fill(250);
break;
}
rect(mouseX,mouseY,20,20);
}
Processing-Methods
Methods are groups of code that perform a specific operation.

A method has a name that is used to call the method-initiate the operations with in the method
through out the program flow.

A method can have parameters that are passed to it and will effect the operations of the method
Parameter Data Type

Method Name Parameter Name

void drawPointer(int x, int y){

// The method commands come here


}
Processing-Methods
Methods are groups of code that perform a specific operation.

A method has a name that is used to call the method-initiate the operations with in the method
through out the program flow.

A method can have parameters that are passed to it and will effect the operations of the method

void setup(){
size(200,200);
ellipseMode(CENTER);
rectMode(CENTER);
}
void draw(){
background(200,200);
drawPointer(mouseX,mouseY);
}
void drawPointer(int x, int y){
ellipse(x,y,3,3);
rect(x-20,y-20,15,15);
rect(x+20,y-20,15,15);
rect(x-20,y+20,15,15);
rect(x+20,y+20,15,15);
}
Processing-Methods
Methods help us save time and energy by simplifying the program flow

size(500,500); void setup(){


int x = 10; size(500,500);
int y = 10; stairs(10,10,15);
for(int i=0; i<15; i++) stairs(100,200,13);
rect(x+(i*10),y,10,50); stairs(300,200,10 );
x = 100; }
y = 200;
for(int i=0; i<13; i++) void stairs(int x, int y, int nsteps){
rect(x+(i*10),y,10,50); for(int i=0; i<nsteps; i++)
x = 300; rect(x+(i*10),y,10,50);
y = 200; }
for(int i=0; i<10; i++)
rect(x+(i*10),y,10,50);
Processing-Functions
A function is a method that returns a value in addition to performing a set of operations.

Function Return Value Data type

Parameter Data Type

Method Name Parameter Name

int volume (int l, int w , int h){


int v=l*w*h;
return v;
}
Processing-Functions
A function is a method that returns a value in addition to performing a set of operations.

void setup(){
int boxLength=10;
int boxWidth=30;
int boxHieght=25;
int boxVolume=volume(boxLength,boxWidth,boxHieght);
println(boxVolume);
}

int volume(int l,int w ,int h){


int v=l*w*h;
return v;
}
Processing-Variable Scopes
The scope of a variable is the extent to which the variable is recognizable by the compiler within
the program flow.

A variable that is initiated inside a block- with in {} – is not recognizable for the block out

void setup(){
int boxLength=10;
int boxWidth=30;
int boxHieght=25;
int boxVolume=volume(boxLength,boxWidth,boxHieght);
println(boxVolume);
}

int volume(int l,int w ,int h){


int v=l*w*h;
return v;
}
Data Manipulation
When working with mathematical operators
and variables, it’s important to be aware of
the data types :
1. The combination of two integers will
always result in an int.
2. The combination of two floating-point
numbers will always result in a float.
3. The combination of an integer and a float
will always result in a float.

println(4/3); // Prints "1"


println(3/4); // Prints "0"
println(4.0/3); // Prints "1.3333334"
println(4/3.0); // Prints "1.3333334"
println(4.0/3.0); // Prints "1.3333334"
float a= 4/3; //Assigns 1. to a
println(a);
Data Manipulation

Data_Type Variable_Name = Value;

int peopleCount = 12;

float userName =“Nashid”;


Numerical Types:…………………………………..
int …,-5,-4,-3,-2,-1,0,1,2,3,4,5

float 14.5, 1.0, -5.15, -700.0

Non-Numerical Types:…………………………..
boolean true, false

char ‘a’, ‘F’, ‘%’

String “Nashid”, “Hello World”


Data Manipulation-Data Type Conversion

b = int(a);
int float

Boolean

char

String
Data Manipulation-Data Type Conversion

b = float(a);
float int

Boolean

String
Data Manipulation-Data Type Conversion

b = boolean(a);
Boolean float

int
Data Manipulation-Data Type Conversion

b = char(a);
char int
Data Manipulation-Data Type Conversion

b = str(a);
String int

float

Boolean
Data Manipulation-Data Type Conversion
int a = 7;
float b = 14.3;
String c = "Nashid";
char d = 'N';
boolean e= false;
float aa= float(a);
int bb=int(b);
String cc=str(a)+ "000" +str(b);
int dd = int(d);
float ddd=float(cc)*10;
int ee = int(e);
boolean eee= boolean(a);
println(aa);
println(bb);
println(cc);
println(dd);
println(ddd);
println(ee);
println(eee);
Data Manipulation-Data Type Conversion
-Functions-formatting numbers into strings:
nf(intValue, digits)
nf(floatValue, left, right)

light_Intensity = 1;
sensor_Code = 10;
light_Intensity_to_Str = nf(light_Intensity,5);
sensor_Code_to_Str = nf(sensor_Code,5);
sensor_Code_Light_Intensity=light_Intensity_to_Str+sensor_Code_to_Str;
println("Light Intensity= " + light_Intensity_to_Str);
println("Sensor Code= " + sensor_Code_to_Str);
println("Light Intensity + Sensor Code= " + sensor_Code_Light_Intensity);
Data Manipulation-Data Type Conversion
-Functions-formatting numbers into strings:
nf(intValue, digits)
nf(floatValue, left, right)

float light_Intensity = 125.4;


int sensor_Code = 1;
String light_Intensity_to_Str = nf(light_Intensity,4,5);
String sensor_Code_to_Str = nf(sensor_Code,5);
String sensor_Code_Light_Intensity=light_Intensity_to_Str+sensor_Code_to_Str;
println("Light Intensity= " + light_Intensity_to_Str);
println("Sensor Code= " + sensor_Code_to_Str);
println("Light Intensity + Sensor Code= " + sensor_Code_Light_Intensity);
Data Manipulation-String Data Type

Na s h i d Na b i a n
0 1 2 3 4 5 6 7 8 9 10 11 12
Data Manipulation-String Data Type
charAt()
Returns the character at the specified index

equals()
Compares a string to a specified object

indexOf()
Returns the index value of the first occurance of a character within the input string

length()
Returns the number of characters in the input string

substring()
Returns a new string that is part of the input string

toLowerCase()
Converts all the characters to lower case

toUpperCase()
Converts all the characters to upper case
Data Manipulation-String Data Type
String a="Room 004 Floor 05 PeopleCount 010";
String b;
char c;
int d;
//Room 004 Floor 05 PeopleCount 010
//012345678911111111112222222222333
// 01234567890123456789012
//charAt() Returns the character at the specified index
c=a.charAt(7);
println("character @ 8th Location="+c);
//indexOf() Returns the index value of the first occurance of a character within the input string
d=a.indexOf("Room");
println("Index of Occurance="+d);
//length() Returns the number of characters in the input string
//substring() Returns a new string that is part of the input string
b=a.substring(5,8);
println("Room="+b);
b=a.substring(15,17);
println("Floor="+b);
b=a.substring(a.length()-3);
println("People Count="+b);
//toLowerCase() Converts all the characters to lower case
b=a.toLowerCase();
println("All Lower Case="+b);
//toUpperCase() Converts all the characters to upper case
b=a.toUpperCase();
println("All Upper Case="+b);
Data Manipulation-Array Data Structure
An array is an ordered list of data.

It is possible to have an array of any type of data: integer, float, sting, etc.

We define an array using [ ] symbol

String[] day = {"Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday"};

day[0] Saturday
day[1] Sunday
day[2] Monday
day[3] Tuesday
day[4] Wednesday
day[5] Thursday
day[6] Friday
Arrays - Accessing Array Elements
Array Index starts at 0
so the first element has the index of 0 and the second has the index of 1 and so on

String[] day = {"Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday"};

println(day[3]);//printlines the forth element of the array which is thursday

day[0] Saturday
day[1] Sunday
day[2] Monday
day[3] Tuesday
day[4] Wednesday
day[5] Thursday
day[6] Friday
Array – Initiating an Array

dataType[] arrayName = new dataType[numberofElements];

String [] days = new String [7];

day[0] Saturday
day[1] Sunday
day[2] Monday
day[3] Tuesday
day[4] Wednesday
day[5] Thursday
day[6] Friday
Array - Assigning value to Array Elements

day[0]=“Sunday”

or

day = {"Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday"};

day[0] Saturday
day[1] Sunday
day[2] Monday
day[3] Tuesday
day[4] Wednesday
day[5] Thursday
day[6] Friday
Array - length
Returns the size of the array or the number of array elements as an integer number

String[] day = {"Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday"};

println(day.length());// prints the size of the array which is seven in this case

day[0] Saturday
day[1] Sunday
day[2] Monday
day[3] Tuesday
day[4] Wednesday
day[5] Thursday
day[6] Friday
Array-
Iterating between the members of an array in a for loop

String[] day = {"Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday"};


for(int i=0; i<day.length-1;i++){
println(day[i]);
}

day[0] Saturday
day[1] Sunday
day[2] Monday
day[3] Tuesday
day[4] Wednesday
day[5] Thursday
day[6] Friday
Array-subset(arrayName,startElement,Size)

Return a subset of the array that starts at the startIndex and has as many elements as the specified size

String[] days = {"Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday"};

String[] workingDays=subset(days,0,5);
for(int i=0; i<workingDays.length;i++){
println("working day = " + workingDays[i]);
}

String[] weekend=subset(days,5,2);
for(int i=0; i<weekend.length;i++){
println("Weekend = " + weekend[i]);
}
Array -1D and 2D arrays

int [] c = new int[10];


for(int i=0; i<10; i++){
c[i] = i * 2;
print(c[i]+" ");
}
//0 2 4 6 8 10 12 14 16 18
Array -1D and 2D arrays

int [][] c = new int[5][10];


for(int x=0; x<5; x++){
for(int y=0; y<10; y++){
c[x][y] = x*y;
print(c[x][y] + " " );
}
print("\n");
}
/*
0000000000
0123456789
0 2 4 6 8 10 12 14 16 18
0 3 6 9 12 15 18 21 24 27
0 4 8 12 16 20 24 28 32 36
*/
Array -1D and 2D arrays

int [][] c = new int[5][10];


for(int x=0; x<5; x++){
for(int y=0; y<10; y++){
c[x][y] = x*y;
print(c[x][y] + " " );
}
print("\n");
}
/*
0000000000
0123456789
0 2 4 6 8 10 12 14 16 18
0 3 6 9 12 15 18 21 24 27
0 4 8 12 16 20 24 28 32 36
*/
Array -1D and 2D arrays

int [][] c = new int[5][10];


for(int x=0; x<5; x++){
for(int y=0; y<10; y++){
c[x][y] = x*y;
print(nf(c[x][y],2) + " " );
}
print("\n");
}

/*
00 00 00 00 00 00 00 00 00 00
00 01 02 03 04 05 06 07 08 09
00 02 04 06 08 10 12 14 16 18
00 03 06 09 12 15 18 21 24 27
00 04 08 12 16 20 24 28 32 36
*/
Data Manipulation-
Connecting two arrays through index

int [] peopleCount={200,100,245,65,54,10,4};
String [] weekDay=new String[7];
weekDay[0]="Saturday";
weekDay[1]="Sunday";
weekDay[2]="Monday";
weekDay[3]="Tuesday";
weekDay[4]="Wednesday";
weekDay[5]="Thursday";
weekDay[6]="Friday";
for(int i=0; i<7; i++){
println("on " +weekDay[i]+" We will have "+ peopleCount[i]+" visitors");
}
Data Manipulation-Array Data Structure
Data Manipulation-concat()

Makes an array as the result of the addition of two innitial arrays. It is used in agglomaration of datasets that
are the same type into one dataset

int [] time1={1,2,3,4,5,6,7};
int [] time2={8,9,10,11,12};
int [] lightIntensity1={0,23,35,40,43,45,50};
int [] lightIntensity2={64,70,83,90,105};
int [] timeAll=concat(time1,time2);
int [] lightIntensityAll=concat(lightIntensity1,lightIntensity2);
for(int i=0;i<lightIntensityAll.length-1;i++)
{
println("Time= "+timeAll[i]+"....."+"Light Intensity= "+lightIntensityAll[i]);
}
Data Manipulation-expand()
increases the size of the array. By default it doubles the size of the array unless the new size is specified as
the second parameter of the function. This function is useful incases that the system is storing realtime data
in an array and at the time of writing the code we do not know how many elements will be stored. Instead of
assigning a huge size to the array at the time of initiation. we write the code so that the array adjusts its size
on demand during the running time and on the fly.
int pointCount;
int[] xPositions=new int[200];
int[] yPositions=new int[200];
boolean redrawPoints=false;
void setup(){
size(300,300);
background(255);
}
void draw(){
xPositions[pointCount]=mouseX;
yPositions[pointCount]=mouseY;
point(mouseX,mouseY);
if (pointCount==xPositions.length-1){
xPositions=(int[ ]) expand(xPositions,xPositions.length+100);//adds 100 elements to the array
yPositions=(int[ ]) expand(yPositions,yPositions.length+100);//adds 100 elements to the array
}
pointCount=pointCount+1;
if(redrawPoints==true){
if(pointCount<xPositions.length-1){
point(xPositions[pointCount],yPositions[pointCount]);
pointCount=pointCount+1;
}else{
exit();
}
}
}
void keyPressed(){
background(255);
redrawPoints=true;
pointCount=0;
}
Data Manipulation-Array Data Structure
Data Manipulation-Manipulating Numeric Data
a+b
a-b
a*b
a/b
if a and b are integer the result of the division will be an integer
a 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

a/4 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3

a%b
Returns the remainder of the division of a by b
This operation is used to modulate an increasing or decreasing value
a 0 1 2 3 4 5 6 7 8 9

a%4 0 1 2 3 0 1 2 3 0 1
Data Manipulation-Manipulating Numeric Data

Making a two dimentional matrix from one dimensionally distributed ( increasing or


decreasing data):
x Coordinate = index%5
0 1 2 3 4

Shape Index = 16
0 0 1 2 3 4
y Coordinate = index/5

x Coordinate = 1 = index%5

y Coordinate= 3 = index/5
1 5 6 7 8 9

2 10 11 12 13 14

3 15 16 17 18 19
Regulating by X : To regulate an increasing/decreasing factor by X you should divide it by X
while X is an integer so the result of the division will be an integer to.

for(int i=0; i<20; i++){


int x = i/2; // it always gives you an integer
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9

for(int i=0; i<20; i++){


int x = i/3;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6

for(int i=0; i<20; i++){


int x = i/4;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
Regulating by X, Moving along the Regulation by Y : To regulate an increasing/decreasing
factor by X you should divide it by X while X is an integer so the result of the division will be
an integer to. To move along the regulation by Y you should add y to the regulated factor
before dividing it by X
for(int i=0; i<20; i++){
int x = (i+1)/2;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10

for(int i=0; i<20; i++){


int x = (i+2)/2;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10

for(int i=0; i<20; i++){


int x = i/4;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
Restricting by X: To restrict an increasing/decreasing factor by X you should modulate it by X
while X is an integer so the result of the modulation will be an integer between 0 and X-1

for(int i=0; i<20; i++){


int x = i%2;// gives you an integer which is the remainder of the division of i by 2 (0 or 1)
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

for(int i=0; i<20; i++){


int x = i%3;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1

for(int i=0; i<20; i++){


int x = i%4;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3
Restricting by X, moving along the restriction by Y: To restrict an increasing/decreasing factor
by X you should modulate it by X while X is an integer so the result of the modulation will be an
integer between 0 and X-1. To move along the restriction by Y, you should add Y to the restricted
factor(i) before modulating it by X
for(int i=0; i<20; i++){
int x = (i+1)%4;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0

for(int i=0; i<20; i++){


int x = (i+2)%4;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1
First, Regulating by X, then Restricting by Y:
for(int i=0; i<20; i++){
int x = (i/2)%2;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 // i/2
//0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 //%2

for(int i=0; i<20; i++){


int x = (i/3)%2;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 // i/3
//0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 0 0 // %2

for(int i=0; i<20; i++){


int x = (i/4)%2;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
//0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0
First, Regulating by X, then Restricting by Y:
for(int i=0; i<20; i++){
int x = (i/2)%4;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 // i/2
//0 0 1 1 2 2 3 3 0 0 1 1 2 2 3 3 0 0 1 1 //%4
First, Restricting by X, then Regulating by Y:
for(int i=0; i<20; i++){
int x = (i%4)/2;
print(x);
};
//0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 // i%4
//0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1// /2
for(int i=0; i<20; i++){
int y = i%2;
point(i*10, 50+y*10);
};

beginShape();
noFill();
for(int i=0; i<20; i++){
int y = i%2;
vertex(i*10, 50+y*10);
};
endShape();
for(int i=0; i<25; i++){
rect((i % 5) * 20,(i / 5) * 20, 10, 10);
}
//i = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...
// X= 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 ...
// Y= 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 ...
Incremental Difference-mapping numbers
1. How can you go from number 65 to number 203 in 100 Step?

65 203

0 100
1. Find the difference between the two extreme :

Difference =Starting Point – End Point =100-0=100


Difference =Starting Point – End Point =203-65=138
2. Divide to the number of steps to find the magnitude of change in each step:
Magnitude of Step: ( Starting Point – End Point)/Number of Steps =

(203-65)/(100-0)=1.38
3. The amount that is added at each step is :
Differential that is added at step i:

i* Magnitude of Step =i* (( Starting Point – End Point)/Number of Steps)= i*1.38


4. The resulted value at step i :
Starting Point + i*Magntude of Step =

Starting Point + i* (( Starting Point – End Point)/Number of Steps)= 203 + (i*1.38)


Incremental Difference-mapping numbers
350 input=550 Light 800

45 Output=105 Degree 180

output Difference =Starting Point – End Point =180-45=135


input Difference =Starting Point – End Point =800-350=450
2. Divide to the number of steps to find the magnitude of change in each step:
Magnitude of Step: input( Starting Point – End Point)/ output( Starting Point – End Point)/ =

(180-45)/(800-350)=135/450=0.3
3. The amount that is added at each step is :
Differential that is added :

(input Current Amount-input Min Amount)* Magnitude of Step = (550-350)*0.3


4. The resulted value at step i :
Output Starting Point + Differential that is added = 45+(200*0.3)=45+60=105
Incremental Difference-mapping numbers
350 input=550 Light 800

45 Output=105 Degree 180

float Output=map(Input, Min Input , Max input , Min Output , Max Output);

float Output=map(550,350,800,45,180);

1. `
Manipulating Numeric Data-Functions

min()
Syntax
min(value1, value2)
min(value1, value2, value 3)
min(array)

int d = min(5, 9); // Sets "d" to 5

int e = min(-4, -12); // Sets "e" to -12

float f = min(12.3, 230.24); // Sets "f" to 12.3

int[] list = { 5, 1, 2, -3 };

int h = min(list);

// Sets "h" to -3
Manipulating Numeric Data-Functions
Processing-Input
Mouse

Keyboard

Time

image

Video
Processing input
Audio

Data from File

Wii controller

Kinect 3D camera

Input from Arduino-Sensed Data


Processing-Output

Audio

Video
Interactive Screen
Image-
Graphics
Processing output Save to File
Text

Output to physical space via arduino


Processing-Mouse Input-Location

mouseX
mouseY
Processing-Mouse Input-Location

mouseX
mouseY

void setup(){
}
void draw(){
int x=mouseX;
int y=mouseY;
println("X Coordinate of Mouse Position = "+x);
println("Y Coordinate of Mouse Position = "+y);
}
Processing-Mouse Input-Location

mouseX
mouseY

void setup(){
}
void draw(){
int x=mouseX;
int y=mouseY;
ellipse(x,y,20,20);
}
Processing-Mouse Input-Location

mouseX
mouseY

void setup(){
}
void draw(){
int x=mouseX;
int y=mouseY;
ellipse(x,y,20,20);
}
Processing-Mouse Input-Mouse Click

void mouseClicked(){
}

void setup(){
}
void draw(){
}

void mouseClicked(){
println("Clicked At: "+ mouseX+" , "+mouseY);
}
Processing-Mouse Input-Mouse Click

void mouseClicked(){
}
void setup(){
}
void draw(){
}

void mouseClicked(){
if(mouseX>50)
ellipse(mouseX,mouseY,20,20);
if(mouseX<50)
rect(mouseX,mouseY,20,20);
}
Processing-Mouse Input-Mouse Click

void mouseClicked(){
}

void setup(){
}
void draw(){
}

void mouseClicked(){
ellipse(mouseX,mouseY,20,20);
}
Processing-Mouse Input-Mouse Click

void mouseClicked(){
}
void setup(){
}
void draw(){
}

void mouseClicked(){
background(255,255,255);
if(mouseX>50)
ellipse(mouseX,mouseY,20,20);
if(mouseX<50)
rect(mouseX,mouseY,20,20);
}
Processing-Mouse Input-Mouse Drag

void mouseDragged(){
}
void setup(){
background(255,255,255);
}
void draw(){
}

void mouseDragged(){
background(255,255,255);
if(mouseX>50)
fill(255);
if(mouseX<50)
fill(0);
ellipse(mouseX,mouseY,20,20);
}
void draw()
{
}
void mousePressed()
{
rect(mouseX,mouseY, 10,10);
}

void draw()
{
}
void mouseDragged()
{
rect(mouseX,mouseY, 10,10);
}
Processing-Mouse Input
Processing-Keyboard Input

void keyPressed(){
}
int value = 0;
draw() {
fill(value);
rect(25, 25, 50, 50);
}
void keyPressed()
{
if(key == '0') {
value = 255;
} else {
value = 0;
}
}
Processing-Keyboard Input
Processing-Time Input-Absolute Time

hour() minute() second()


year() month() day()

void setup(){
}
void draw() {
int Year=year();
int Month=month();
int Day=day();
int Hour=hour();
int Minute=minute();
int Second=second();
println("Absolute Time : "+ Year + "/" + Month + "/" + Day + "," + Hour + ":" + Minute + ":" +
Second);
}
Processing-Time Input-Relative Time
hour() minute() second()
year() month() day()

int Year_Origin=year();
int Month_Origin=month();
int Day_Origin=day();
int Hour_Origin=hour();
int Minute_Origin=minute();
int Second_Origin=second();
void setup(){
}
void draw() {
int Year=year()-Year_Origin;
int Month=month()-Month_Origin;
int Day=day()-Day_Origin;
int Hour=hour()-Hour_Origin;
int Minute=minute()-Minute_Origin;
int Second=second()-Second_Origin;
println("This Program has been Running for : "+ Year + " years and " + Month + " months and
" + Day + " days and " + Hour + " hours and " + Minute + " minutes and " + Second + "
seconds.");
}
Processing-Time Input-Timebase Operation
Animation
int Hour_Origin=hour();
int Minute_Origin=minute();
int Second_Origin=second();
void setup(){
background(255);
}
void draw() {
int Hour=hour()-Hour_Origin;
int Minute=minute()-Minute_Origin;
int Second=second()-Second_Origin;
int RunTime=Hour*60*60+Minute*60+Second;
if(RunTime%4>1)//2,3
fill(255);
if(RunTime%4<=1)//0,1
fill(0);
rect(50,50,25,25);
}
Processing-Time Input-Timebase Operation
Interaction
int Hour_Origin=hour();
int Minute_Origin=minute();
int Second_Origin=second();
int r=5;
void setup(){
size(300,300);
background(255);
fill(255,0,0,0);
}
void draw() {
background(255);
if(mousePressed){
int Hour=hour()-Hour_Origin;
int Minute=minute()-Minute_Origin;
int Second=second()-Second_Origin;
int RunTime=Hour*60*60*1000+Minute*60*1000+Second*1000;
fill(255,0,0,RunTime/25);
r=r+1;
println(r);
ellipse(width/2,height/2,r,r);
}
else{
r=5;
fill(255,0,0,0);
ellipse(width/2,height/2,r,r);
}
}
void mousePressed(){
Hour_Origin=hour();
Minute_Origin=minute();
Second_Origin=second();
}
Processing-Time Input-Timebase Operation
Interaction
int Second_Origin=second();
int r=5;
int Sum=0;
int LU,LB,RU,RB=0;
void setup(){
size(302,302);
stroke(0);
strokeWeight(5);
fill(255,255,255);
rect(1,1,150,150);
rect(151,1,150,150);
rect(1,151,150,150);
rect(151,151,150,150);
}
void draw() {
int RunTime=second()-Second_Origin;
if ((Sum<4)&&(RunTime>2))
{
println("You Lost");
println();
println();
println();
Second_Origin=second();
fill(255,255,255);
rect(1,1,150,150);
rect(151,1,150,150);
rect(1,151,150,150);
rect(151,151,150,150);
Sum=0;
LU=0;
RU=0;
LB=0;
RB=0;
}
if ((Sum==4)&&(RunTime<2000))
{
println("You Win");
println();
println();
println();
Processing-Time Input-RunTime
millis()

void draw(){
println("This program has been Running for "+ millis()/1000 + " Seconds");
}
Processing-Time Input
Processing-Using Image Files
Processing can load images, display them on the
screen, and change their size, position, opacity, and tint.

You can load gif , png and jpg images in processing

Images are stored in variables of the Plmage data type.

Before displaying an image, it’s necessary to first load it


with the loadlmage () function.

For the image to load, it must be in the data folder of the


current program. Add the image by selecting the “Add
File” option in the Sketch menu of the Processing
environment.

As a shortcut, you can also drag and drop an image to


the Processing window.
Processing-Using Image Files
You can display an image with image() function:

image(name, x, y) ;
//Place the top corner of the image at (x,y) and displays the image at its original size

image(name, x, y, width, height) ;


//Place the top corner of the image at (x,y) and displays the image with mentioned width and height

Images are colored with the tint ( ) function. This function is used the same way as fill() and stroke (), but
it affects only images:

tint(gray) ;
tint(gray, Transparency) ;
tint(value1, value2, value3) ;
tint(value1, value2, value3, Transparency) ;
Processing-Using Image Files
PImage MyImage; //Innitiating a PImage Variable
size(800,300);
// Image must be in the sketch's "data" folder
MyImage=loadImage("Test.jpg"); // Loading the Image
//image(img, 0, 0);
image(MyImage, 0,0, 200, 200);//image(name,x, y, width, height);
tint(152,0,0);//tint(valuel, value2, value3);
image(MyImage, 200,0, 200, 200);
tint(70,70,152,200);//tint(value1, value2, value3,Transparency);
image(MyImage, 400,0, 200, 200);
tint(70,70,152,100);//tint(value1, value2, value3,Transparency);
image(MyImage, 600,0, 200, 200);
Processing-Using Image Files
PImage img;
size(400,200);
img = loadImage("Test.jpg");
background(255);
tint(255, 100);
// Draw the image 20 times moving each to the right
for (int i = 0; i <=20; i++) {
image(img, i*10, 0,200,200);
}
PixelBase Manipulation of Images-
Getting and setting pixel colors
In Processing anything that appears in the
display window is interpreted as a group of
pixels.

Processing gives you access to each and


everyone of these pixels.

You are able to manipulate graphics and visual


constructs via manipulating their pixels.
Processing-PixelBase Manipulation of Images
In Processing anything that appears in the
display window is interpreted as a group of
pixels.

Processing gives you access to each and


everyone of these pixels.

every pixel has a position consisting of X and Y


coordinates and a color attribute
Processing-PixelBase Manipulation of Images
You can read the color attribute of a pixel

color pixelColor;

pixelColor=get(x,y);
Processing-PixelBase Manipulation of Images
You can read the color attribute of a pixel and assign it to a variable of the data type: color

color pixelColor;

pixelColor=get(x,y);

The pixel color attribute is of color data type. color data type has three parts: Red, Green and
Blue Value.

These values are integers between 0 and 255. You can get access to these values with the
following functions:

int RedValue=red(pixelColor);
int GreenValue=green(pixelColor);
int BleValue=blue(pixelColor);
Processing-PixelBase Manipulation of Images
You can also set the color of a pixel:

set(x,y,pixelColor);

in set function the first two parameters are integer type and specify the coordinate of the pixel in
the display window and the third parameter specifies the color of the pixel. The third parameter
should be of color data type. You can make a color with passing three integers to color() function
and then assign it to a pixel using a set function.

int RedColor=125;
int GreenColor=200;
int BlueColor=100;
color pixelColor=color(RedColor,GreenColor,BlueColor);
set(x,y,pixelColor);
Processing-Pixel Base Manipulation of Images
Why is pixel manipulation important?Later on , we
are going to work with video both as input and
output.

we will use video camera to figure out presence of


moving subject as well as the number of subjects in
the video frame. In processing video is a series of
images, as a result accessing the pixels of the
image enables us to analyze the video feed through
analyzing the changes to each pixel from one frame
to another frame to detect movement and change
in the environment.

On the other hand video can be used as an out put


to animate the space as a response to a sensed
situation. You can manipulate the pixels of a live
feed video or previously recorded video as a
response to a contextual stimuli and project it on
surfaces to transform the architectural or urban
surfaces to animated responsive ones.
Image Processing

size(400,400);
for(int x=0; x<width; x++)
for(int y=0; y<height; y++){
float r = random(255);
float g = random(255);
float b = random(255);
stroke(color(r,g,b));
point(x,y);
}
Image Processing

size(400,400);
PImage MyImage = createImage(width, height, RGB);
for(int x=0; x<width; x++)
for(int y=0; y<height; y++){
float r = random(255);
float g = random(255);
float b = random(255);
set(x,y,color(r,g,b));
}
Image Processing

size(400,400);
PImage MyImage = createImage(width, height, RGB);
for(int x=0; x<width; x++)
for(int y=0; y<height; y++){
float r = random(255);
float g = random(255);
float b = random(255);
set(x,y,color(r,g,b));
}
color c= get(100,100);
println(red(c));
Image Processing

PImage myImage; //define an image object


myImage = loadImage(“test.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image
Image Processing

PImage myImage; //define an image object


myImage = loadImage(“test.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image
filter(GRAY); // all pixels get the average value of their rgb
Image Processing

PImage myImage; //define an image object


myImage = loadImage(“test.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image
filter(THRESHOLD, .45); // every pixel below .45 becomes black
Image Processing

PImage myImage; //define an image object


myImage = loadImage(“test.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image
filter(INVERT); // all pixels get the opposite value of their rgb (i.e. 255-r)
Image Processing

PImage myImage; //define an image object


myImage = loadImage("Toco Toucan.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image
filter(POSTERIZE, 3); // limits each channel of the image to 3 colors
Image Processing

PImage myImage; //define an image object


myImage = loadImage("Toco Toucan.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image
filter(BLUR, 3); // executes a Guassian blur with radius 3.Changing it to 6 make it more blurred
Image Processing

PImage myImage; //define an image object


myImage = loadImage("Toco Toucan.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image

for(int y=0; y<myImage.height; y++) //for all pixels in the y direction


for(int x=0; x<myImage.width; x++){ //for all pixels in the x direction
color myPixel = get(x,y); //get a pixel's color
int r = int(red(myPixel)); //extract the red value
int g = int(green(myPixel)); //extract the green value
int b = int(blue(myPixel)); //extract the blue value
color inverse = color(255-r,255-g,255-b); //make a color by inverting (255-value)
set(x,y,inverse); //set the pixel’s color in the image
}
Image Processing

PImage myImage; //define an image object


myImage = loadImage(“test.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image

for(int y=0; y<myImage.height; y++) //for all pixels in the y direction


for(int x=0; x<myImage.width; x++){ //for all pixels in the x direction
color myPixel = get(x,y); //get a pixel's color
int r = int(red(myPixel)); //extract the red value
int g = int(green(myPixel)); //extract the green value
int b = int(blue(myPixel)); //extract the blue value
color inverse = color(255-r,255-g,255-b); //make a color by inverting (255-value)
set(x,y,inverse); //set the pixel’s color in the image
}
save("Toco Toucan_inverted.jpg"); // save the image as a file
Image Processing

PImage myImage; //define an image object


myImage = loadImage(“test.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image

for(int y=0; y<myImage.height; y++) //for all pixels in the y direction


for(int x=0; x<myImage.width; x++){ //for all pixels in the x direction
color myPixel = get(x,y); //get a pixel's color
int r = int(red(myPixel)); //extract the red value
int g = int(green(myPixel)); //extract the green value
int b = int(blue(myPixel)); //extract the blue value
color inverse = color(255-r,255-g, b); //make a color by inverting (255-value)
set(x,y,inverse); //set the pixel’s color in the image
}
Image Processing

PImage myImage; //define an image object


myImage = loadImage(“test.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image

for(int x=2; x<width-2; x++) //for all rows


for(int y=2; y<height-2; y++){ //for all columns
color c = get(x,y);
//make sure the values fall between 0-255
int xx = x+int(random(-4,4));
int yy = y+int(random(-4,4));
set(xx,yy,c); //color the pixel
}
Image Processing

PImage myImage; //define an image object


myImage = loadImage(“test.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image

for(int x=2; x<width-2; x=x+6) //for all rows


for(int y=2; y<height-2; y=y+6){ //for all columns
color c = get(x,y);
//make sure the values fall between 0-255
int xx = x+int(random(-4,4));
int yy = y+int(random(-4,4));
fill(c);
noStroke();
rect(xx,yy,6,6);
}
Image Processing

PImage myImage; //define an image object


myImage = loadImage(“test.jpg"); //load it
size(myImage.width,myImage.height); //size it to fit the window
image(myImage, 0,0); //display the image

for(int x=2; x<width-2; x=x+15) //for all rows


for(int y=2; y<height-2; y=y+15){ //for all columns
color c = get(x,y);
//make sure the values fall between 0-255
int xx = x+int(random(-4,4));
int yy = y+int(random(-4,4));
fill(c);
noStroke();
rect(xx,yy,15,15);
}
Code by Kostas Terzidis
Image Processing-
PixelAnalysis

PImage MyImage = loadImage("Map.jpg");


size(MyImage.width, MyImage.height);
image(MyImage,0,0);

for(int x=2; x<width-2; x++) //for all rows


for(int y=2; y<height-2; y++){ //for all columns
color c = get(x,y);
float r = red(c); //create a formula here
float g = green(c); //create a formula here
float b = blue(c); //create a formula here
//Select range of colors that represent vegetation
if(r>11 && g>26 && b>19 && r<117 && g<133 && b<96){
set(x,y,color(255)); //color the pixel
}
}
Code by Kostas Terzidis
Image Processing-
PixelAnalysis
PImage MyImage = loadImage("Map.png");
size(MyImage.width, MyImage.height);
image(MyImage,0,0);

int k=0; //counter to count vegetation


for(int x=2; x<width-2; x++) //for all rows
for(int y=2; y<height-2; y++){ //for all columns
color c = get(x,y);
float r = red(c); //create a formula here
float g = green(c); //create a formula here
float b = blue(c); //create a formula here
//Select range of colors that represent vegetation
if(r>11 && g>26 && b>19 && r<117 && g<133 && b<96){
set(x,y,color(255)); //color the pixel
k++; //count the green pixels
}
}
print(k*1./(width*height) ); // 0.41729397
Code by Kostas Terzidis

int [] xd = {0,1,1,1,0,-1,-1,-1,0};
int [] yd = {1,1,0,-1,-1,-1,0,1,1};
PImage MyImage = loadImage("MapFootPrint.jpg");
size(MyImage.width,MyImage.height);
image(MyImage, 0,0);
int [][] MyCopy = new int[width][height];
int [] xd = {0,1,1,1,0,-1,-1,-1,0};
int [] yd = {1,1,0,-1,-1,-1,0,1,1};
PImage MyImage = loadImage("MapFootPrint.jpg");
size(MyImage.width,MyImage.height);
image(MyImage, 0,0);
int [][] MyCopy = new int[width][height];
for(int x=1; x<width-1; x++)
for(int y=1; y<height-1; y++){ Code by Kostas Terzidis
int b=0;
int a=0;
//checking the pixel neiborhood
for(int i=0; i<8; i++){
if(brightness(get(x+xd[i],y+yd[i]))<100)
b++;
if(brightness(get(x+xd[i],y+yd[i]))<100 &&
brightness(get(x+xd[i+1],y+yd[i+1]))>100)
a++;
}
// filling the copy
if((b>=2 && b<=6) || a==1 )
MyCopy[x][y]=1;
else
MyCopy[x][y]=0;
}
//Paint the screen
for(int x=1; x<width-1; x++)
for(int y=1; y<height-1; y++){
if(MyCopy[x][y]==1)
set(x,y,color(0,0,0));
else
set(x,y,color(255,255,255));
}
int [] xd = {0,1,1, 1, 0,-1,-1,-1,0};
int [] yd = {1,1,0,-1,-1,-1, 0, 1,1};
PImage MyImage;
int [][] MyCopy;
void setup(){
MyImage = loadImage("MapFootPrint.jpg");
size(MyImage.width,MyImage.height);
MyCopy = new int[width][height];
image(MyImage, 0,0);
filter(THRESHOLD);
initialize();
for(int g=0; g<35; g++) skeletonize();
save("MyImage.jpg");
}
void skeletonize(){
for(int x=1; x<width-2; x++)
for(int y=2; y<height-1; y++){
//if(getBinary(x,y)==0){
int b=0;
int a=0;
for(int i=0; i<8; i++){
if(getBinary(x+xd[i],y+yd[i])==1)b++;
if(getBinary(x+xd[i],y+yd[i])==0 &&
getBinary(x+xd[i+1],y+yd[i+1])==1) a++;
}
int a2=0;
for(int i=0; i<8; i++)
if(getBinary(x+xd[i],y+1+yd[i])==0 &&
getBinary(x+xd[i+1],y+1+yd[i+1])==1) a2++;
int c2 = getBinary(x,y+1) * getBinary(x+1,y) * getBinary(x-1,y);
int a3=0;
for(int i=0; i<8; i++)
if(getBinary(x+1+xd[i],y+yd[i])==0 &&
getBinary(x+1+xd[i+1],y+yd[i+1])==1) a3++;
int c3=getBinary(x,y+1) * getBinary(x+1,y) * getBinary(x,y-1);
if((2<=b && b<=6) &&
a==1 &&
(c2==0 || a2!=1) &&
(c3==0 || a3!=1))
if(getBinary(x,y)==1)MyCopy[x][y]=0;
}
update();
}
void update(){
for(int x=1; x<width-1; x++)
for(int y=1; y<height-1; y++)
if(MyCopy[x][y]==1)
set(x,y,color(0,0,0)); //black
else
set(x,y,color(255,255,255)); //white
}
void initialize(){
for(int x=0; x<width; x++)
for(int y=0; y<height; y++)
MyCopy[x][y] = getBinary(x,y);
}
int getBinary(int x,int y){
if(brightness(get(x,y))>128)
return 0;
else
return 1;
}

Code by Kostas Terzidis


input
Reading data sets from file loadStrings(textfilename);
from File
save()
File based Output as a raster image)
Input/Output saveFrame()

beginRecord()
Output to output as a vector image
File endRecord()

createWriter(textfilename)
output as text file of data
flush();
sets
close();
Processing-Pattern Making
Save Graphics to Raster File

save(filename);
saveFrame();

These two functions save files in the same directory as the processing sketch itself
Processing-Randomness-Pattern Making
Saving Graphics to Image File

size(400,400);
noStroke();
background(50,200,200);
for(int x=0;x<400;x=x+10){
for(int y=0;y<400;y=y+10){
fill(int(random(255)));
int dimension=int(random(3,10));
ellipse(x,y,dimension,dimension);
}
}
save("Random_Pattern.jpg");
Processing-Randomness-Pattern Making
Saving Graphics to File-Multiple Frames
void setup(){
size(400,400);
noStroke();
background(50,200,200);
frameRate(1);
}
void draw(){
background(50,200,200);
for(int x=0;x<400;x=x+10){
for(int y=0;y<400;y=y+10){
fill(int(random(255)));
int dimension=int(random(3,10));
ellipse(x,y,dimension,dimension);
}
}
save("Random_Pattern"+frameCount+".jpg");
//or saveFrame();
}
Processing-Pattern Making
Save Graphics to Vector File
beginRecord(fileFormat,fileName);
endRecord();
import processing.pdf.*; // or import processing.dxf.*;
void setup() {
size(400, 400);
beginRecord(PDF, "everything.pdf"); //or beginRecord(DXF, "everything.pdf");
}
void draw() {
rect(mouseX, mouseY,10,10);
}
void keyPressed() {
if (key == ' ') {
endRecord();
exit(); }
}
Processing-
Writing Datasets to File
createWriter(textfilename);
PrintWriter output;
void setup() {
// Create a new file in the sketch directory
output = createWriter("positions.txt");
}
void draw() {
point(mouseX, mouseY);
output.println(mouseX+ ","+mouseY); // Write the coordinate to the file
}
void keyPressed() {
output.flush(); // Writes the remaining data to the file
output.close(); // Finishes the file
exit(); // Stops the program
}
Processing-
Reading Datasets from File
loadStrings(textfilename);
int i=0;
public String [] lines;
void setup(){
lines= loadStrings("positions.txt");//this file should be in the same directory as the processing sketch
println("there are " + lines.length + " lines");
for (int i=0; i < lines.length; i++) {
println(lines[i]);
}
background(255);
}
void draw(){
if(i>lines.length) exit();
String[]pointPosition = split(lines[i],',');
println("ok");
int x = int(pointPosition[0]);
int y = int(pointPosition[1]);
point(x,y);
delay(250);
i=i+1;
}
Data Manipulation-
Exporting Data and Graphics
Processing-
Runtime Memory-Tracking Attributes Using
Arrays

void setup(){
size(400,400);
for(int i=0; i<100 ; i++){
float px=random(0,400);
float py=random(0,400);
rect(px,py,5,5);
}
}
void draw(){
}
Processing-
Runtime Memory-Tracking Attributes Using
Arrays

float[] px=new float[100];


float[] py=new float[100];
void setup(){
size(400,400);
for(int i=0; i<100 ; i++){
px[i]=random(0,400);
py[i]=random(0,400);
rect(px[i],py[i],5,5);
}
}
void draw(){
}
Processing-
Runtime Memory-Tracking Attributes Using
float[] px=new float[100];
float[] py=new float[100];
Arrays
void setup(){
size(400,400);
for(int i=0; i<100 ; i++){
px[i]=random(0,400);
py[i]=random(0,400);
rect(px[i],py[i],5,5);
}
}
void draw(){
background(200);
for( int i=0;i<100;i++){
if(dist(mouseX,mouseY,px[i],py[i])<20)
stroke(255,0,0);
else
stroke(0,0,0);
rect(px[i],py[i],5,5);
}
}

void mouseDragged(){
for( int i=0;i<100;i++){
if(dist(mouseX,mouseY,px[i],py[i])<20){
px[i]=mouseX;
py[i]=mouseY;
}
}
}
Runtime Memory-Tracking Attributes Using
float [] px;
Arrays
float [] py;
void setup(){
makePolygon(7);
}
void makePolygon(int n){
px = new float[n+1];
py = new float[n+1];
float angle = 2 * PI / n;
beginShape(POLYGON);
for(int i=0; i<px.length; i++){
px[i] = 50. + 30. * sin(angle*i);
py[i] = 50. + 30. * cos(angle*i);
vertex(px[i],py[i]);
}
endShape();
}
void draw(){
background(200);
beginShape(POLYGON);
for(int i=0; i<px.length; i++)
vertex(px[i],py[i]);
endShape();
}
void mouseDragged(){
for(int i=0; i<px.length; i++)
if(dist(mouseX,mouseY,px[i],py[i])<10){
px[i] = mouseX;
py[i] = mouseY;
}
}
Processing-Randomness

random(parameter);
random(min,max);

void setup(){
frameRate(1);
}
void draw(){
float x=random(0,100);
float y=random(0,100);
println("X,Y= "+x+" , "+y);
}
Processing-Poetics
Diagram by Kostas Terzidis
of Randomness

1. A point with static attributes

2. A point with parametric attributes

3. A point with random location:


Vagueness in attributes

4. A point with randomness of existence


Processing-Randomness

random(high);
random(low,high);

void setup(){
}
void draw(){
float x=random(0,100);
float y=random(0,100);
println("X,Y= "+x+" , "+y);
int pointX=int(x);
int pointY=int(y);
point(pointX,pointY);
}
Randomness
1. Computer programs can generate random patterns
2. The random( ) function is used to create unpredictable values within the range specified by its
parameters.

random(high);
random(low, high) ;
3. When one parameter is passed to the function, it returns a float from zero up to –but not including the
value of the parameter. For example; random(5.0) can return a float number between 0 and 5, including
zero but not 5.
4. If two parameters are used, the function returns a value between the two parameters. Running
random( -5.0, 10.2) returns values from -5.0 up to 10.2
Randomness
1. Computer programs can generate random patterns
2. The random( ) function is used to create unpredictable values within the range specified by its
parameters.

random(high);
random(low, high) ;
3. When one parameter is passed to the function, it returns a float from zero up to –but not including the
value of the parameter. For example; random(5.0) can return a float number between 0 and 5, including
zero but not 5.
4. If two parameters are used, the function returns a value between the two parameters. Running
random( -5.0, 10.2) returns values from -5.0 up to 10.2

for (int i = 1; i<11; i++)


{
print( "Try Number " + i + "= ");
println(random(2));
}
Randomness
1. Computer programs can generate random patterns
2. The random( ) function is used to create unpredictable values within the range specified by its
parameters.

random(high);
random(low, high) ;
3. When one parameter is passed to the function, it returns a float from zero up to –but not including the
value of the parameter. For example; random(5.0) can return a float number between 0 and 5, including
zero but not 5.
4. If two parameters are used, the function returns a value between the two parameters. Running
random( -5.0, 10.2) returns values from -5.0 up to 10.2

for (int i = 1; i<11; i++)


{
print( "Try Number " + i + "= ");
println(random(-5.0,10.2));
}
Randomness
1. Because the numbers returned from random( ) are not predictable, each time the program is run, the
result is different.
2. The numbers from this function can be used to generate random graphical patterns and compositions
smooth ();
strokeWeight(10);
stroke(0,130);
for (int i=0; i<5;i++)
{
line(0, random(100), 100, random(100));
}
Randomness
1. The version of random() with two parameters provides more control over the results of the function.
The previous example has been modified so the lines always progress from the upper-left to the lower-
right, but the precise position is a chance operation.
2. Storing the results of random ( ) into a variable makes it possible to use the value more than once in the
program.
smooth ();
strokeWeight(10);
stroke(0,130);
float r;
for (int i=0; i<5;i++)
{
r = random(5, 45);
stroke(r * 5.6, 230);
line(0, r, 100, random(55, 95));
}
Randomness
1. Using random() within a for structure is an easy way to generate random numbers.
background(0);
stroke(255, 60);
for (int i = 0; i<50; i++) {
float r = random(10);
strokeWeight(r) ;
float offset = r * 20;
line(i-20,100, i+offset, 0);
}
Randomness
1. To use random values to determine the flow of the program, you can place the random ( ) function in a
relational expression. In the example below, either a line or an ellipse is drawn, depending on whether
the result of the random() function is less than 50 or greater than or equal to 50, respectively.
float r = random(100);
if (r < 50.0) {
line(0,0,100,100);
} else {
ellipse(50, 50, 75, 75);
}
Randomness
1. In the example below, , between 1 and 50 vertical lines are drawn according to the result of the
random ( ) function that is passed as a part of the test condition of a for loop

int num = int(random(50)) + 1;


for (int i = 0; i < num; i++) {
line(i * 2, 0, i * 2, 100);
}
Processing-Randomness-Pattern Making

size(400,400);
noStroke();
background(50,200,200);
for(int x=0;x<400;x=x+10){
for(int y=0;y<400;y=y+10){
fill(int(random(255)));
int dimension=int(random(3,10));
ellipse(x,y,dimension,dimension);
}
}
Processing-Controlled Randomness
void setup(){
background(255);
}
void draw(){
background(255);
for(int i=0; i<1000;i++){
int x=int(random(0,100));
int y=int(random(0,100));
point(x,y);
} void setup(){
} background(255);
}
void draw(){
background(255);
for(int i=0; i<100;i++){
int x=int(random(-25,25));
int y=int(random(-25,25));
if (pow(x*x+y*y,0.5)<25)
point(mouseX+x,mouseY+y);
}
}
Processing-Randomness-Pattern Making
Controlled Randomness
void setup(){
size(400,400);
noStroke();
background(50,200,200);
frameRate(1);
}
void draw(){
background(50,200,200);
for(int x=5;x<400;x=x+15){
for(int y=5;y<400;y=y+15){
fill(int(random(255)));
int dimensionFactor=int(random(3,10));
int scaleFactor=int(1+random((x+y)/200.0));

ellipse(x,y,dimensionFactor*scaleFactor,dimens
ionFactor*scaleFactor);
}
}
}
Processing-Randomness-Pattern
int num = 3000;
Making
int [] px = new int[num];
int [] py = new int[num];
Controlled Randomness
void setup(){
for(int i=0; i<num; i++){
px[i] = (int)random(100);
py[i] = (int)random(100);
}
}
void draw(){
background(200);
for(int i=0; i<num; i++){
px[i] = px[i] + int(random(-2,2));
py[i] = py[i] + int(random(-2,2));
constrain(px[i],0,100);
constrain(py[i],0,100);
point(px[i],py[i]);
}
}
Processing-Randomness-Pattern
int num = 3000;
Making
int [] px = new int[num];
int [] py = new int[num];
Controlled Randomness
void setup(){
for(int i=0; i<num; i++){
px[i] = 0;
py[i] = 0;
}
}
void draw(){
background(200);
for(int i=0; i<num; i++){
px[i] = px[i] + int(random(-2,2));
py[i] = py[i] + int(random(-2,2));
constrain(px[i],0,100);
constrain(py[i],0,100);
point(px[i],py[i]);
}
}
Processing-Environment

width
height

//Using the width and height variables is useful when writing a program to scale to
//different sizes. This technique allows a simple change to the parameters of size( )
//to alter the dimensions and proportions of a program
// The measurements of the graphics is relative to the display size
//change the size of the display to 200*200 and see what happens
size(100, 100);
ellipse(width*0.5, height*0.5, width*0.66, height*0.66);
line(width*0.5,0, width*0.5, height);
line(0, height*0.5, width, height*0.5);
Processing-Environment

frameRate();
frameCount

void setup(){
frameRate(1);
}
void draw(){
println(frameCount);
}
Debugging and Error Finding
If you are running a piece of code that has a syntax error or an error in the use of different
commands, the Processing engine while give an error along with the hind of possible location of
an error and suggestions how to fix it:
1.
Debugging and Error Finding
If the program is behaving in an unexpected way, use println() command to print different
variables into the console to find out the reason
Transforming the Grid
By default processing uses a virtual coordinate system that uses the upper left corner of the
display window as the origin with the x-coordinates increasing horizontallt to the right and y-
coordinates increasing vertically downward. You can transform, scale and rotate this grid. As a
result the same sets of commands drawing to the display window will result in different
positioning, scaling and orientation of the graphics on the display window:

pushMatrix();
translate(x,y);
rotate(angle);
scale(scaleFactor);
popMatrix();
Transforming the Grid
By default processing uses a virtual coordinate system that uses the upper left corner of the
display window as the origin with the x-coordinates increasing horizontallt to the right and y-
coordinates increasing vertically downward. You can transform, scale and rotate this grid. As a
result the same sets of commands drawing to the display window will result in different
positioning, scaling and orientation of the graphics on the display window:

size (500,500);
for(int i =-100; i<=200;i+=10)
{
line(i,-100,i,200);
line(-100,i,200,i);
}
fill(0);
stroke(200,0,0);
rect(50,50,30,30);
translate(15,30);//moves the grid
rotate(PI/12);//rotates the grid
scale(2);//scales the grid
for(int i =-100; i<=200;i+=10)
{
line(i,-100,i,200);
line(-100,i,200,i);
}
fill(0);
rect(50,50,30,30);
Transforming the Grid-Saving/Retrieving Base Grid
1. · The pushMatrix() function records the current state of all transformations so that a
program can return to it later. To return to the previous state, use popMatrix()

rect(0, 20, 66, 30);


rect(0, 50, 66, 30);

translate(33,0);
rect(0, 20, 66, 30);
rect(0, 50, 66, 30);

pushMatrix(); //Save the current matrix


translate(33,0);
rect(0, 20, 66, 30);
popMatrix(); //Retrieve the saved Grid
rect(0, 50, 66, 30);
Transforming the Grid-Rotating Base Grid
The rotate () function rotates the coordinate system so that shapes can be drawn to the screen at
an angle. · It has one parameter that sets the amount of the rotation as an angle:

rotate(angle);
1. The rotate function assumes that the angle is specified in units of radians
2. The affects are accumulating every time that you apply the function.
3. You can make different angles by using PI which is a constant in processing representing p
which equals to an angle of 180 degree.
size (150,100);
smooth ( );
rect(5,70,70,20);
rotate(-PI/16);
rect(5,70,70,20);
rotate(-PI/16);
rect(5,70,70,20);
rotate(-PI/16);
rect(5,70,70,20);
rotate(-PI/16);
rect(5,70,70,20);
Transforming Grid-Combining Transform /Rotate
These simple examples demonstrate the potential in combining transformations:

translate(10, 60);//moving of the origin of coordinate system


rect(0, 0, 70, 20);//
rotate(-PI/12); // the coordinate system rotates around its origin
rect(0, 0, 70, 20);
//it results in rotation of the rectangular
//around its upper left corner which happens to be at the origin
rotate(-PI/6);
rect(0, 0, 70, 20);
Transforming Grid-Combining Transform /Rotate
These simple examples demonstrate the potential in combining transformations:

//If you want to rotate around a specific point


//first you should translate the grid to that specific point
//the translated origin would be the base
//that scale and rotation with use as point of reference
translate(45, 60);
rect(-35, -5, 70, 10);
rotate(-PI/8);
rect(-35, -5, 70, 10);
rotate(-PI/8);
rect(-35, -5, 70, 10);
rotate(-PI/8);
rect(-35, -5, 70, 10);
rotate(-PI/8);
Transforming Grid-Scale
The scale( ) function magnifies the coordinate system so that shapes are drawn
larger or smaller. It has one or two parameters to set the amount of increase or
decrease:

scale(size);
scale(xsize,ysize);
The affects are accumulating every time that you apply the function.

size (300,200);
smooth ( );
rect(10,20,70,20);
scale(1.5);
rect(10,20,70,20);
scale(1.5);
rect(10,20,70,20);
scale(1.5);
rect(10,20,70,20);
scale(1.5);
Transforming Grid-Combining Transform /Scale
These simple examples demonstrate the potential in combining transformations:

noFill() ;
translate(10, 20);
rect(0, 0, 20, 10);
scale(2.2);
rect(0, 0, 20, 10);
scale(2.2);
rect(0, 0, 20, 10);
scale(2.2);
Transforming Grid-Combining Transform /Scale
These simple examples demonstrate the potential in combining transformations:

noFill() ;
translate(50, 30);
rect(-10,5,20,10);
scale(1.5);
rect(-10,5,20,10);
scale(1.5);
rect(-10,5,20,10);
scale(1.5);
rect(-10,5,20,10);
scale(1.5);
Transforming Grid-Combining Transform ations
The effects of the transformation functions accumulate throughout the program, and these effects
can be magnified with a for structure:

background(0);
smooth();
stroke(255, 120);
translate(66, 33); // Set initial offset
for (int i = 0; i < 18; i++) //18 repetitions
{
strokeWeight(i); // Increase stroke weight
rotate (PI /12) ;// Accumulate the rotation
line(0, 0, 55, 0);
}
Transforming Grid-Combining Transform ations
The effects of the transformation functions accumulate throughout the program, and these effects
can be magnified with a for structure:

background(0);
smooth();
fill(255, 48);
noStroke();
translate(33,66);
for (int i = 0; i < 12; i++)
{
scale(1.2);
ellipse(4, 2, 20, 20);
}
Random Transformation of the Grid

Code by Kostas Terzidis

size(700,500);
for(int i=0; i<7000; i++){
pushMatrix();
translate(random(width),random(height));
rotate(radians(random(360)));
rect(0,0,4,30);
popMatrix();

}
Interactive/Random Transformation of the Grid
void setup(){
size(700,500);
for(int i=0; i<7000; i++){
pushMatrix();
translate(random(width),random(height));
rotate(radians(random(360)));
rect(0,0,8,60);
popMatrix();
}
}
void draw(){
fill(100,100,100,100);
pushMatrix();
translate(mouseX,mouseY);
rotate(radians(random(360)));
rect(0,0,8,60);
popMatrix();
}
Useful Functions

sin(angleinRadians) and cos(angleinRadians)

float a = sin(PI);

degrees() and radians()

float a = sin(radians(90))
size(720,100);
for(int t=0; t<720; t++){ Useful Functions
point(t,sin(radians(t))*30+50);
}

size(720,100);
for(int t=0; t<720; t++){
point(t,sin(radians(t*3))*30+50);
}
Useful Codes
//Animation and Interaction

void setup()
{
// Any set up related command that is run just once comes here
}
void draw()
{
// Any command that needs to run continuously comes here
}
Useful Codes-Animating a line through time
void setup(){
size(300,100);
}
int i=0;
void draw(){
background(200);
line(i%300,0,i%300,100);
i++;
}
Useful Codes-Animating a line back and forth
int dir=1;
int lineColor=0;
void setup()
{
size(300,100);
background(255);
}
int i=0;
void draw()
{
stroke(lineColor);
background(255);
line(i,0,i,300);
i=i+dir;
if (i>300 || i<1)
{
dir=-dir;
}
}
Useful Codes-Making A dial
void setup()
{
size(300,100);
}
void draw()
{
background(255);
line(mouseX,0,mouseX,100);
println(mouseX);
}
Useful Codes-Defining an area around mouse

int num_floors = 40;


int num_panels = 28;
void setup(){
size(400,600);
// Facade
}
void draw(){
for(int x=0; x<num_panels; x++)
for(int y=0; y<num_floors; y++){
int xx = 100+x*7;
int yy = 20+y*14;
float d = dist(xx,yy, mouseX, mouseY);
if(d<100)fill(255-d);
else
fill(100);
rect(xx, yy, 7, 7 );
}
}
Code by Kostas Terzidis
Using Trigonometry to make patterns
1. sin() function gets the angle in radiant and gives back a number between -1 and 1 as a result.

size(700,100);
noStroke();
fill(0);
float angle = 0.0;
for ( int x=0;x<=width;x+=5){
float y=50+(sin(angle)*35.0);
rect(x,y,2,4);
angle+=PI/40.0;
}
Using Trigonometry to make patterns
1. The cos( ) function returns values in the same range and pattern as sin( ). But the numbers are offset by π/2.

size(700, 100);
noStroke();
smooth();
float offset = 50.0;
float scaleVal = 20.0;
float angleInc = PI/18.0;
float angle= 0.0;
for (int x = 0; x <= width; x += 5) {
float y = offset + (sin(angle) * scaleVal);
fill(255);
rect(x, y, 2, 4);
y=offset + (cos(angle) * scaleVal);
fill(0) ;
fill(0);
rect(x, y, 2, 4);
angle += angleInc;
}
Using Trigonometry to make patterns
1. Making complex patterns

size(700, 100);
smooth();
strokeWeight(2);
float offset = 126.0;
float scaleVal = 126.0;
float anglelnc = 0.42;
float angle = 0.0;
for (int x = -52; x <= width; x += 5) {
float y = offset + (sin(angle) * scaleVal);
stroke(y);
line(x, 0, x+50, height);
angle += anglelnc;
}
Using Trigonometry to make patterns
1. Making complex patterns

size(700, 100);
smooth();
fill(255, 20);
float scaleVal = 18.0;
float anglelnc = PI/28.0;
float angle = 0.0;
for (int offset = -10; offset < width+10; offset += 5) {
for (int y = 0; y <= height; y += 2) {
float x = offset + (sin(angle) * scaleVal);
noStroke () ;
ellipse(x, y, 10, 10);
stroke(0);
point(x, y);
angle += anglelnc;
}
angle += PI;
}
Using Trigonometry to make patterns
1. Circles can be drawn from sin() and cos() functions. The example below has an angle that increments by
12°, all the way up to 360°. On each step, the cos () value of the angle is used to draw the x-coordinate,
and the sin( ) value draws the y-coordinate. Because sin() and cos () return numbers between -1.0 and
1.0, the result is multiplied by the radius variable to draw a circle with radius 38. Adding 50 to the x and
y positions sets the center of the circle at (50,50).

noStroke();
smooth();
int radius = 38;
for (int deg = 0; deg < 360; deg += 12) {
float angle = radians(deg);//this converts the value of the angle from degree to radian
float x = 50 + (cos(angle) * radius); // cos() gives us the base for y coordinate
float y = 50 + (sin(angle) * radius); //sin() gives us the base for x coordinate
ellipse(x, y, 6, 6);
}
Drawing arc with arc() Function
1. To simplify drawing arcs, Processing includes an arc () function:

Arc(x, y, width, height, startAngle, stopAngle) ;


2. The start and stop parameters specify the angles needed to draw the arc form in units of radians. The
following examples show the function in use:

strokeWeight(2);
arc(50, 55, 50, 50, 0, PI/2);
arc(50, 55, 60, 60, PI/2, PI);
arc(50, 55, 70, 70, PI, (2*PI)-(PI/2));
noFill() ;
arc(50, 55, 80, 80, (2*PI)-(PI/2), 2*PI);
Drawing arc with arc() Function
1. To simplify drawing arcs, Processing includes an arc () function:

Arc(x, y, width, height, startAngle, stopAngle) ;


2. The start and stop parameters specify the angles needed to draw the arc form in units of radians. The
following examples show the function in use:

smooth();
noFill();
strokeWeight(10);
stroke (0, 150);
for (int i = 0; i < 160; i += 10) {
float begin = radians(i); //changing the angle from degree to radian
float end = begin + (PI/2);
arc(67, 37, i, i, begin, end);
Drawing Spirals
1. To create a spiral, multiply the sin() and cos() values by increasing or decreasing radius values:

noStroke();
smooth();
float radius = 1.0;
for (int deg = 0; deg < 360*6; deg += 11) {
float angle = radians(deg);
float x = 75 + (cos(angle) * radius);
float y = 42 + (sin(angle) * radius);
ellipse(x, y, 6, 6);
radius = radius + 0.34;
}
Drawing Spirals
1. To create a spiral, multiply the sin() and cos() values by increasing or decreasing radius values:

smooth();
float radius= 0.15;
float cx = 33; // Center x- and y-coordinates
float cy = 66;
float px=cx; // Start with center as the previous coordinate
float py = cy; // Start with center as the previous coordinate
for (int deg=0 ; deg < 360*5; deg += 12) {
float angle = radians(deg);// change the angle from radians to degree
float x = cx + (cos(angle) * radius);
float y = cy + (sin(angle) * radius);
line(px, py, x, y); //draw a line from the previous line to the new line
radius = radius * 1.05; //increases the radius for the next loop
px = x; // the new point becomes the old point to be used for the next loop
py = y; // the new point becomes the old point to be used for the next loop
}
Processing-Video

Video Stream
Presence Detection
Input(webcam)
Movement
Color Differentiation
Color Change
Video Pixel Manipulation
Resolution Change
Rotate
Orientation/Direction
Output Scale
Manipulation
(Screen/Projection) Move
Multiple Copies
Video Overlay
Movement Tracing
Processing-Video Input-Access to each Pixel

Making a two dimentional matrix from one dimensionally distributed ( increasing or


decreasing data):
x Coordinate = index%5
0 1 2 3 4

Shape Index = 16
0 0 1 2 3 4
y Coordinate = index/5

x Coordinate = 1 = index%5

y Coordinate= 3 = index/5
1 5 6 7 8 9

2 10 11 12 13 14

3 15 16 17 18 19
Processing-Video Input-Access to each Pixel
weight

X pixels[i] height

Y=i/weight
x=i%weight
Processing-Video Input-Access to each Pixel
weight

X pixels[i] height

Y=i/weight if (i/weight>200) //Checking y coordinate of pixel

x=i%weight if(i%weight>200) //Checking x coordinate of the pixel


Processing-Video Input-Access to each Pixel
Rotation
YY=x
Y
X
XX=height-Y

Y=i/weight
x=i%weight
Processing-Video Input-Access to each Pixel
Color Change

int r=int(red(img[i]);
Y
int g=int(green(img[i]);
X
int b=int(b(img[i]);
Y=i/weight r=255-r;
x=i%weight g=255-g;
b=0;
color c=color(r,g,b);
pixels[i]=c;
Processing-Audio
Beat Detection

Input(Microphone)
Sound Intensity
Detection

Video
Volume/Pan
Manipulation

Audio File
Output(Speaker)
Play/Pause/Loop/skip

Multiple audio
Overlay
Arduino Board: Arduino UNO

Arduino Programing Environment: Arduino 0022


Download @ http://arduino.cc/en/Main/Software

.
1
*Download Arduino Software from Arduino.cc and unzip the folder to your computer. A
file within the folder called Arduino, allows you to launch the programming
environment.

*You need to install a driver that comes with Arduino to be able to communicate with
the board 2
Setup Arduino-
Install the Arduino Board Drivers that come with Arduino Folder
You can use device manager to install the driver by manually giving the
address of this folder
Setup Arduino-
Connect Arduino to Computer via USB Port using USB Cable
Let the System Find the New Hardware

To Computer USB Port


Setup Arduino-
Setting The Appropriate Arduino Port
Run Arduino, On Arduino Environment go to Tools>Board
Check the appropriate Board
Setup Arduino-
Setting The Appropriate Arduino Port
Run Arduino, On Arduino Environment go to Tools>Serial Ports
Check the Port that you just found out is dedicated to USB Serial
Setup Arduino-
Making Your First Circuit
Connect an LED to Pin 13 and Ground, Short leg to ground and long
leg to Pin 13

To Computer USB Port


Setup Arduino-
Writing Your First Arduino Code
Write and Compile and Uploade your First Arduino Code

void setup(){

pinMode(13,OUTPUT);
}
void loop(){
digitalWrite(13,LOW);
delay(1000);
digitalWrite(13,HIGH);
delay(1000);

}
Sparkfun Shopping Lists:

1. The short list for following physical computing workshop sessions


http://sprkfn.com/w26434
2. The long list of possibilities
http://sprkfn.com/w6408
Arduino Board: Arduino UNO

Arduino Programing Environment: Arduino 0022


Download @ http://arduino.cc/en/Main/Software

1
*Download Arduino Software from Arduino.cc and unzip the folder to your computer. A
file within the folder called Arduino, allows you to launch the programming
environment.

*You need to install a driver that comes with Arduino to be able to communicate with
the board 2
Digital Input/Output Pins
Pins with ~ are PWM
[Analog Output] Transmitter/Receiver
GRD Serial Connection

Microcontroller ATmega328
Operating Voltage 5V
Input Voltage (recommended)7-12V
Input Voltage (limits)6-20V
Digital I/O Pins 14
(of which 6 provide PWM output)
USB Analog Input Pins 6
DC Current per I/O Pin 40 mA
DC Current for 3.3V Pin 50 mA

7-12 v

3v 5v
GRD Analog Input Pins 3
4
5
6
Other Hardware Choices-Boards
Arduino BT
The Arduino BT is an Arduino board with built-in bluetooth module,
allowing for wireless communication.
LilyPad Arduino
The LilyPad Arduino is a microcontroller board designed for wearables
and e-textiles. It can be sewn to fabric and similarly mounted power
supplies, sensors and actuators with conductive thread.

Arduino Nano
Arduino Nano is a surface mount breadboard embedded version with
integrated USB. It is a smallest, complete, and breadboard friendly. It
has everything that Diecimila has (electrically) with more analog input
pins and onboard +5V AREF jumper.

7
Xbee Shield Other Hardware Choices-Sheilds
The Xbee shield allows an Arduino board to communicate wirelessly using Zigbee. The module can
communicate up to 100 feet indoors or 300 feet outdoors (with line-of-sight). It can be used as a
serial/usb replacement or you can put it into a command mode and configure it for a variety of
broadcast and mesh networking options.
The Xbee shield was created in collaboration with Libelium, who developed it for use in their SquidBee
motes (used for creating sensor networks).
Adafruit Servo/Stepper/DC Motor shield
A shield that can control 2 hobby servos and up to 2 unipolar/bipolar stepper motors or 4 bi-directional
DC motors.
Battery Shield
A shield from Liquidware that connects to the back of the Arduino, with a USB-rechargable lithium ion
battery that can power an Arduino for 14-28 hours depending on the circuit
Liquidware TouchShield
OLED touch screen shield.
Adafruit Wave shield
Plays any size 22KHz audio files from an SD memory card for music, effects and interactive sound art
Adafruit GPS & Datalogging shield
Connects up a GPS module and can log location, time/date as well as sensor data to an SD memory
flash card.
Adafruit XPort/Ethernet shield
Allows use of an XPort module for connecting to the Internet as a client or server. 8
Other Hardware Choices-Sheilds
Adafruit GPS & Datalogging shield
Connects up a GPS module and can log location,
time/date as well as sensor data to an SD memory
flash card.

Adafruit XPort/Ethernet shield


Allows use of an XPort module for connecting to the
Internet as a client or server.

9
http://ladyada.net
Other Hardware Choices-Sheilds
Liquidware TouchShield
OLED touch screen shield.

http://www.liquidware.com

Adafruit Servo/Stepper/DC Motor shield


A shield that can control 2 hobby servos and up to 2
unipolar/bipolar stepper motors or 4 bi-directional
DC motors.

10
http://ladyada.net
USB Cable A to B - 6 and 10 Feet/ USB miniB Cable - 6 Foot
This USB Cable type is the one that allows for connecting normal Arduino Boards to the computer. They come in black and white and in various lengths. For
Arduino Mini Pro and Lilypad you need USB miniB for connecting to computer.

http://www.sparkfun.com/commerce/product_info.php?products_id=512
http://www.sparkfun.com/commerce/product_info.php?products_id=513
http://www.sparkfun.com/commerce/product_info.php?products_id=598
USB Cable Extension - 6 Foot/ USB Cable A to A - 6 and 10 Foot

These extension cables have a type A male connector on one end that plugs into any computer. The opposing end has a female type A connector allowing a
second USB cable to be inserted. This allows as many cables to be daisy chained together as needed. May come in White or Black, and in 6 feet. For more
extension you can combine USB cable extension with a USB A to A cable.

http://www.sparkfun.com/commerce/product_info.php?products_id=517
http://www.sparkfun.com/commerce/product_info.php?products_id=516
http://www.sparkfun.com/commerce/product_info.php?products_id=515
Arduino Boards
This is the new Arduino Uno. In addition to all the features of the previous board, the Uno now uses an ATmega8U2 instead of the FTDI chip. This allows for
faster transfer rates, no drivers needed for Linux or Mac (inf file for Windows is needed), and the ability to have the Uno show up as a keyboard, mouse, joystick,
etc.

The Arduino Mega is a microcontroller board based on the ATmega2560. It has 54 digital input/output pins (of which 14 can be used as PWM outputs), 16
analog inputs, 4 UARTs (hardware serial ports), a 16 MHz crystal oscillator, a USB connection, a power jack, an ICSP header, and a reset button. It contains
everything needed to support the microcontroller; simply connect it to a computer with a USB cable or power it with a AC-to-DC adapter or battery to get started.
The Mega is compatible with most shields designed for the Arduino Duemilanove or Diecimila. This is the new Arduino Mega 2560. In addition to all the features
of the previous board, the Mega 2560 now uses an ATmega8U2 instead of the FTDI chip. This allows for faster transfer rates, no drivers needed for Linux or
Mac (inf file for Windows is needed), and the ability to have the board show up as a keyboard, mouse, joystick, etc. It also has twice as much flash memory.

Other variaitions of arduino are Arduino pro, Arduino Mini Pro and Lilypad Arduino .

http://www.sparkfun.com/commerce/product_info.php?products_id=9950
http://www.sparkfun.com/commerce/product_info.php?products_id=9949
http://www.sparkfun.com/commerce/tutorial_info.php?tutorials_id=148
Arduino Project Enclosure/ Crib for Arduino - Metal Enclosure
The Arduino enclosure allows you to easily enclose your Arduino main board, Arduino Mega, or any other board that fits the Arduino foot print (FEZ Domino,
FEZ Panda, Netduino, etc). It simply presses shut, so you don't have to worry about screws or fasteners. It has room internally for an Arduino and a shield. It
even has a removable tab mated for use with an Ethernet shield. It also has a snap-in compartment in the back for accessing switches or connections or battery
access.
Made from sturdy, lightweight powder-coated aluminum, the Crib for Arduino can accommodate either an Arduino Duemilanove or Arduino Mega with head
room to spare for a shield like an Ethernet shield. This enclosure weighs only 5.6 oz (159 g) and is structurally very strong. The baseplate is pre-drilled with hole
patterns for both Arduino boards(Main and Mega so you get perfect alignment and no hole drilling for board mounting. Use the snap-in standoffs to quickly
mount your board and go. Flanges on the lid let you mount your project anywhere with just 4 screws. Bolt it securely under your desk or to the ceiling! Or just
insert four rubber feet (not included) into the flange holes so your Arduino project can sit on your desk and not scratch it.

http://www.sparkfun.com/commerce/product_info.php?products_id=10088
http://www.sparkfun.com/commerce/product_info.php?products_id=10033
Wall Adapter Power Supply - 9VDC 650mA/ Wall Adapter Power Supply - 12VDC 600mA

9VDC is High quality switching 'wall wart' AC to DC 9V 650mA wall power supply manufactured specifically for Spark Fun Electronics. These are switch mode
power supplies which mean the output is regulated to 9V and the capable output current is much higher (650mA!). These will power most projects that don't
require more than 650mA of current. Center-positive 5.5x2.1mm barrel connector.
Works with 100-240VAC inputs.

12VDC is a high quality AC to DC 'wall wart' which produces a regulated output of 12VDC at up to 600mA. These are switch mode power supplies which means
the output is regulated to 12V and the capable output current is much higher (600mA!). These will power most projects that don't require more than 650mA of
current. Center-positive 5.5x2.1mm barrel connector. Works with 100-240VAC inputs.

http://www.sparkfun.com/commerce/product_info.php?products_id=298
http://www.sparkfun.com/commerce/product_info.php?products_id=9442
9V to Barrel Jack Adapter
Plug a 9V battery into one end and connect the other end to anything with a 5.5x2.1mm, center-positive barrel jack. Use this cable to battery-power any device
that needs 9V and has an on-board barrel jack - it works great for Arduinos, development boards, evaluation boards, and more!

http://www.sparkfun.com/commerce/product_info.php?products_id=9518
Battery Holder - 4xAA to Barrel Jack Connector

This is a simple 4 cell AA battery holder. The 5 inch cable is terminated with a standard 5.5x2.1mm, center positive barrel jack connector. The connector mates
with the barrel jack on the Arduino (among a number of other products) allowing you to easily make your project battery powered. Note: the average voltage
regulator has about 1V of dropout (but can vary greatly). This pack, with normal alkaline batteries, will output ~5.5V causing a normal 5V board to run at around
4 to 4.5V. This depends a lot of what board and processor you are using with the battery pack. Please consult your datasheet.

http://www.sparkfun.com/commerce/product_info.php?products_id=9835
9V Solar & battery power supply
The 9V Solar & battery power supply is specially designed for Arduino and other microcontroller project alike. It can be used as a portable power supply, and is
capable of delivering 9V, 500mA power. It can be charged by your PCB USB port or by sun-light or in-door light sources. It has following features:

http://www.nuelectronics.com/estore/index.php?main_page=product_info&products_id=13
Long life Lithium Backpack Batteries for Arduino
These are long-life batteries particularly designed for Arduino. There is also a variation for Arduino Mega. Depending on how much juice you need, get these in
low, medium, or high capacity. Bare battery PCB matches the size of the Arduino . High Capacity 2200mAh Lithium Ion Battery provides 29 Standby Arduino
Hours. Medium Capacity 1000mAh Lithium Ion Battery provides 15 Standby Arduino Hours. Low Capacity 600mAh Lithium Ion Battery provides 9.4 Standby
Arduino Hours. It is rechargeable via Arduino USB or via USB Tybe-B Mini Cable and supplies regulated 5V and 3.3V .

http://www.liquidware.com/shop/show/bp/lithium+backpack
http://www.liquidware.com/shop/show/BPM/
http://antipastohw.blogspot.com/2008/06/how-to-install-lithium-backpack-to-your.html
Jumper wires with F/F, F/M and M/M connecting ends
These are easy to use jumper wires terminated as male to female, male to male or female to female for connections.

http://www.sparkfun.com/commerce/product_info.php?products_id=9386
http://www.sparkfun.com/commerce/product_info.php?products_id=8431
http://www.sparkfun.com/commerce/product_info.php?products_id=8430
Color Coded Flat (Ribbon)/Coded Flat (Ribbon)
These are easy to use jumper wires terminated as male to female, male to male or female to female for connections.

http://www.newark.com/jsp/search/productdetail.jsp?SKU=23M8844&CMP=AFC-GB100000001
http://www.allelectronics.com/make-a-store/item/RCBL-10TF/10-CONDUCTOR-TWIST-FLAT-RIBBON-CABLE/1.html
http://www.allelectronics.com/make-a-store/item/RCBL-9/9-CONDUCTOR-FLAT-RIBBON-CABLE/1.html
http://solutions.3m.com/wps/portal/3M/en_US/Interconnect/Home/Products/ProductCatalog/Catalog/?PC_7_RJH9U5230O73D0ISNF9B3C3SI1_nid=855TBYZX
VNit6Z44P5GPWMglD2FDQK85M6bl
Conductive Thread
Conductive thread is a creative way to connect various electronics onto clothing. This thread can carry current for power and signals. While not as conductive as
traces on a printed circuit board (PCB), this thread makes wearable clothing 'wearable'!

http://www.sparkfun.com/commerce/product_info.php?products_id=8544
http://www.sparkfun.com/commerce/product_info.php?products_id=8549
Protoboard
Protoboards provide a free canvass for devising soldered circuit compositions. They come in different colors and sizes.

http://www.sparkfun.com/commerce/product_info.php?products_id=8619
http://www.sparkfun.com/commerce/product_info.php?products_id=8708
http://www.sparkfun.com/commerce/product_info.php?products_id=8808
http://www.sparkfun.com/commerce/product_info.php?products_id=8814
http://www.sparkfun.com/commerce/product_info.php?products_id=8809
http://www.sparkfun.com/commerce/product_info.php?products_id=8847
http://www.sparkfun.com/commerce/product_info.php?products_id=8885
http://www.sparkfun.com/commerce/product_info.php?products_id=8887
Solderless Breadboard
To free yourself from the pain of soldering and also from the risk of ruining your components it is advisable to your breadboards. Breadboards come in different
sizes and even colors

http://www.sparkfun.com/commerce/product_info.php?products_id=9567
http://www.sparkfun.com/commerce/product_info.php?products_id=8800
http://www.sparkfun.com/commerce/product_info.php?products_id=8802
http://www.sparkfun.com/commerce/product_info.php?products_id=8803
http://www.sparkfun.com/commerce/product_info.php?products_id=137
http://www.sparkfun.com/commerce/product_info.php?products_id=7916
Breadboard Power Supply Stick 5V/3.3V
This is a very simple board that takes a 6-12V input voltage and outputs a selectable 5V or 3.3V regulated voltage. All headers are 0.1" pitch for simple insertion
into a breadboard. Input power can be supplied to either the DC barrel jack or the two pin header labeled + and -. Output power is supplied to the pins labeled
GND and VCC. Board has both an On/Off switch and a voltage select switch (3.3V/5V).

http://www.sparkfun.com/commerce/product_info.php?products_id=9319
Micro SD Shield –Data Logger Shield for Arduino
Running out of memory space in your Arduino project? The microSD Shield equips your Arduino with mass-storage capability, so you can use it for data-logging
or other related projects. Communication with microSD cards is achieved over an SPI interface. The SCK, DI, and DO pins of the microSD socket are broken
out to the ATmega168/328's standard SPI pins (digital 11-13), while the CS pin is broken out to Arduino's D8 pin. If you decide to use one of the many open
source FAT libraries (like FAT16 or SDFat) make sure to change the code to reflect the location of the CS pin. Most libraries assume the CS pin is connected to
D10; this will have to be changed to D8. Also for the libraries to work pin D10 will have to be set as an output in the 'setup()' section of your sketch. The shield
also includes a large prototyping area with a 13x12 grid of 0.1" pitch PTHs. This shield comes populated with a microSD socket, red power indicator LED, and a
reset button; but it does not come with headers installed. We recommend the 6 and 8-pin stackable headers.

http://www.sparkfun.com/commerce/product_info.php?products_id=9802
XBEE Module and XBEE Shield for Arduino
This is the very popular 2.4GHz XBee module from Digi (formally Maxstream). These modules take the 802.15.4 stack (the basis for Zigbee) and wrap it into a
simple to use serial command set. These modules allow a very reliable and simple communication between microcontrollers, computers, systems, really
anything with a serial port! Point to point and multi-point networks are supported.
The XBee Shield simplifies the task of interfacing an XBee with your Arduino. This board mates directly with an Arduino Pro and equips it with wireless
communication capabilities using the popular XBee module. This unit works with all XBee modules including the Series 1 and Series 2.5, standard and Pro
version. The serial pins (DIN and DOUT) of the XBee are connected through an SPDT switch, which allows you to select a connection to either the UART pins
(D0, D1) or any digital pins on the Arduino (D2 and D3 default). Power is taken from the 5V pin of the Arduino and regulated on-board to 3.3VDC before being
supplied to the XBee. The shield also takes care of level shifting on the DIN pin of the XBee. The board also includes LEDs to indicate power and activity on
DIN, DOUT, RSSI, and DIO5 pins of the XBee. The Arduino's reset button is brought out on the shield, and a 12x11 grid of 0.1" holes are available for
prototyping. The shield does not come with headers installed; we recommend the 6 and 8-pin stackable headers. The XBee module is also not included.

http://www.sparkfun.com/commerce/product_info.php?products_id=9841
http://www.sparkfun.com/commerce/product_info.php?products_id=8664
http://www.sparkfun.com/commerce/product_info.php?products_id=8665
Cellular Shield with SM5100B for Arduino
The Cellular Shield for Arduino includes all the parts needed to interface your Arduino with an SM5100B cellular module. This allows you to easily add SMS,
GSM/GPRS, and TCP/IP functionalities to your Arduino-based project. All you need to add cellular functionality to your Arduino project is a SIM card (pre-paid or
straight from your phone) and an antenna and you can start sending Serial.print statements to make calls, send texts and serve web pages! The main
components of the Cellular Shield are a 60-pin SM5100B connector, a SIM card socket, and an SPX29302 voltage regulator configured to regulate the
Arduino's raw voltage to 3.8V. The board's red LED indicates power. The Arduino's reset button is also brought out on the shield. Two jumpers on the board
allow you to select which serial pins interface with the cellular module - software (D2, D3) or hardware (D0, D1). There is also a 5-pin, 0.1" spaced header with
connections for microphone inputs and speaker outputs. Headers are not soldered on, w e recommend the 6 and 8-pin stackable headers. The SM5100B
cellular module is included with this product, however the SMA to u.FL connector is not. It is pre-configured to 9600bps.

http://www.sparkfun.com/commerce/product_info.php?products_id=9607
http://www.sparkfun.com/commerce/product_info.php?products_id=9145
29
LED

Light

RGB LED

Sound Piezo

Digital(on/off, HIHG/LOW, 0,1)


Standard Servo Motor

Movement

Continuous Rotation Servo


Motor

Output

Wind Fan

Analog(0-255) Light LED-Light Intensity

30
Arduino-Digital Output
Digital Out put is defined as sending on/off or 0/1 signals from one of the digital pins on the
Aurduino board (pin 2-13) to the electronic actuator that recognize on/off or 0/1 signal.
The so-called digital pins are highlighted here.

31
Arduino-Digital Output-LED
LED (Light Emitting Diode) is a light feature that can be used as an actuator of the space.

Being a Diode, an LED is a directional piece meaning that it is activated only if it is placed in the
circuit in the right direction

Ground Pin
Digital Pin
32
Arduino-Ground Pin
For electricity to flow in a circuit, we need difference in level of electricity energy. In Arduino board
this difference is provided by making a circuit between one of the output pins and ground pin.
When we send a signal through output pin any signal that is not 0 or LOW will provide the
desired difference between the two ends of the circuit and will result in electricity flow between
the digital output pin and ground pin- The level of electricity energy at Ground pin is zero, as a
result any non zero signal on the digital pin gives us a difference and an electricity flow.
You can also create this situation using two output pins, one sending the low signal and one
sending a high signal. The low signal pin in this case will function as the ground.

33
Arduino-Digital Output-LED
LEDs come in different colors and shapes.

34
Arduino-Digital Output-LED

35
Arduino-Digital Output-LED

36
Arduino-Digital Output-LED

void setup(){
pinMode(13, OUTPUT);
}
void loop(){
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}

37
Arduino-Checking the Right Board 38
Arduino-Checking the Right Port 39
Arduino-Compiling and Uploading Code

1. Write the code


2. Compile the code
3. Check Arduino Port Connection
4. Upload the Code
40
5. The Arduino and Connected Circuits start to show behavior based on the uploaded code
Arduino-Digital Output-LED

41
Arduino-Digital Output-LED

The Board should be connected to the computer in order to upload the program from arduino
environment to the board. Once the program is uploaded, if there is no realtime data being
communicated between the board and the program there is no need for the board to be
connected any more. Thus you can change the power to Ext(external Power) as opposed to
USB(power from USB) and use a battery or a power adaptor to power the board.
In the case of the LED exercise since after uploading there is no data being communicated
between the board and the computer, you can disconnect the piece and make it a independent
42
disconnected piece.
Arduino-Using SolderlessBreadboard
Solderless Board is useful to build prototypes, as fast as possible without going through tiresome
and time consuming process of soldering parts together to make connections

43
Arduino-Using SolderlessBreadboard
Solderless Board is useful to build prototypes, as fast as possible without going through tiresome
and time consuming process of soldering parts together to make connections

Most important thing in using a solderless breadboard in understanding its connections and
wiring underneath the white cover to be able to connect parts in a way that complete and flawless
lines are provided for electricity flow

44
Arduino-Using SolderlessBreadboard
Solderless Board is useful to build prototypes, as fast as possible without going through tiresome
and time consuming process of soldering parts together to make connections

Most important thing in using a solderless breadboard in understanding its connections and
wiring underneath the white cover to be able to connect parts in a way that complete and flawless
lines are provided for electricity flow

45
Arduino-Using SolderlessBreadboard
For example this is how an LED can be connected to an Arduino board using a solderless
breadboard.

*we are using color codes in wiring. Red wire is connected to output pin and black wire
46
is
connected to Ground
Arduino-Using SolderlessBreadboard
For example this is how an LED can be connected to an Arduino board using a solderless
breadboard. The red dotted line shows the flow of electricity from the digital output pin to LED
and then ground pin.

47
Arduino-Using SolderlessBreadboard
Using a Solderless breadboard does not make that much of sense if we are only connecting one
LED to the board with one in and one out wire connected to it. It is best suited when we want to
have multiple elements connected to one or multiple pins.
For example what if we want to control multiple LEDs from one digital output pin on Arduino
board?

48
Arduino-Connecting Multiple Actuators to
Single Output Pin-Serial Connection

Ground Pin

Digital Pin

In Serial connection, adding more electricity consuming elements results in weaker electricity
flow. In case of Arduino Board adding more than three High intensity LEDs will result in so weak
an electricity flow that the LEDs will not turn on
Also, in Serial connection, disconnecting any element of the connection-i.e. disconnecting one of
the LEDs will result in breaking the circuit and as a result electricity will stop flowing and the
49
whole circuit will not work anymore
Arduino-Connecting Multiple Actuators to
Single Output Pin-Serial Connection

Serial Connection on Solderless Board-The left diagram shows the electricity flow in the circuit.

50
Arduino-Connecting Multiple Actuators to
Single Output Pin-Parallel Connection

Ground Pin Digital Pin

In Parallel connection, adding more electricity consuming elements do not result in decrease of
electricity flow
Also, in Parallel connection, disconnecting any element of the connection-i.e. disconnecting one
of the LEDs will not result in breaking the circuit since each element is individually connected to
51
both digital output pin and ground pin.
Arduino-Connecting Multiple Actuators to
Single Output Pin-Parallel Connection

Parallel Connection on Solderless Board.

52
Arduino-Analog Output-LED
Analog Out put is defined as sending signals from one of the digital pins on the Aurduino board
that range between two extremes: 0-255

Out of 13 Digital pins on Arduino board the following pins can be used to signal out Analog
output: 3,5,6,9,10,11

These are the pins with PWM label next to them on the board

53
Arduino-Analog Output-LED

For this exercise since we need to see the light variations , we are going to use a high intensity
LED. High Intensity LEDs emit more light than normal LEDs and it is easier to detect light
54
variations, using them.
Arduino-Analog Output-LED

55
Arduino-Analog Output-LED
//pin 11,10,9,6,5,3 can be used for Analog output
void setup(){
pinMode(11, OUTPUT); // Specify Arduino Pin number and output/input mode
}
void loop(){
analogWrite(11, 255); // sending Analog output 255
delay(500); // Wait for half a second
analogWrite(11, 200); // Sending Analog output 200
delay(500); // Wait for half a second
analogWrite(11, 150); // Sending Analog output 150
delay(500); // Wait for half a second
analogWrite(11, 100); // Sending Analog output 100
delay(500); // Wait for half a second
analogWrite(11, 50); // Sending Analog output 50
delay(500); // Wait for half a second
analogWrite(11, 0); // sending analog output 0
delay(500); // Wait for half a second
}

56
Arduino-Analog Output-LED_Dimming Using
Loop Structure

57
Arduino-Analog Output-LED_Dimming Using
Loop Structure
//pin 11,10,9,6,5,3 can be used for Analog output
void setup(){
pinMode(11, OUTPUT); // Specify Arduino Pin number and output/input mode
}
void loop(){
for(int i=255; i>0; i--){
analogWrite(11, i); // sending Analog output 255
delay(20);
}
for(int i=0; i<255; i++){
analogWrite(11, i); // sending Analog output 255
delay(20);
}
}

58
Arduino-Controlling Multiple Actuators
separately from different output pins

Follow the above diagram to assemble your circuit:


Black represents the wiring that is connected to ground
Red represents wiring that is connected to Aurdoino output pins
Yellow represents wiring that is providing connections on Solderless Board to create seamless
electricity flow for the Ground Line that we are creating. LEDs are seperately connected to digital
pins while are all connected to the same Ground pin via a Ground Line on the solderless board
59
Arduino-Controlling Multiple Actuators
separately from different output pins-
Sequencing

60
Arduino-Controlling Multiple Actuators
separately from different output pins-
Sequencing
void setup(){
pinMode(2, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(3, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(4, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(5, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(6, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(7, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(8, OUTPUT); // Specify Arduino Pin number and output/input mode
}
void loop(){
for(int i=2; i<9; i++){//iterating through pin 2 to 8 and turning them on one by one
digitalWrite(i,HIGH); //Sending High Signal to Pin
delay(1000); //Wait 1 second
}
for(int i=9; i>2; i--){//iterating through pin 8 to 2 and turning them off one by one
digitalWrite(i,LOW); //Sending LOW Signal to Pin
delay(1000); //Wait 1 second
}
}

61
Arduino-Controlling Multiple Actuators
separately from different output pins-
Sequencing

62
Arduino-Controlling Multiple Actuators
separately from different output pins-
Random Patterns

63
Arduino-Controlling Multiple Actuators
separately from different output pins-
Random Patterns
void setup(){
pinMode(2, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(3, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(4, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(5, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(6, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(7, OUTPUT); // Specify Arduino Pin number and output/input mode
pinMode(8, OUTPUT); // Specify Arduino Pin number and output/input mode
}
void loop(){
for(int i=2; i<9; i++){//iterating through pin 2 to 8 and turning them on/off randomly
int signal=int(random(0,2));
digitalWrite(i,signal); //Sending High Signal to Pin
}
delay(1000); //Wait 1 second
}

64
Arduino-Controlling Multiple Actuators
separately from different output pins-
Random Patterns

65
Arduino-Controlling Multiple Actuators
separately from different output pins-
Random Patterns

Aside from introduction of randomness, payattention to how changing the place of delay()
function can change the systems behavior. Here we put the delay function out side of the for
loop. As a result instead of seeing the change for each actuator one by one in a sequence, which
is the case in the previous exercise, here, at first all the actuators(LEDs) are configured together
and then the system pauses for one second to let us see the over all configuration. 66
Arduino-Controlling Actuators Based on
Input from Arduino Serial Port

67
Arduino-Controlling Actuators Based on
Input from Arduino Serial Port
//pin 11,10,9,6,5,3 can be used for Analog output
int serialNumber=0;
int lightIntensityValue=0;
void setup(){
Serial.begin(9600);
pinMode(11, OUTPUT); // Specify Arduino Pin number and output/input mode
}

void loop(){
int value=Serial.read();
Serial.println(value);
if(value!=-1 && value!=10){
serialNumber=serialNumber*10+(value-48);
}
if(value==10){
lightIntensityValue=serialNumber%255;
Serial.print("Number Recieved from Serial Port:");
Serial.println(serialNumber);
serialNumber=0;
}
analogWrite(11,lightIntensityValue);
delay(1000);
}

1. Data is received from Serial port as ASCII codes.


2. If data is numerical, each digit is sent separately.
3. ASCII code of zero is 48
4. To calculate the numerical value of a digit from its ASCI code: digit=ASCII-48
5. At the end of a package the serial port send a number 10
68
6. If nothing is passed to the serial port, the port sends number -1 as default
3-Color LED
void setup(){
pinMode(13,OUTPUT);
pinMode(12,OUTPUT);
pinMode(11,OUTPUT);
pinMode(10,OUTPUT);
}
void loop(){
digitalWrite(11,LOW);

digitalWrite(13,HIGH);
digitalWrite(12,LOW);
digitalWrite(10,LOW);
delay(1000);
digitalWrite(13,LOW);
digitalWrite(12,HIGH);
digitalWrite(10,LOW);
delay(1000);
digitalWrite(13,LOW);
digitalWrite(12,LOW);
digitalWrite(10,HIGH); Digital Pin13
delay(1000); LOW/HIGH Digital Pin12 Digital Pin10
LOW/HIGH LOW/HIGH
}

Digital Pin11
LOW

**Make sure you are not doing the circuit vice versa!!!
** Sometimes the long leg should be high and the leg
which is low would determine the color of the light
69
Arduino-
Digital Output-Sound-Piezo

A Piezo is an electronic piece that converts electricity energy to sound. It is a digital output
device. You can make white noise or even exact musical notes ( frequencies for musical notes)
based on the duration that you iterate between HIGH and LOW signals.
A Piezo is a directional piece, meaning that it has a positive and negative pole. The positive pole
should be connected to the digital output pin that you allocate to control the piezo and the
70
negative pole should be connected to Ground pin
Arduino-
Digital Output-Sound-Piezo

71
Arduino-
Digital Output-Sound-Piezo
//connect piezo to pin 13 and ground
int freqs[] = {
1915, 1700, 1519, 1432, 1275, 1136, 1014, 956};
//string tones[] = {"do", "re", "mi", "fa","sol"," la", "si", "do"};
void setup(){
pinMode(13,OUTPUT);
}
void loop(){
for(int i=0;i<8;i++){//iterating through notes
for(int j=0;j<1000;j++){//the time span that each note is being played
digitalWrite(13,HIGH);
delayMicroseconds(freqs[i]);
digitalWrite(13,LOW);
delayMicroseconds(freqs[i]);
}
}
}

72
Arduino-
Digital Output-Sound-Piezo-Playing a melody

73
Arduino-
Digital Output-Sound-Piezo-Playing a melody
//connect piezo to pin 13 and ground
void playNote(int note)
{
for(int j=0;j<60;j++){//the time span that each note is being played
digitalWrite(13,HIGH);
delayMicroseconds(note);
digitalWrite(13,LOW);
delayMicroseconds(note);
}
delay(60);
}
int pause=200;
int freqs[] = {
1915, 1700, 1519, 1432, 1275, 1136, 1014, 956};
//string tones[] = {"do", "re", "mi", "fa","sol"," la", "si", "do"};
// i={0 1 2 3 4 5 6 7
//mi mi mi - mi mi mi - mi sol do re mi - - - fa fa fa fa fa mi mi mi mi re re mi re - sol - mi mi mi - mi mi mi - mi sol do re mi -- fa fa fa fa fa mi mi mi sol sol fa re do - - -
void setup(){
pinMode(13,OUTPUT);
}
void loop(){
playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]); delay(pause);
playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]); delay(pause);
playNote(freqs[2]); playNote(freqs[4]); playNote(freqs[0]); playNote(freqs[1]);
playNote(freqs[2]); delay(pause); delay(pause); delay(pause);
playNote(freqs[3]); playNote(freqs[3]); playNote(freqs[3]); playNote(freqs[3]);
playNote(freqs[3]); playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]);
playNote(freqs[2]); playNote(freqs[1]); playNote(freqs[1]); playNote(freqs[2]);
playNote(freqs[1]); delay(pause); playNote(freqs[4]); delay(pause);
playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]); delay(pause);
playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]); delay(pause);
playNote(freqs[2]); playNote(freqs[4]); playNote(freqs[0]); playNote(freqs[1]);
playNote(freqs[2]); delay(pause); delay(pause); delay(pause);
playNote(freqs[3]); playNote(freqs[3]); playNote(freqs[3]); playNote(freqs[3]);
playNote(freqs[3]); playNote(freqs[2]); playNote(freqs[2]); playNote(freqs[2]);
playNote(freqs[4]); playNote(freqs[4]); playNote(freqs[3]); playNote(freqs[3]);
playNote(freqs[0]); delay(pause); delay(pause); delay(pause);
}
74
Arduino-
Same Signal Multiple Interpretations

In the same setting if you connect an LED parallel to Piezo, you can see how the same signal
can be interpreted differently using a different output device that accept the same type of
75
signals(in this case digital signal)
Arduino-
DigitalOutput-Motion-Servo Motor

Servo Motors are electronic devices that convert digital signal to rotational movement. There are
two sorts of servo motors: Standard servos that their rotation is limited to maximum of 180
degrees in each direction and Continuous Rotation Servos that can provide rotation unlimitedly
76
in
both directions
Arduino-
DigitalOutput-Motion-Servo Motor
A servo motor is a motor that pulses at a certain rate moving its gear at a certain angle. It has
three connections: the black is ground, the red is connected to 5V, and the white (yellow
wire here) is set to the digital pin.

Ground

V5

Digital Pin

77
Arduino-
Standard Servo Rotation to Exact Angel

78
Arduino-
Standard Servo Rotation to Exact Angel
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
myservo.attach(9);
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
myservo.detach(); //Detach the servo if you are not controling it for a while
delay(2000);
}

79
Arduino-
Controlling Standard Servo with User Input

80
Arduino-
Controlling Standard Servo with User Input
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
int angleValue=0;
int serialNumber=0;
void setup()
{
Serial.begin(9600);
myservo.attach(9);
}
void loop()
{
int value=Serial.read();
Serial.println(value);
if(value!=-1 && value!=10){
serialNumber=serialNumber*10+(value-48);
}
if(value==10){
myservo.attach(9);
angleValue=serialNumber%180;
myservo.write(angleValue); // tell servo to go to position in variable 'pos'
Serial.print("Number Recieved from Serial Port:");
Serial.println(serialNumber);
serialNumber=0;
delay(250);
}
myservo.detach();
}

81
Arduino-
Controlling Servo with User Input

82
Arduino-
DigitalOutput - Continuous Rotation
As opposed to standard Servo that its rotation is limited to 180 degrees both ways, a continuous
rotation servo can keep rotating unlimitedly-again both ways- based on the frequency that is
pulsed out to it. There is a specific frequency at which the Servo motor should be static and
beyond and before which the servo will change in its rotation direction.

Ground

V5

Digital Pin

83
Arduino-
Digital Output - Continuous Rotation-
Adjustment
As opposed to standard Servo that its rotation is limited to 180 degrees both ways, a continuous
rotation servo can keep rotating unlimitedly-again both ways- based on the frequency that is
pulsed out to it. There is a specific frequency at which the Servo motor should be static and
beyond and before which the servo will change in its rotation direction.
There is a pin on the servo motor that enables us to adjust the servo for its static frequency.

84
Arduino-
Digital Output - Continuous Rotation-
Upload the following code to the board and while the servo is
connected, try to adjust the pin until the servo motor is static. Adjustment
Once the servo is adjusted to this code any pulse grater than 1500 will
result in rotation in one direction while any pulse less than 1500 will
result in rotation in the other direction

void setup()
{
pinMode(5,OUTPUT);
}
void loop()
{
for (int i = 0; i <= 200; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1500); // 1.5ms This is the frequency at which the servo motor should be static
digitalWrite(5,LOW);
delay(20); // 20ms
}
} 85
Arduino-
Digital Output - Continuous Rotation-
Direction Change

Once the servo is adjusted to this code any pulse grater


than 1500 will result in rotation in one direction while any
pulse less than 1500 will result in rotation in the other
direction

86
void setup()
{
Arduino-
Digital Output - Continuous Rotation-
pinMode(5,OUTPUT);
}
void loop()
{

Direction Change
//Rotating in One direction
for (int i = 0; i <= 200; i++)
{
digitalWrite(5,HIGH);

delayMicroseconds(1800);
digitalWrite(5,LOW);
delay(20); // 20ms
}

Once the servo is adjusted to this code any pulse grater


//Stop
for (int i = 0; i <= 200; i++)

than 1500 will result in rotation in one direction while any


{
digitalWrite(5,HIGH);

delayMicroseconds(1500); pulse less than 1500 will result in rotation in the other
direction
digitalWrite(5,LOW);
delay(20); // 20ms
}
//Rotating in the other direction
for (int i = 0; i <= 200; i++)
{
digitalWrite(5,HIGH);

delayMicroseconds(1200);
digitalWrite(5,LOW);
delay(20); // 20ms
}
//Stop
for (int i = 0; i <= 200; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1500);
digitalWrite(5,LOW);
delay(20); // 20ms
}
} 87
void setup()
{
pinMode(5,OUTPUT);
}
Arduino-
Digital Output - Continuous Rotation-
void loop()
{
//Continious Rotation
for (int i = 0; i <= 20; i++)
{
digitalWrite(5,HIGH);

Delayed Steps
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(1);
}
//Rotating with delayed steps
for (int i = 0; i <= 20; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(100);
Playing with delay() gives us pauses between rotation
}
//More Delay
for (int i = 0; i <= 20; i++)

steps
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(200);
}
//More Delay
for (int i = 0; i <= 20; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(400);
}
//More Delay
for (int i = 0; i <= 20; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(800);
}
//More Delay
for (int i = 0; i <= 20; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);

delay(1800);
} 88
}
Arduino-
Digital Output - Continuous Rotation-
void setup()
{
pinMode(5,OUTPUT);
}
Controlling Rotation Angle
void loop()
{

for (int i = 0; i <= 10; i++)


{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);
delay(20);
}
Playing with the number of steps in the for loop gives us
delay(1000);
variations in the span /Angle of the rotation
for (int i = 0; i <= 20; i++)
{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);
delay(20);
}
delay(1000);

for (int i = 0; i <= 30; i++)


{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);
delay(20);
}
delay(1000);

for (int i = 0; i <= 40; i++)


{
digitalWrite(5,HIGH);
delayMicroseconds(1800);
digitalWrite(5,LOW);
delay(20);
}
delay(1000);
}

89
Arduino-
Digital Output – Wind –Controlling a Fan
// Connect the fan to Pin 13 and Ground
void setup(){ Controlling a Fan is as easy as sending a HIGH or LOW
pinMode(13, OUTPUT); // Specify Arduino Pin number
and output/input mode Signal to the Pin that the fan is connected to.
}
void loop(){
digitalWrite(13, HIGH); // Turn on Pin 13 sending a
HIGH Signal
delay(1000); // Wait for one second
digitalWrite(13, LOW); // Turn off Pin 13 sending a
LOW Signal
delay(3000); // Wait for Three second
}

90
Arduino-
Digital Output – Rotation –Controlling a DC
Motor
// Connect to Pin 13 and Ground
void setup(){
pinMode(13, OUTPUT); // Specify Arduino Pin number
and output/input modeCode for Rotation/No Rotation
}
void loop(){
digitalWrite(13, HIGH); // Turn on Pin 13 sending a
HIGH Signal
delay(1000); // Wait for one second
digitalWrite(13, LOW); // Turn off Pin 13 sending a
LOW Signal
delay(3000); // Wait for Three second
}

// Connect to Pin 13 and 12


void setup(){
pinMode(13, OUTPUT); // Specify Arduino Pin number
and output/input mode
pinMode(12, OUTPUT);
}
void loop(){
digitalWrite(13, HIGH); // Turn on Pin 13 sending a
HIGH Signal
digitalWrite(12, LOW); //Make Pin 12 a Ground
delay(1000); // Wait for one second
digitalWrite(13, LOW); // Make Pin 13 a Ground
digitalWrite(12, HIGH); // Turn on Pin 12 sending a Code for CW and CCW Rotation
HIGH Signal
delay(3000); // Wait for Three second
}

91
Arduino- Digital Output–Rotation–
V5
Stepper Motor
2

4 Stepper motors translate digital switching sequences into motion.


They are used in a variety of applications requiring precise motions
5
under computer control.
Unlike ordinary dc motors, which spin freely when power is
applied,steppers require that their power source be continuously
pulsed in specific patterns. These patterns, or step sequences,
determine the speed and direction of a stepper’s motion.
For each pulse or step input, the stepper motor rotates a fixed
angular increment; typically 1.8 or 7.5 degrees.
Steppers are driven by the interaction (attraction and repulsion) of
magnetic fields. The driving magnetic field “rotates” as strategically
placed coils are switched on and off. This pushes and pulls at
permanent magnets arranged around the edge of a rotor that drives
the output shaft. 92
93
When the on-off pattern of the magnetic fields is in the
proper sequence, the stepper turns (when it’s not, the Stepper Motor
stepper sits and quivers).

The most common stepper is the four-coil unipolar variety.


These are called unipolar because they require only that
their coils be driven on and off. Bipolar steppers require that
the polarity of power to the coils be reversed.

The normal stepping sequence for four-coil unipolar


steppers appears in the figure. If you run the stepping
sequence in the figure forward, the stepper rotates
clockwise; run it backward, and the stepper rotates
counterclockwise.

The motor’s speed depends on how fast the controller runs


through the step sequence. At any time the controller can
stop in mid sequence.

If it leaves power to any pair of energized coils on, the motor


is locked in place by their magnetic fields. This points out
another stepper motor benefit: built-in brakes. 94
Stepper Motor

95
Stepper Motor-Direction and Speed
void setup(){
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
}
void loop(){
// Pause between the types that determines the speed
int stepperSpeed=200;// Change to change speed
int dir=1;// change to -1 to change direction
if (dir==1){ //Running Clockwise
digitalWrite(2,HIGH);//Step 1
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,HIGH);//Step 2
digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,LOW);//Step 3
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,LOW);//Step 4
digitalWrite(3,HIGH);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(stepperSpeed);// Pause between the types that determines the speed
}
if (dir==-1){ //Running CounterClockwise
digitalWrite(2,LOW);//Step 4
digitalWrite(3,HIGH);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,LOW);//Step 3
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,HIGH);//Step 2
digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(stepperSpeed);// Pause between the types that determines the speed
digitalWrite(2,HIGH);//Step1
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(stepperSpeed);// Pause between the types that determines the speed
} 96
}
Vibration Motor
: A vibration motor! This itty-bitty, shaftless vibratory motor is perfect for non-audible indicators. Use in any number of applications to indicate to the wearer when
a status has changed. All moving parts are protected within the housing. With a 2-3.6V operating range, these units shake crazily at 3V. Once anchored to a
PCB or within a pocket, the unit vibrates softly but noticeably. This high quality unit comes with a 3M adhesive backing and reinforced connection wires.

http://www.sparkfun.com/products/8449
MigaOne Linear Actuator and Muscle Wires
MigaOne is a unique electric actuator based on Shape Memory Alloy (SMA) wire, also known as muscle wire. Exposing the MigaOne to 10V and 2.7A for half a
second will cause the wires to heat up, contract, and push what ever is attached to the arm with 2.5 lbs. (11N) of force. Surprisingly strong for such a slim
actuator. This is a very new type of actuator with many interesting potential applications. Checkout the datasheet for more ideas and information.

http://www.sparkfun.com/products/8751
http://www.musclewires.com/Products.php
Firgelli Linear Actuator
They come in various shapes and sizes and powers. They are able to initiate straight locomotion.

http://www.robotshop.com/
Flexible Heater
They come in various shapes and sizes and powers. They are able to regulate temperature.

http://www.omega.com/
Solenoid Water Valves
Allow to control flow of fluids electronically.

iklimnet.com
Honeywell.com
jelpc-pneumatic.com
Hagen-Laguna Ultrasonic Fog Generator
Generates mist

MarineDepot.com
Single/Double/Tri Color LED Matrix
7 segment LED Digital Display
LED Strips
RGB LEDs

Sparkfun.com
http://www.jameco.com/
www.ledsupply.com/
http://www.oznium.com/led-strip-flat-head
Arduino-
Digital Output – Controling any Electrical
Device with any power needs using a relay
Externally Powered Device

3v-220v
External Power
Externally Powered Device

// Connect to Pin 13 and Ground


void setup(){
pinMode(13, OUTPUT); // Specify Arduino Pin number and
output/input mode
}
void loop(){
digitalWrite(13, HIGH); // Turn on Pin 13 sending a HIGH Signal
delay(1000); // Wait for one second
digitalWrite(13, LOW); // Turn off Pin 13 sending a LOW Signal
delay(3000); // Wait for Three second
}

GRD Control Pin


104
Input-Analog Sensors : Variable Resistors
There are countless variety of variable resistors to measure all kinds of physical properties. A sensor or
variable resistor changes in its resistance based on the detected level of the physical property and as a
result affect the electricity flow . The decrease or increase in the electricity flow that passes through the
variable resistor is what is read as a signal by Arduino board as an indicator of change in the sensed
property:
Position Sensors/GPS
Distance Sensors
Motion Sensors/ Accelerometer
Tilt Sensors
Digital Compass
Bend Sensors
Pressure Sensors
Tension Sensors
Light Sensors
Color Sensors
Temperature Sensors
Humidity Sensors
Wind Sensor
Gas and Chemical Sensors
Skin Capacity Sensors
Tactile sensors such as push button and Dials and Sliders
Touch Sensors
Magnetic Field Sensors
RFID Tags and Readers/RFID read/write tags and Reader/Writers
1
Motion state Mechanical Sensors
Input Devices-Location-GPS Sensor

Connecting a Parallax GPS module to the Arduino, and using Arduino code enables us to read
information like date, time, location and satellites in view from the GPS Sensor

2
GPS Module and GPS Shield for Arduino
Adding GPS to your Arduino has never been easier. The EM406 plugs easily onto the shield, and you will be able to locate your exact position within a few meters. GPS also
gives you amazingly accurate time! Spark fun website has a complete manual and example sketches for working with GPS modules

http://www.sparkfun.com/commerce/product_info.php?products_id=9898
Input Devices-Location-Digital Compass

Connecting a Parallax Hitachi HM55B Compass, you can get angle to north, as analog data.

4
Hitachi H48C 3-Axis Accelerometer
The Hitachi H48C 3-Axis Accelerometer is an integrated module that can sense gravitational (g) force of ±3g on three axes (X, Y, and Z).This sensor can be used for Tilt
measurement, Multi-axis vibration measurement, Multi-axis movement/lack-of-movement measurements.

http://www.parallax.com/Store/Sensors/AccelerationTilt/tabid/172/CategoryID/47/List/0/SortField/0/Level/a/ProductID/97/Default.aspx
Compass Module with Tilt Compensation - HMC6343
The HMC6343 is a solid-state compass module with tilt compensation from Honeywell. What you get is a compass heading over I2C that stays the same even as you tilt the
board. Solid-state (and many classic water based) compasses fail badly when not held flat. The tilt compensated HMC6343 is crucial for those real-world compass
applications.

http://www.sparkfun.com/commerce/product_info.php?products_id=8656
http://wiring.org.co/learning/libraries/hmc6343sparkfun.html
Input Devices-Orientation/Motion-
Accelerometer
Parallax Hitachi H48C Tri-Axis Accelerometer is an integrated module that can sense gravitational
(g) force of ±3g on three axes (X, Y, and Z). So it helps you detect Movement, Speed and using
time factor the distance covered in a motion in three directions

7
Input Devices-Orientation- Tilt Sensor

The Parallax Memsic 2125 is a low cost, dual-axis thermal accelerometer capable of measuring
tilt, acceleration, rotation, and vibration with a range of ±3 g.
Key Features of the Memsic 2125:
Measure 0 to ±3 g on either axis
Fully temperature compensated over 0° to 70° C range
Simple, pulse output of g-force for X and Y axis
Analog output of temperature (TOut pin)
Low current 3.3 or 5V operation: less than 4 mA at 5 vdc
Dual-axis tilt sensing
Single-axis rotational position sensing
Movement/Lack-of-movement sensing

8
Input Devices-Distance-Range Finder

The PING range finder is an ultrasound sensor from Parallax able of detecting objects up to a 3
meter distance. The sensor comes with 3 pins, two are dedicated to power and ground, while
the third one is used both as input and output.

9
Input Devices-Distance-IR Sensor /IR LED

To make a simple IR distance sensor You can use a Panasonic pna4602m IR sensor and an IR led.
Hardware Requirments
Panasonic pna4602m IR sensor (1)
IR led (1)
220 ohm resistor (2)

10
Infrared Proximity Sensor Short Range - Sharp GP2D120XJ00F
Infrared proximity sensor made by Sharp. Part # GP2D120XJ00F has an analog output that varies from 3.1V at 3cm to 0.3V at 40cm with a supply voltage between 4.5 and
5.5VDC. The sensor has a Japanese Solderless Terminal (JST) Connector. We recommend purchasing the related pigtail below or soldering wires directly to the back of the
module.

Infrared Proximity Sensor Long Range - Sharp GP2Y0A02YK0F


Infrared proximity sensor made by Sharp. Part # GP2Y0A02YK0F has an analog output that varies from 2.8V at 15cm to 0.4V at 150cm with a supply voltage between 4.5 and
5.5VDC. The sensor has a Japanese Solderless Terminal (JST) Connector. We recommend purchasing the related pigtail below or soldering wires directly to the back of the
module. This sensor is great for sensing objects up to 5 feet away!

Infrared Proximity Sensor - Sharp GP2Y0A21YK


Infrared proximity sensor made by Sharp. Part # GP2Y0A21YK has an analog output that varies from 3.1V at 10cm to 0.4V at 80cm. The sensor has a Japanese Solderless
Terminal (JST) Connector. We recommend purchasing the related pigtail below or soldering wires directly to the back of the module.

Infrared Sensor Jumper Wire - 3-Pin JST


Three pin JST connector with red, black, and yellow colors. 5 inch wire outs. This cable comes fully assembled as shown and connects directly to many different Sharp sensors.
Quick and easy, this cable will save you 15-20 minutes over making your own wiring harness.

http://www.sparkfun.com/commerce/product_info.php?products_id=8959
http://www.sparkfun.com/commerce/product_info.php?products_id=8958
http://www.sparkfun.com/commerce/product_info.php?products_id=242
http://www.sparkfun.com/commerce/product_info.php?products_id=8733
Ultrasonic Range Finder - XL-Maxsonar EZ0-4
The XL series of MaxSonars are a super high-performance version of the easy-to-use sonar range finder from Maxbotix. The XL series of this sensor features higher resolution,
longer range, higher power output and better calibration when compared to the LV version. We are extremely pleased with the size, quality, and ease of use of this little
range finder. The sensor provides very accurate readings from 0 to 765cm (0 to 25.1ft) with 1cm resolution. This sensor can be powered with anywhere between 3.3 and
5VDC. Range information can be gathered through one of three methods - analog, serial, or PWM - all of which are active at the same time. The analog output will produce a
voltage proportional to the measured distance, with a sensitivity of (Vcc/1024)V/cm. The serial interface is simple and formatted to RS-232, with voltages ranging from 0 to
Vcc and terminal settings of 9600-8-N-1. Finally, the PWM pin outputs a pulse-width representation of the range with a scale factor of 58us/cm. The Maxsonar-XL series is
offered in the EZ0, EZ1, EZ2, EZ3, and EZ4 versions, each with progressively narrower beam angles allowing the sensor to match the application. Please see beam width
explanation below.

http://www.sparkfun.com/commerce/product_info.php?products_id=9491
http://www.sparkfun.com/commerce/product_info.php?products_id=9492
http://www.sparkfun.com/commerce/product_info.php?products_id=9493
http://www.sparkfun.com/commerce/product_info.php?products_id=9494
http://www.sparkfun.com/commerce/product_info.php?products_id=9495

http://www.arduino.cc/playground/Main/MaxSonar
Photo Interrupter GP1A57HRJ00F
This sensor is composed of an infrared emitter on one upright and a shielded infrared detector on the other. By emitting a beam of infrared light from one upright to the
other, the sensor can detect when an object passes between the uprights, breaking the beam. Used for many applications including optical limit switches, pellet dispensing,
general object detection, etc. Gap width = 10mm . A breakout board is also available. This sensor is best for detecting boundary passage and presence in a particular range.

http://www.sparkfun.com/commerce/product_info.php?products_id=9299
http://www.sparkfun.com/commerce/product_info.php?products_id=9322
IR Reciever and Transmitters from Parallax
Infrared receiver with 38 kHz carrier frequency, for use with our IR Transmitter Assembly Kit. The IR Transmitter Kit consists of: IR LED (#350-00003), LED Standoff (#350-
90000), and LED Light Shield (#350-90001).

IR Reciever and Transmitter from Spark Fun


Sparkfun IR LED is a very simple, clear infrared LED. These devices operate between 940-950nm and work well for generic IR systems including remote control and touch-less
object sensing. 1.5VDC forward voltage and 50mA max forward current. Spark Fun IR Reciever Breakout is a very small infrared receiver. This receiver has all the filtering and
38kHz demodulation built into the unit. Simply point a IR remote at the receiver, hit a button, and you'll see a stream of 1s and 0s out of the data pin.

http://www.parallax.com/Store/Sensors/ColorLight/tabid/175/CategoryID/50/List/0/SortField/0/Level/a/ProductID/177/Default.aspx
http://www.parallax.com/StoreSearchResults/tabid/768/List/0/SortField/4/ProductID/178/Default.aspx?txtSearch=IR+Transmitter+Assembly+Kit
http://www.sparkfun.com/commerce/product_info.php?products_id=9349
http://www.sparkfun.com/commerce/product_info.php?products_id=8554
PIR Motion Detector
This is a simple to use motion sensor. Power it up and wait 1-2 seconds for the sensor to get a snapshot of the still room. If anything moves after that period, the 'alarm' pin
will go low.

http://www.sparkfun.com/commerce/product_info.php?products_id=8630
http://itp.nyu.edu/physcomp/sensors/Reports/PIRMotionSensor
Input Devices-Bend/Pressure Sensor

In a bend sensor, the bending angle is proportional to its resistance.


In Pressure sensor the amount of force on the button area is detected by sensor
16
Input Devices-Tagging-RFID Reader
The Parallax Radio Frequency Identification
(RFID) Reader Module is a solution to read
passive RFID transponder tags from up to 4
inches away. The RFID Reader Module can be
used in a wide variety of hobbyist and
commercial applications, including access
control, automatic identification, robotics,
navigation, inventory tracking, and payment
systems. It requires single +5VDC supply and
has a Bi-color LED for visual indication of
activity.
The reader is a sensor that is provoked by RFID
tags, each passive RFID tag has a unique
identification number that is read by the
reader Parallax RFID Disc Sticker is made of
PVC and has adhesive on one side. This tag can
be glued on flat and clean surfaces. It is 25mm
in diameter, and 1.0mm in thickness, and is
designed to work with RFID Reader. Each card
is preprogrammed with a unique identification
17
number.
RFID Serial Reader Module
This RFID Reader Module (Serial version only) comes with two 54x85mm Rectangle Tags. Designed in cooperation with Grand Idea Studio, the Parallax Radio Frequency
Identification (RFID) Reader Module is the first low-cost solution to read passive RFID transponder tags. The RFID Reader Module can be used in a wide variety of hobbyist
and commercial applications, including access control, automatic identification, robotics, navigation, inventory tracking, payment systems, and car immobilization. There are
a variety of transponder tags that come in different packages. Each tag has a specific range that is within 10% of the given distance for each type of tag. The reason for the
10% is due to environmental conditions and RFID modules.

http://www.parallax.com/StoreSearchResults/tabid/768/txtSearch/RFID/List/0/SortField/4/ProductID/114/Default.aspx
http://www.parallax.com/StoreSearchResults/tabid/768/txtSearch/RFID/List/0/SortField/4/ProductID/115/Default.aspx
http://www.parallax.com/StoreSearchResults/tabid/768/txtSearch/RFID/List/0/SortField/4/ProductID/116/Default.aspx

http://www.parallax.com/Store/Accessories/CommunicationRF/tabid/161/ProductID/688/List/0/Default.aspx?SortField=ProductName,ProductName
RFID Serial Read/Write Module
Designed in cooperation with Grand Idea Studio (www.grandideastudio.com), the Parallax Radio Frequency Identification (RFID) Read/Write Module provides a low-cost
solution to read and write passive RFID transponder tags up to 3 inches away. The RFID transponder tags provide a unique serial number and can store up to 116 bytes of
user data, which can be password protected to allow only authorized access. The RFID Read/Write Module can be used in a wide variety of hobbyist and commercial
applications, including access control, user identification, robotics navigation, inventory tracking, payment systems, car immobilization, and manufacturing automation. It is
Read/Write compatible only with the RFID R/W 54mm x 85mm Rectangle Tag. It is Read compatible with all RFID tags sold by Parallax.

http://www.parallax.com/Store/Accessories/CommunicationRF/tabid/161/CategoryID/36/List/0/SortField/0/catpageindex/2/Level/a/ProductID/688/Default.aspx
http://www.parallax.com/Store/Accessories/CommunicationRF/tabid/161/ProductID/689/List/0/Default.aspx?SortField=ProductName,ProductName
Input Devices-Environment-
Humidity/Temperature Sensor
Parallax Sensirion Temperature/Humidity Sensor is a smart sensor
for both humidity and temperature.Humidity is notoriously difficult
to measure. If you're interested in the details see Tracy Allen's web
site (EME Systems) for his discussion. The Sensirion SHT1x
addresses many of these issues head on., and All that Arduino
has to do is read out the humidity and temperature values through
the two-wire digital serial interface. The only math required is a
simple scale and offset. The SHT1x is factory calibrated so that it
returns temperature with a resolution of 0.01 degrees Celsius and
relative humidity with a resolution of 0.03 percent. The accuracy is
better than most other sensors too.

20
Gas Sensors
LPG Gas Sensor - MQ-6 is a simple-to-use liquefied petroleum gas (LPG) sensor, suitable for sensing LPG (composed of mostly propane and butane) concentrations in the air.
The MQ-6 can detect gas concentrations anywhere from 200 to 10000ppm with a very high sensitivity and fast response.

Carbon Monoxide Sensor - MQ-7 is a simple-to-use Carbon Monoxide (CO) sensor, suitable for sensing CO concentrations in the air. The MQ-7 can detect CO concentrations
anywhere from 20 to 2000ppm with a very high sensitivity and fast response.

Alcohol Gas Sensor - MQ-3 is suitable for detecting alcohol concentration on your breath, just like your common breathalyzer. It has a high sensitivity and fast response time.
Sensor provides an analog resistive output based on alcohol concentration.

Methane CNG Gas Sensor - MQ-4 is a simple-to-use compressed natural gas (CNG) sensor, suitable for sensing natural gas (composed of mostly Methane [CH4])
concentrations in the air. The MQ-4 can detect natural gas concentrations anywhere from 200 to 10000ppm with a very high sensitivity and fast response.

http://www.sparkfun.com/commerce/product_info.php?products_id=9405
http://www.sparkfun.com/commerce/product_info.php?products_id=9404
http://www.sparkfun.com/commerce/product_info.php?products_id=9403
http://www.sparkfun.com/commerce/product_info.php?products_id=8880
INSPEED Vortex Wind Sensor
Rugged wind sensor handles speeds from 5 to over 125 mph. Reed switch/magnet provides one pulse per rotation.

http://www.inspeed.com/anemometers/Vortex_Wind_Sensor.asp
http://community.pachube.com/arduino/anemometer
Light Color Sensor Evaluation Board
The ADJD-S371 is a great little sensor. This evaluation board provides all the necessary support circuitry to actually play with the sensor! It is capable of sensing light color
that is reflected off surfaces.

http://www.sparkfun.com/commerce/product_info.php?products_id=8663
http://interactive-matter.org/2008/08/tinkering-with-adjd-s371-q999/
USB Weather Board
We take the sensitive SCP1000 barometric pressure sensor, add the TEMT6000 ambient light sensor, match it with a sensitive SHT15 humidity sensor, and we give you
weather over USB which allows you to immediately tell what the current pressure, humidity, ambient light level, and temperature is. Graphed over time you can watch
weather fronts move in and the rain come down. Serial output is a single visible ASCII string at 9600bps. There is a footprint and switch for 'RF'. This unit can be powered
from our large solar cell and data can be transmitted via our BlueSMiRF wireless modem! All you need now is a greenhouse to monitor.

http://www.sparkfun.com/commerce/product_info.php?products_id=9800
http://wiring.org.co/learning/libraries/serialweather.html
Light Intensity to Frequency IC
a light sensing circuit wrapped up in a clear plastic casing. This neat little device will convert irradiance (the light energy on the surface of the sensor) into frequency. Working
with a simple input concept like a frequency means that we won’t have to build any extra circuitry to get the full range of information from the circuit, and having an accurate
measure of radiance means that we’ll be able to convert easily over to illuminance, which is how the light looks to us.

http://www.sparkfun.com/commerce/product_info.php?products_id=8940
http://roamingdrone.wordpress.com/2008/11/13/arduino-and-the-taos-tsl230r-light-sensor-getting-started/
Input Devices-Environment-Light Sensor

A light sensor is a variable resistor that detects levels of light intensity. It is an analog sensor and
is the one that we are going to use in this class to learn conceptual framework and actual
techniques of using sensors to sense physical properties of the environment

26
Input Devices-Environment-Color Sensor

With Parallax Color sensor you can detect colors in the environment

27
Push button Switch
Push button switches are perfect as tactile sensors for detecting whether a part is clicked or pushed.

http://www.sparkfun.com/commerce/product_info.php?products_id=97
http://www.sparkfun.com/commerce/product_info.php?products_id=9190
Five way Tactile Switch
It is basically five push buttons packaged as one interface. Great for detection of push and its orientation in five directions with one sensor.

http://www.sparkfun.com/commerce/product_info.php?products_id=10063
Linear Potentiometers
Linear potentiometers are variable resistors that change resistance based on the magnitude of linear disposition of their handle within a limited physical range. They can be
used for detecting change in position of kinetic parts with in a spatial composition within a defined limited range.

http://www.sparkfun.com/commerce/product_info.php?products_id=9119
Logarithmic or Linear Rotary Potentiometers
A rotary potentiometer is an angular measuring device with limited rotation. Turning the pot changes the resistance of the potentiometer. the resistance changes. Connect
VCC to an outer pin, GND to the other, and the center pin will have a voltage that varies from 0 to VCC depending on the rotation of the pot. Rotary potentiometers come in
linear or logarithmic variations. In linear rotary potentiometers the angle of rotation has a linear relation to how the resistance of the potentiometer changes. In logarithmic
potentiometers this relation is not linear and changes exponentially.

http://www.sparkfun.com/commerce/product_info.php?products_id=9940
http://www.sparkfun.com/commerce/product_info.php?products_id=9939
Rotary Encoder
A rotary or "shaft" encoder is an angular measuring device. It is used to precisely measure rotation of motors or to create wheel controllers (knobs) that can turn infinitely
(with no end stop like a potentiometer has). Some of them are also equipped with a pushbutton when you press on the axis (like the ones used for navigation on many music
controllers). They come in all kinds of resolutions, from maybe 12 to at least 1024 steps per revolution. This is a 12-step rotary encoder with a nice 'clicking' feel. It's
breadboard friendly, and has a pretty handy select switch (by pushing in on the knob). The encoder is different from a potentiometer in that an encoder has full rotation
without limits. You can tell how much and in which direction the encoder has been turned. Incorporating the temporal aspect you can also calculate speed of rotation based
on how long it takes the rotary Encoder to move from one step to the next.

http://www.sparkfun.com/commerce/product_info.php?products_id=9117#
http://www.arduino.cc/playground/Main/RotaryEncoders
Thumb Joystick
It is basically a combination of two rotary potentiometers to detect direction in two access perpendicular to each other and a push button to detect push action. The result is
a low-tech joystick input device.

http://www.sparkfun.com/commerce/product_info.php?products_id=9032
Thumb Slide Joystick
This is another interesting Joystick that allows to send information regarding direction in x,y directions. It has an interesting ‘slide’ feeling

http://www.sparkfun.com/commerce/product_info.php?products_id=9032
Blackberry Trackballer Breakout
This is another easy to use tactile interface. The four spindles on the trackball have a tiny circular magnet at the end; each of these are paired with an SMD hall effect sensor,
which are used to measure up, down, left and right movements of the trackball. An SMD momentary switch is placed under the trackball to give you a select switch. The BTN
line will be pulled low when the switch is pressed. Also included on the Trackballer are 4 LEDs: red, blue, green and white. These can be powered to light the clear trackball up
any color you can imagine. Regulated, 2.5-5.25VDC power must be provided to power the Hall sensors. The hall-effect sensors and trackball combo are surprisingly sensitive.
A slight roll of the trackball creates multiple high/low transitions on the four axis pins, easily picked up by any microcontroller. A 360° rotation of the trackball, along a single
axis, will result in about 9 high/low transitions.

http://www.sparkfun.com/commerce/product_info.php?products_id=9320
Reed Switch and Hall effect Sensor for Sensing Magnetic Field
When a reed switch is exposed to a magnetic field, the two ferrous materials inside the switch pull together and the switch closes. When the magnetic field is removed, the
reeds separate and the switch opens. This makes for a great non-contact switch. This switch can carry up to 1.2A. In a hall effect sensor, holding a magnet near the sensor will
cause the output pin to toggle. This makes for a robust presence sensor. A reed sensor also works nicely, but can be limited by the glass encapsulation and size. A hall effect
sensor is much smaller, but can handle less current than a reed switch.

http://www.sparkfun.com/commerce/product_info.php?products_id=8642
http://www.sparkfun.com/commerce/product_info.php?products_id=9312
Scientific 2" Flexible Stretch Sensor
Infrared receiver with 38 kHz carrier frequency, for use with our IR Transmitter Assembly Kit. The IR Transmitter Kit consists of: IR LED (#350-00003), LED Standoff (#350-
90000), and LED Light Shield (#350-90001).

IR Reciever and Transmitter from Spark Fun


Sparkfun IR LED is a very simple, clear infrared LED. These devices operate between 940-950nm and work well for generic IR systems including remote control and touch-less
object sensing. 1.5VDC forward voltage and 50mA max forward current. Spark Fun IR Reciever Breakout is a very small infrared receiver. This receiver has all the filtering and
38kHz demodulation built into the unit. Simply point a IR remote at the receiver, hit a button, and you'll see a stream of 1s and 0s out of the data pin.

http://www.robotshop.com/images-scientific-2inch-stretch-sensor-2.html
38
39
40
41
42
43
44
45
46
47
Button

Digital(on/off, HIHG/LOW,
0,1)

Threshold Passage Sensor

Light

Input

Temperature

Linear

Potentiometer

Analog(0-255)
Rotation

Gas Sensor

Distance sensor

Bend Sensor
48
49
Arduino- Analog Input - Photocell
Connect the photocell in the following
configuration (in accordance to the diagram):

As you know A photocell detects the level of


light intensity. Light intensity can be at many
levels, so it is an analog data type, as a
result the photocell should be connected to
one of the analog pins.

A0
1k

50
Two-legged sensor

**The bend sensor, another two-legged Ground


sensor, is connected to Arduino like the V5 – V 3.3
photocell as well
Analog Pin

Connecting Photocell and other two-legged sensors 51


Arduino- Analog Input - Photocell

void setup(){

Serial.begin(9600); //Begining Serial Connection


}
void loop(){

int in = analogRead(0); // Reading Sensed data from Arduino


Serial.println(in);// Writing Sensed Data to Serial Port
}

1.While running you can see the values of the


photocell by pressing the Serial Monitor button
2. Depending on powering the sensor with 5V or 3.3V
you can change the sensitivity of the sensor
3. Depending on the magnitude of the resistor that you
use you can change the sensitivity of the sensor
52
53
54
Arduino- Analog Input/Digital Output- Your
First Interactive System

55
Arduino- Analog Input/Digital Output- Your
First Interactive System
//Connect Photocell to Analog pin 0
//Connect LED to Digital Pin 13
void setup(){

Serial.begin(9600); //Begining Serial Connection


pinMode(13,OUTPUT);
}
void loop(){

int in = analogRead(0); // Reading Sensed data from Arduino


Serial.println(in);// Writing Sensed Data to Serial Port

if(in<250) digitalWrite(13,HIGH);
if(in>250) digitalWrite(13,LOW);
}

Depending on lighting condition of the environment


you may need to change the critical threshold – 250 at
56
this point- to correspond to the lighting condition
Arduino- Analog Input/Digital Output- Your
First Interactive System
Here in the two IF statements we are
introducing a condition for a threshold, stating
that if the read light intensity is less than the
specified threshold(In this case 250) then it
means that the environment is dark So we are
asking the system to turn the light on. And if the
light intensity is above the specified threshold it
means that the environment has enough light
already so we are asking the system to turn the
light off.
The question always is how to specify this
threshold. For now run the code once and
monitor the sensed values in the Serial port
console to see what is the maximum and
minimum and then choose the threshold
approximately midway. 57
Arduino- Analog Input/Digital Output-
System Calibration
Most of the time we choose the decisive threshold of the system based on the status of the
environmental properties. Changing the environment of the system results in shifts in maximum
and minimum of the range of the sensed data.
As a result when changing the environment of the system we need to calibrate the system and
reset the threshold based on the new range of the sensed data.

The other option is to write the code in a way that the system calibrates itself automatically.

58
Arduino- Analog Input/Digital Output-
//Connect Photocell to Analog pin 0
//Connect LED o Digital Pin 13
int avrage=0;
System Calibration
void setup(){
Serial.begin(9600);//Begining Serial Connection
pinMode(13,OUTPUT);

for (int i=0; i<20; i++){


avrage=avrage+analogRead(0);
}
avrage=avrage/20;
Serial.println("System Ready");
}
void loop(){
int in = analogRead(0);// Reading Sensed data from Arduino
//Serial.println(in);// Writing Sensed Data to Serial Port

if(in<avrage/2) digitalWrite(13,HIGH);
if(in>avrage/2) digitalWrite(13,LOW);
}

59
Arduino- Analog Input/Digital Output-
System Calibration
This way you do not need to calibrate the
system manually. You can design and
implement your responsive system off-site,
install it on site and using the reset bottom on
the board reset the system to calibrate to the
new environment.
Holding down the reset button for five seconds
will do the job.

60
Arduino- Analog Input/Digital Output-
System Calibration

Using Automatic Self-Calibration techniques you can detach the system from the computer and
61
install it as an stand alone piece in the environment
Arduino- Analog Input/Digital Output-
Using Multiple Actuators
We can control multiple Actuators based on sensed physical property from one sensor, defining
multiple threshold beyond which different signals are sent to different sensors resulting in more
than one conditional situation

62
//Connect Photocell to Analog pin 0

Arduino- Analog Input/Digital Output-


//Connect LEDs to Digital Pin 2,3,4,5
int avrage=0;
void setup(){
Serial.begin(9600);//Begining Serial Connection

Using Multiple Actuators


pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
for (int i=0; i<20; i++){
avrage=avrage+analogRead(0);
}
avrage=avrage/20;
Serial.println("System Ready");
Serial.println(avrage);
}
void loop(){
int in = analogRead(0);// Reading Sensed data from Arduino
//Serial.println(in);// Writing Sensed Data to Serial Port
if(in<avrage/5){
digitalWrite(2,HIGH);
digitalWrite(3,HIGH);
digitalWrite(4,HIGH);
digitalWrite(5,HIGH);
}
if((avrage/5<in)&&(in<avrage/4)){
digitalWrite(2,LOW);
digitalWrite(3,HIGH);
digitalWrite(4,HIGH);
digitalWrite(5,HIGH);
}
if((avrage/4<in)&&(in<avrage/3)){
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,HIGH);
}
if((avrage/3<in)&&(in<avrage/2)){
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
}
if((avrage/2<in)&&(in<avrage)){
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5,LOW);
}
63
}
Arduino- Analog Input/Digital Output-
Using Multiple Sensors & Multiple Actuators
We can have multiple sensors. In this Scenario we have two sensors and each sensor is
controlling one LED

64
Digital Pin 2
Digital Pin 3 GND

65
Analog Pin 1 V5 GND Analog Pin 0
Arduino- Analog Input/Digital Output-
Using Multiple Sensors & Multiple Actuators
//Sensor A is Connected to Analog pin 0 and is controlling the LED connected to Digital Pin 2
//Sensor B is Connected to Analog pin 1 and is controlling the LED connected to Digital Pin 3
int averageA;
int averageB;
void setup(){
Serial.begin(9600);
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
for(int i=0;i<10;i++) //Calibrate the first sensor
averageA+=analogRead(0); //Calibrate the first sensor
averageA/=10; //Calibrate the first sensor
for(int i=0;i<10;i++) //Calibrate the second sensor
averageB+=analogRead(1); //Calibrate the second sensor
averageB/=10; //Calibrate the second sensor
Serial.println("System Ready"); //System let us know that the calibration is done
}
void loop(){
int A = analogRead(0);
int B = analogRead(1);
if (A<averageA/2)
digitalWrite(2,HIGH);
else
digitalWrite(2,LOW);
if (B<averageB/2)
digitalWrite(3,HIGH);
else
digitalWrite(3,LOW); 66
}
Detecting Presence of a subject using one photocell

1. Using one Photo sensor you can detect if a subject is near or at a specific point
in the space by detecting the casted shadow on a photo sensor

A shadow is casted on this spot No shadow is casted on this spot

Somebody/Something is here Nobody/Nothing is here

1. Read the amount of Light


2. If the amount of light is less than the threshold it means that a shadow is casted
3. If Something/Someone is casting a shadow at this area it means that He/She/It is there
4. React to this knowledge
5. Go to 1
67
Keeping track of entering and exiting of a subject to and from a
space using two photo sensors

1. Using Two Photo sensors you can detect if a subject has entered a space and is
inside or has left the space and is outside. You can also detect from which point
the subject has entered or left

A B

At first the User is outside and none of the sensors are detecting a shadow

68
Keeping track of entering and exiting of a subject to and from a
space using two photo sensors

1. Using Two Photo sensor you can detect if a subject has intered a space and inside
or has left the space and is outside. You can also detect from which point the
subject has entered or left

A B

At first the User is outside and none of the sensors are detecting a shadow

Shadow is casted at point A

The user was outside and point A is passed >>>>>> The user is entering the space from point A

69
Keeping track of entering and exiting of a subject to and from a
space using two photo sensors

1. Using Two Photo sensor you can detect if a subject has intered a space and inside
or has left the space and is outside. You can also detect from which point the
subject has entered or left

A B

At first the User is outside and none of the sensors are detecting a shadow

Shadow is casted at point A

The user was outside and point A is passed >>>>>> The user is entering the space from point A

Shadow is casted at point B

70
Keeping track of entering and exiting of a subject to and from a
space using two photo sensors

1. Using Two Photo sensor you can detect if a subject has intered a space and inside
or has left the space and is outside. You can also detect from which point the
subject has entered or left

A B

At first the User is outside and none of the sensors are detecting a shadow

Shadow is casted at point A

The user was outside and point A is passed >>>>>> The user is entering the space from point A

Shadow is casted at point B

The user was inside and point B is passed>>>>>> The user is exiting the space from point B

71
Arduino-
Detect Entrance/Exit with two
photocells

72
Arduino-
//Sensor A is Connected to Analog pin 0 and is controlling the LED connected to Digital Pin 2
//Sensor B is Connected to Analog pin 1 and is controlling the LED connected to Digital Pin 3
int averageA;
int averageB;

Detect Entrance/Exit with two


int is_Outside=1;
void setup(){
Serial.begin(9600);
pinMode(2,OUTPUT);

photocells
pinMode(3,OUTPUT);
for(int i=0;i<10;i++) //Calibrate the first sensor
averageA+=analogRead(0); //Calibrate the first sensor
averageA/=10; //Calibrate the first sensor
for(int i=0;i<10;i++) //Calibrate the second sensor
averageB+=analogRead(1); //Calibrate the second sensor
averageB/=10; //Calibrate the second sensor
Serial.println("System Ready"); //System let us know that the calibration is done
Serial.println(averageA);
Serial.println(averageB);
}
void loop(){
int A = analogRead(0);
int B = analogRead(1);
if (A<averageA/2){//Point A is passed
digitalWrite(2,HIGH);
if(is_Outside==1)Serial.println("Subject Enters Room from Point A");
if(is_Outside==-1)Serial.println("Subject Exits Room from Point A");
is_Outside=-is_Outside;
delay(1000);// With delay system avoids multiple reads from one point pass
}else
digitalWrite(2,LOW);
if (B<averageB/2){////Point B is passed
digitalWrite(3,HIGH);
if(is_Outside==1)Serial.println("Subject Enters Room from Point B");
if(is_Outside==-1)Serial.println("Subject Exits Room from Point B");
is_Outside=-is_Outside;
delay(1000);//With delay system avoids multiple reads from one point pass
}else
digitalWrite(3,LOW);
} 73
Arduino-Detecting Movement Direction

74
Arduino-
//Sensor A is Connected to Analog pin 0 and is controlling the LED connected to Digital Pin 2
//Sensor B is Connected to Analog pin 41and is controlling the LED connected to Digital Pin 3
int averageA;
int averageB;

Detecting Movement Direction


int is_Outside=1;
void setup(){
Serial.begin(9600);
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
for(int i=0;i<10;i++) //Calibrate the first sensor
averageA+=analogRead(0); //Calibrate the first sensor
averageA/=10; //Calibrate the first sensor
for(int i=0;i<10;i++) //Calibrate the second sensor
averageB+=analogRead(1); //Calibrate the second sensor
averageB/=10; //Calibrate the second sensor
Serial.println("System Ready"); //System let us know that the calibration is done
Serial.println("Subject is outside!");
}
void loop(){
int A = analogRead(0);
int B = analogRead(1);
if (A<averageA/2){//Point A is passed
digitalWrite(2,HIGH);
if(is_Outside==1)Serial.println("Subject is moving from Right to Left");
if(is_Outside==-1)Serial.println("Subject is moving from Left to Right");
is_Outside=-is_Outside;
delay(1000);// With delay system avoids multiple reads from one point pass
}else
digitalWrite(2,LOW);
if (B<averageB/2){////Point B is passed
digitalWrite(3,HIGH);
if(is_Outside==1)Serial.println("Subject is moving from Left to Right");
if(is_Outside==-1)Serial.println("Subject is moving from Right to Left");
is_Outside=-is_Outside;
delay(1000);//With delay system avoids multiple reads from one point pass
}else
digitalWrite(3,LOW);
}
75
Same Physical Setting, Same Code Different
Interpretation of Sensed Data
In the last two exercises we had the same physical setting, same arrangement of sensors and
circuits and we were sensing the same physical properties, the only difference was how we were
interpreting the data.

76
Detecting
Entrance and Movement Direction from
Single Node

77
Detecting
//Sensor A is Connected to Analog pin 0 and is controlling the LED connected to Digital Pin 2
//Sensor B is Connected to Analog pin 1 and is controlling the LED connected to Digital Pin 3
int averageA;
int averageB;
long a_Passed_Time;

Entrance and
long b_Passed_Time;
int just_Passed=-1;
int people_Count=0;
void setup(){
Serial.begin(9600);

Movement Direction
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
for(int i=0;i<10;i++) //Calibrate the first sensor
averageA+=analogRead(0); //Calibrate the first sensor
averageA/=10; //Calibrate the first sensor

from Single Node


for(int i=0;i<10;i++) //Calibrate the second sensor
averageB+=analogRead(1); //Calibrate the second sensor
averageB/=10; //Calibrate the second sensor
Serial.println("System Ready"); //System let us know that the calibration is done
Serial.println("Nobody is Inside!");
}
void loop(){
int A = analogRead(0);
int B = analogRead(1);
if (A<averageA/2){//Point A is passed
digitalWrite(2,HIGH);
a_Passed_Time=millis();
just_Passed=1;
}
else digitalWrite(2,LOW);
if (B<averageB/2){////Point B is passed
digitalWrite(3,HIGH);
b_Passed_Time=millis();
just_Passed=1;
}
else digitalWrite(3,LOW);
if ((A>averageA/2)&&(B>averageB/2)&&(just_Passed==1))
{
just_Passed=-1;
if(a_Passed_Time>b_Passed_Time){
Serial.println("Somebody Moved from B to A-Somebody Left the Room");
people_Count=people_Count-1;
}
if(a_Passed_Time<b_Passed_Time) {
Serial.println("Subject Moved from A to B-Somebody Entered the Room");
people_Count=people_Count+1;
}
Serial.print("Number of Individuals in the Room = ");
Serial.println(people_Count);
} 78
}
Detecting
//Sensor A is Connected to Analog pin 0 and is controlling the LED connected to Digital Pin 2
//Sensor B is Connected to Analog pin 1 and is controlling the LED connected to Digital Pin 3
int averageA;
int averageB;
long a_Passed_Time;

Entrance and
long b_Passed_Time;
int just_Passed=-1;
int people_Count=0;
void setup(){
Serial.begin(9600);

Movement Direction
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
for(int i=0;i<10;i++) //Calibrate the first sensor
averageA+=analogRead(0); //Calibrate the first sensor
averageA/=10; //Calibrate the first sensor

from Single Node


for(int i=0;i<10;i++) //Calibrate the second sensor
averageB+=analogRead(1); //Calibrate the second sensor
averageB/=10; //Calibrate the second sensor
Serial.println("System Ready"); //System let us know that the calibration is done
Serial.println("Nobody is Inside!");

In this exercise every time that a photocell is covered


}
void loop(){
int A = analogRead(0);
int B = analogRead(1);
if (A<averageA/2){//Point A is passed the system also detects the time of the incident using
millis() function. This function shows how much time
digitalWrite(2,HIGH);
a_Passed_Time=millis();
just_Passed=1;
} has passed since the program is running. Once both
else digitalWrite(2,LOW);
if (B<averageB/2){////Point B is passed
digitalWrite(3,HIGH);
photocells are covered and then are revealed, the
b_Passed_Time=millis(); system checks which photocell has been passed
just_Passed=1;
}
else digitalWrite(3,LOW);
first. if A is passed first then it meanis that the motion
if ((A>averageA/2)&&(B>averageB/2)&&(just_Passed==1))
{
is from A to B meaning somebody has entered the
just_Passed=-1;
if(a_Passed_Time>b_Passed_Time){
room, and if B has been passed first it means that
Serial.println("Somebody Moved from B to A-Somebody Left the Room");
people_Count=people_Count-1;
the motion is from B to A meaning that somebody
}
if(a_Passed_Time<b_Passed_Time) {
has entered the room. The system also Adjusts the
Serial.println("Subject Moved from A to B-Somebody Entered the Room");
people_Count=people_Count+1;
number of individuals in the room accordingly each
}
Serial.print("Number of Individuals in the Room = ");
time that it detects an entrance or exit.
Serial.println(people_Count);
} 79
}
Changing Range of Sensed Data
using different voltage pin or resistors

V=IR
With the Same Photo-Cell, using different resistors or
connecting it to different power outlets V3 vs. V5 you
can have different ranges for your sensing device.

The larger the range gets, the more variations on the


sensed data you have and as a result your circuit is
more sensitive to the variations in the sensed data.

void setup(){
Serial.begin(9600);
}
void loop(){
int in = analogRead(5);
Serial.println(in);
} 80
10*100
=1000
=1k
10*1000
=10,000
=10k
10*100,000
=1000000
=1 Mega

81
Higher Voltage and Higher Resistance gives you Better Light Detection Range

Voltage 3 volt 5 volt


Resistor

10*100 1K 0-625 0-950


=1000 Dark-Light Dark-Light
=1k
10*1000 10 K 0-650 0-1020
=10,000 Dark-Light Dark-Light
=10k
1 Meg 200-674 990-1023
10*100,000
=1000000
=1 Mega

82
Responsive System
Input Photocell-Output Standard Servo
Photocell Covered-Go to 0 Degrees
Photocell Not Covered-Go to 180 Degrees

83
Responsive System
Input Photocell-Output Standard Servo
Rotation Relative To Light Intensity

84
Responsive System
Input Photocell-Output Standard Servo
Photocell Covered-Go to 0 Degrees
Photocell Not Covered-Go to 180 Degrees
#include <Servo.h>

int avrage;
int val;//Variable determining the servo movement
Servo myServo;
void setup(){
Serial.begin(9600);//Begining Serial Connection
pinMode(13,OUTPUT);//Servo White wire connection
for (int i=0; i<20; i++){
avrage=avrage+analogRead(0);
myServo.attach(13);
}
avrage=avrage/20;
Serial.println("System Ready");
Serial.println(avrage);
}
void loop(){
int in = analogRead(0);// Reading Sensed data from Arduino
if (in>avrage/2) val=180;
if (in<avrage/2) val=0;
Serial.println(in);
myServo.write(val);
}
85
Responsive System
Input Photocell-Output Standard Servo
Rotation Relative To Light Intensity
#include <Servo.h>
Servo myServo;

int avrage;
int light_min=80;
int light_max=600;
float lighttoAngle;
void setup(){
Serial.begin(9600);//Begining Serial Connection
pinMode(13,OUTPUT);//Servo White wire connection
myServo.attach(13);
for (int i=0; i<20; i++){
avrage=avrage+analogRead(0);
}
avrage=avrage/20;
Serial.println("System Ready");
Serial.println(avrage);
}
void loop(){
int in = analogRead(0);// Reading Sensed data from Arduino
lighttoAngle=map(in,light_min, light_max,0,180);

Serial.print("Light=");
Serial.println(in);
Serial.print("Angel=");
Serial.println(int(lighttoAngle));
myServo.write(lighttoAngle);
delay(100);
} 86
Arduino-
Light to Angle Conversion

Minimum Value of Light x Maximum Value of Light

Minimum Value of Angle=0 Maximum Value of Angle=180

f(x)

X f(X)
=
Max(x)-Min(x) Max f(x)-Min f(x)

87
Responsive System
Input Photocell-Output Continuous Servo
Direction Change

88
Responsive System
Input Photocell-Output Continuous Servo
Direction Change

int avrage;
int val;
void setup(){
Serial.begin(9600);//Begining Serial Connection
pinMode(13,OUTPUT);//Servo White wire connection
for (int i=0; i<20; i++){
avrage=avrage+analogRead(0);
}
avrage=avrage/20;
Serial.println("System Ready");
Serial.println(avrage);
}
void loop(){
int in = analogRead(0);// Reading Sensed data from Arduino
Serial.println(in);
if(in<avrage-20) val=1200;
if((in>avrage-20)&&(in<avrage+20)) val=1500;
if(in>avrage+20) val=1800;
digitalWrite(13,HIGH);
delayMicroseconds(val); // 1.5ms This is the frequency at which the servo motor should
be static
digitalWrite(13,LOW);
delay(20); // 20ms 89
}
Responsive System
Input Photocell-Output Standard Servo
Facing a Definitive Point

90
Responsive System
Input Photocell-Output Standard Servo
Facing a Definitive Point

91
Responsive System
int avrageA,avrageB,avrageC,avrageD;
int Angle=90;
int counter;
void setup(){
Serial.begin(9600);//Begining Serial Connection

Input Photocell-
pinMode(13,OUTPUT);//Servo White wire connection
for (int i=0; i<20; i++){
avrageA=avrageA+analogRead(5);
avrageB=avrageB+analogRead(4);
avrageC=avrageC+analogRead(3);

Output Standard Servo-


avrageD=avrageD+analogRead(2);
}
avrageA=avrageA/20;
avrageB=avrageB/20;
avrageC=avrageC/20;

Facing a Definitive Point


avrageD=avrageD/20;
Serial.println("System Ready");
Serial.println(avrageA);
Serial.println(avrageB);
Serial.println(avrageC);
Serial.println(avrageD);
}
void loop(){
int inA = analogRead(5);
int inB = analogRead(4);
int inC = analogRead(3);
int inD = analogRead(2);
if(inA<avrageA/2){
Angle=170; counter=0;
}
if(inB<avrageB/2){
Angle=120; counter=0;
}
if(inC<avrageC/2){
Angle=60; counter=0;
}
if(inD<avrageD/2){
Angle=0; counter=0;
}
if((inA>avrageA/2)&&(inB>avrageB/2)&&(inC>avrageC/2)&&(inD>avrageD/2)){
counter=counter+1;
if(counter==100){
Angle=90;
}
}
for(int a=0; a<5; a++){
int pulseWidth = Angle*11+500; // See the formula
digitalWrite(13,HIGH);
delayMicroseconds(pulseWidth);
digitalWrite(13,LOW);
delay(10);
}
}
92
Responsive System
Input Potentiometer-
Output Standard Servo-

93
94
95
96
Changing the arrangement of the sensors and actuators in the same
responsive system in a way that the response of the actuator to the
sensed data can affect the setting of the sensor in some way and as a
result lead to a different read of the properties of the environment, will
give us a feed back system as opposed to a responsive system

97
Changing the range of a Potentiometer using
resistors

If you add a resistor between the ground


and the potentiometer connected to the
ground, you change the range of a resistor.

The other way to change the range is


connecting the potentiometer to 3v instead
of 5v

Analog Pin 0

v5 or v3
Ground

98
Analog Input – Digital Output
Photocell controlling Fan

99
Analog Input – Digital Output
Photocell controlling Fan

int avrage;
void setup(){
Serial.begin(9600);//Begining Serial Connection
pinMode(13,OUTPUT);//Servo White wire connection
for (int i=0; i<20; i++){
avrage=avrage+analogRead(5);
}
avrage=avrage/20;
Serial.println("System Ready");
Serial.println(avrage);
}
void loop(){
int in = analogRead(5);
if(in<avrage-10)
digitalWrite(13,HIGH);
else
digitalWrite(13,LOW);
Serial.println(in);
}

100
Analog Input – Digital Output
Photocell controlling Fan
Changing the setting to a feedback system

101
Analog Input – Digital Output
Temperature controlling Fan

102
Analog Input – Digital Output
Temperatures controlling Fan

int avrage;
void setup(){
Serial.begin(9600);//Begining Serial Connection
pinMode(13,OUTPUT);//Servo White wire connection
for (int i=0; i<20; i++){
avrage=avrage+analogRead(5);
}
Using Resistance in Parallel to Increase avrage=avrage/20;
Serial.println("System Ready");
the Sensitivity of the Sensor Serial.println(avrage);
}
void loop(){
int in = analogRead(5);
if(in>avrage-20)
digitalWrite(13,HIGH);
else
digitalWrite(13,LOW);
Serial.println(in);
} 103
Analog Input – Digital Output
Temperature controlling Fan
Changing a Responsive System to feedback system

104
Digital Input – Output to Processing
Controlling the Screen with a Button
1. Controlling an LED with Push Button
A push‐button will open (or close) a circuit when pressed. Its circuit is shown below. The black
wire goes to ground, the yellow to the pin (2 for this case), and the 10K resistor connects to 5V.
If you connect the 10K resistor to ground and the black wire to 5V you inverse the state of the
push button.

105
Digital Input – Output to Processing
Controlling the Screen with a Button
1. Controlling an LED with Push Button
A push‐button will open (or close) a circuit when pressed. Its circuit is shown below. The black
wire goes to ground, the yellow to the pin (2 for this case), and the 10K resistor connects to 5V.

106
Digital Input – Output to Processing
Controlling the Screen with a Button
1. Controlling an LED with Push Button
A push‐button will open (or close) a circuit when pressed. Its circuit is shown below. The black
wire goes to ground, the yellow to the pin (2 for this case), and the 10K resistor connects to 5V.

void setup(){
Serial.begin(9600);
pinMode(13,OUTPUT);
pinMode(2,INPUT);
}
void loop(){
int in=digitalRead(2);
Serial.println(in);
if (in==0) digitalWrite(13,LOW);
if (in==1) digitalWrite(13,HIGH);
}

107
Sensor: Force Sensitive Resistor (FSR)

FSRs are sensors that allow you to detect physical pressure,


squeezing and weight. FSR is basically a resistor that changes
its resistive value (in ohms Ω) depending on how much its
pressed. These sensors are fairly low cost, and easy to use but
they're rarely accurate. They also vary some from sensor to
sensor perhaps 10%. So basically when you use FSR you
should only expect to get ranges of response. While FSRs can
detect weight, they're a bad choice for detecting exactly how
many pounds of weight are on them. However, for most touch-
sensitive applications like "has this been squeezed or pushed
and about how much" they're a good deal for the money!
The FSR that is included in your package is Interlink 402 model. The
1/2" diameter round part is the sensitive bit. The FSR is made of
2 layers separated by a spacer. The more one presses, the
more of those Active Element dots touch the semiconductor and
that makes the resistance go down. FSR's resistance changes
as more pressure is applied. When there is no pressure, the
sensor looks like an infinite resistor (open circuit), as the
pressure increases, the resistance goes down. It is important to
notice that the graph isn't really linear (its a log/log graph) and
that at especially low force measurements it quickly goes from
infinite to 100KΩ.
Because FSRs are basically resistors, they are non-polarized. That
means you can connect them up 'either way'a and they'll work
just fine! The best way to connect to these is to simply plug them
into a breadboard, or use a clamp-style connector like alligator
clips, female header, or a terminal block. It is also possible to
solder yet, the piece is really delicate

http://www.ladyada.net/learn/sensors/fsr.html
Sensor: Force Sensitive Resistor (FSR)
void setup(){
Serial.begin(9600);
}
void loop(){
int in=analogRead(0);
Serial.println(in);
delay(1000);
}

http://www.ladyada.net/learn/sensors/fsr.html
Sensor: Slide Potentiometer (10 KΩ)

Slide Potentiometer is basically a variable resistance with a tactile


interface. It can be used to detect linear disposition.
Ypu need a pull down resistor (10K) while connecting the
Potentiometer to ground. Connecting the sensor to 5V or 3V
changes the range of the sensibility of the sensor. Alternating 10 K Ω
between the Voltage and Ground pin changes the direction of
Ground
range of sensibility of the sensor.

void setup(){
Serial.begin(9600);
}
void loop(){
int in=analogRead(0);
Serial.println(in);
delay(1000);
}

http://www.sparkfun.com/commerce/product_info.php?products_id=9119
Sensor: Rotary Potentiometer (500 Ω B Single)

Rotary Potentiometer is basically a variable resistance with a tactile


interface. It can be used to detect Rotational disposition.
Connecting the sensor to 5V or 3V changes the range of the sensibility
of the sensor. Alternating between the Voltage and Ground pin
changes the direction of range of sensibility of the sensor.
Keep in mind that rotary potentiometers can be linear or logarithmic.
The one that is included in your package is a linear one.

void setup(){
Serial.begin(9600);
}
void loop(){
int in=analogRead(0);
+5V/+3V
Serial.println(in);
delay(1000);
} Ground
Analog Pin

http://www.futurlec.com/PotRot.shtml
Sensor: PIR Motion Sensor

This is a simple to use motion sensor. Power it up and wait 1-2 seconds for the sensor to
get a snapshot of the still room. If anything moves after that period, the 'alarm' pin
will go low. Red wire is power (5 to 12V). Brown wire is GND. Black wire is open
collector Alarm. The alarm pin is an open collector meaning you will need a pull up
resistor on the alarm pin. This means that on one hand the alarm pin is connected
to the analog input and on the other hand it is connected to 5 volt via a10K resistor
as shown in the photograph.

Take note that by default the sensor read is 1023 and once motion is detected it alternates
between 1023 and 18. so you need to code the sensor in a way that consistent read
means no motion and alternating between low and high read means motion.

void setup () {
Serial.begin (9600);
delay (2000);
// it takes the sensor 2 sec to scan the area around it before detectingpresence.
}
void loop(){
int in=analogRead(0);
Serial.println(in);
delay(1000);
}

http://www.sparkfun.com/commerce/product_info.php?products_id=8630
http://itp.nyu.edu/physcomp/sensors/Reports/PIRMotionSensor
Sensor: PIR Motion Sensor
// example for the PIR motion sensor
int timer = 500;
int alarmPin = 0;
int alarmValue = 0;
int ledPin = 11;
void setup () {
Serial.begin (9600);
pinMode(ledPin, OUTPUT);
pinMode(alarmPin, INPUT);
delay (2000); // it takes the sensor 2 seconds to scan the area around it
}
void loop (){
alarmValue = analogRead(alarmPin);
if (alarmValue < 100){
blinky(); // blinks when the motion has been detected, just for confirmation.
}
delay(timer);
Serial.println (alarmValue);
delay (10);
}

void blinky() {
for(int i=0; i<3; i++) {
digitalWrite(11,HIGH);
delay(200);
digitalWrite(11,LOW);
delay(200);
}
}

http://www.sparkfun.com/commerce/product_info.php?products_id=8630
http://itp.nyu.edu/physcomp/sensors/Reports/PIRMotionSensor
Sensor: GP2D12 Analog Distance Sensor and JST
Cable
It is an analog Distance sensor. Connection is easy: Black to Ground, Red to 5V and
Yellow to Analog Pin. The one that you have is sensitive between 10-80cm. You can
buy ones with different rages.

void setup () {
Serial.begin (9600);
}
void loop(){
int in=analogRead(0);
Serial.println(in);
delay(1000);
}

http://www.lynxmotion.com/p-260-sharp-gp2d12-ir-sensor.aspx
5V Analog 0 GND
Sensor: Tilt Ball Switch Diff Angle:30
The "poor man's" accelerometer! Tilt sensors are switches that can detect basic
motion/orientation. The metal tube has a little metal ball that rolls around in it, when 5V
its tilted upright, the ball rolls onto the contacts sticking out of end and shorts them
together.
int val;
void setup()
{
Serial.begin(9600); // sets the serial port to 9600 10K
pinMode(3, INPUT);
}
void loop()
{ Digital 2 GND
val = digitalRead(2); // read digital I/O pin 2
Serial.println(val); // prints the value read
delay(1000);
}

http://www.adafruit.com/index.php?main_page=product_info&products_id=173
http://www.ladyada.net/learn/sensors/tilt.html
Sensor: Tilt Ball Switch
The "poor man's" accelerometer! Tilt sensors are switches that can detect basic
motion/orientation. The metal tube has a little metal ball that rolls around in it, when
its tilted upright, the ball rolls onto the contacts sticking out of end and shorts them
together.

OR

http://www.adafruit.com/index.php?main_page=product_info&products_id=173
http://www.ladyada.net/learn/sensors/tilt.html
Sensor: MQ7 Air Quality Sensor
This is a simple-to-use Carbon Monoxide (CO) sensor, suitable for sensing CO
concentrations in the air. The MQ-7 can detect CO concentrations anywhere from
20 to 2000ppm.

This sensor has a high sensitivity and fast response time. The sensor's output is an
analog resistance. The drive circuit is very simple; all you need to do is power the
heater coil with 5V, add a load resistance, and connect the output to an ADC.

void setup(){
Serial.begin(9600);
}
void loop(){
int in=analogRead(0);
Serial.println(in);
}

http://wiring.org.co/learning/basics/airqualitymq135.html
https://www.parallax.com/Portals/0/Downloads/docs/prod/sens/MQ-7Datasheet.pdf
Sensor: MQ7 Air Quality Sensor
This is a simple-to-use Carbon Monoxide (CO) sensor, suitable for sensing CO
concentrations in the air. The MQ-7 can detect CO concentrations anywhere from
20 to 2000ppm.

This sensor has a high sensitivity and fast response time. The sensor's output is an
analog resistance. The drive circuit is very simple; all you need to do is power the
heater coil with 5V, add a load resistance, and connect the output to an ADC.

http://wiring.org.co/learning/basics/airqualitymq135.html
https://www.parallax.com/Portals/0/Downloads/docs/prod/sens/MQ-7Datasheet.pdf
*Blow to the sensor, copy the serial data and visualize in excel to see the change
Sensor: IR Distance Sensor 2-10 cm
This small digital distance sensor detects objects between 2 and 10 cm (0.8" and 4")
away. With its quick response time, small size, and low current draw, this sensor is a
good choice for non-contact object detection, and our compact carrier PCB makes it
easy to integrate into your project.. The Power is 5V.

void setup(){
Serial.begin(9600);
}
void loop(){
int in=analogRead(0);
Serial.println(in);
}

http://www.pololu.com/catalog/product/1134
Sensor: IR Distance Sensor 2-10 cm
This sensor is composed of an infrared emitter on one upright and a shielded infrared
detector on the other. By emitting a beam of infrared light from one upright to the
other, the sensor can detect when an object passes between the uprights, breaking
the beam. Used for many applications including optical limit switches, pellet
dispensing, general object detection, etc. Gap width = 10mm. The Power is 5V.

void setup(){
Serial.begin(9600);
pinMode(12,INPUT);
}
void loop(){
int in=digitalRead(12);
Serial.println(in);
}

http://www.sparkfun.com/commerce/product_info.php?products_id=9322
http://www.sparkfun.com/commerce/product_info.php?products_id=9299
Rules of combining Resistors

If R1 and R2 are connected serial:


R3=R1+R2
If R1 and R2 are Connected Parallel
1/R3=1/R1+1/R2
Sensor: Piezo Vibration Sensor - Small Horizontal
Piezo Vibration sensors can be used as nock sensors. The Minisense 100 is a low-cost
cantilever-type vibration sensor loaded by a mass to offer high sensitivity at low
frequencies. Useful for detecting vibration and 'tap' inputs from a user. A small AC
and large voltage (up to +/-90V) is created when the film moves back an forth. A
simple resistor should get the voltage down to ADC (Analog Digital Conversion)
levels. Can also be used for impact sensing or a flexible switch.

void setup() {
Serial.begin(9600);
}
void loop() {
int val = analogRead(0);
if (val>10)Serial.println(val);
if (val>10) digitalWrite(13,HIGH); //Turn on LED Connected to pin 13
if (val<=10) digitalWrite(13,LOW); //Turn off LED Connected to pin 13
}
1Megaohms
Or
100Kohm

Ground Analog Pin 0


http://www.sparkfun.com/commerce/product_info.php?products_id=9198
http://forums.adafruit.com/viewtopic.php?f=8&t=15280
www.arduino.cc/en/Tutorial/KnockSensor
Sensor: Temp Sensor LM35DZ(0-100) or LM335A (-40-100)

Piezo Vibration sensors can be used as nock sensors. The Minisense 100 is a low-cost
cantilever-type vibration sensor loaded by a mass to offer high sensitivity at low
frequencies. Useful for detecting vibration and 'tap' inputs from a user. A small AC
and large voltage (up to +/-90V) is created when the film moves back an forth. A
simple resistor should get the voltage down to ADC (Analog Digital Conversion)
levels. Can also be used for impact sensing or a flexible switch.

Make sure you are not wiring it Vice Versa because this will ruin the unit

void setup(){
Serial.begin(9600); //Begining Serial Connection
}
void loop(){
float in = analogRead(0); // Reading Sensed data from Arduino Analog 5
in=(5.0 * in* 100.0)/1023.0; //convert the analog data to temperature 5V GND
Serial.println(in);// Writing Sensed Data to Serial Port
}

http://pscmpf.blogspot.com/2008/12/arduino-lm35-sensor.html
http://www.ladyada.net/learn/sensors/tmp36.html
http://www.adafruit.com/index.php?main_page=product_info&cPath=35&products_id=165
http://www.sparkfun.com/commerce/product_info.php?products_id=9438
Motion Detection with Movement State Switches[libelium.com]
/*
Parallex PIR Sensor and Detecting Motion
Source: http://www.arduino.cc/playground/Code/PIRsense
The code switches an LED according to the sensor output:
Motion detected>> LED On, No motion detected>> LED off
Also, the begining and the end of a continious motion is
determined.
PIR detects motion upto 20 ft away by using a Fresnel lens
and infrared-sensitivite elemnt to detect changing pattern
of passive infrared emitted by objects in its vicinity.
The sensors output will be HIGH when motion is detected
Yet, even if motion is present, it goes to LOW from time-

5V
to time, as if no motion is present.
This program ignores LOW-phases shorter than a given time,
assuming continuous motion is present during these phases.
*/
int calibrationTime = 30; //Time for the sensor to callibrate in seconds
long unsigned int lowIn; //
long unsigned int pause = 5000; //Margin for detection of continious motion in miliseconds
boolean lockLow = true;
boolean takeLowTime;
int pirPin = 3; //Digital pin that the PIR sensor is connected to
int ledPin = 13; //Digital pin that LED is connected to
void setup(){
Serial.begin(9600);
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT); 1K
//Callibration of sensor starts
digitalWrite(pirPin, LOW);
Serial.println();
Serial.print("calibrating sensor ");
for(int i = 0; i < calibrationTime; i++){
Serial.print(".");
delay(1000);
}
Serial.println(" done");
Serial.println("SENSOR ACTIVE"); Digital 13 GND
delay(50);
//Callibration of sensor ends
}
void loop(){
if(digitalRead(pirPin) == HIGH){
//motion is detected 1K
//turn the LED on
digitalWrite(ledPin, HIGH);
//if we where previously in noMotion State
if(lockLow){
//Now, we are in Motion State
lockLow = false;
Serial.println("---");
Serial.print("motion detected at ");
Serial.print(millis()/1000);
Serial.println(" sec");
delay(50);
}
// If sensor goes to low state, note the time
takeLowTime = true;
}
if(digitalRead(pirPin) == LOW){
digitalWrite(ledPin, LOW); //the led visualizes the sensors output pin state
if(takeLowTime){
lowIn = millis(); //save the time of the transition from high to LOW
takeLowTime = false; //make sure this is only done at the start of a LOW phase
}
if(!lockLow && millis() - lowIn > pause){ //If the sensor detect no motion and you are in motionState and the duration of this state is more that 5 seconds
lockLow = true; //Accept that we are actually in noMotionState
Serial.print("motion ended at "); //output
Serial.print((millis() - pause)/1000); //Calculate the time of the ending of the continous motion
Serial.println(" sec");
delay(50);

}
}
124
}
Arduino - Analog Sensor - Detecting nocking[sound] using a piezo
The code is detecting nocking and respond to it by controling an LED
Piezo and Piezo vibration Sensor[http://www.meas-spec.com/]

//Connect LED to digital pin 13 and Ground


int ledPin = 13;
//Connect nockSensor to analog pin 0 and 5V
int knockSensor = 0;
int val = 0;
int THRESHOLD = 1000;

void setup() {
pinMode(ledPin, OUTPUT);
1Megaohms
Serial.begin(9600);
}

void loop() {
val = analogRead(knockSensor);
if (val >= THRESHOLD) {
digitalWrite(ledPin, LOW);
} 5V Analog Pin 0
if (val < THRESHOLD) {
digitalWrite(ledPin, HIGH);
}
Serial.println(val);
delay(100); // we have to make a delay to avoid overloading the serial port
}
125
IR transmitter and Receiver
GND Analog 5 5V

void setup(){
Serial.begin(9600); //Beginning Serial Connection
//connect infrared LED to digital pin 13
pinMode(13,OUTPUT);
digitalWrite(13,HIGH);
}
void loop(){
int in = analogRead(5); // Reading Sensed data from Arduino
Serial.println(in);// Writing Sensed Data to Serial Port
}

GND
126
Digital 13
IR transmitter and Receiver-Photointruptor
GND Analog 5 5V

void setup(){
Serial.begin(9600); //Beginning Serial Connection
//connect infrared LED to digital pin 13
pinMode(13,OUTPUT);
}
void loop(){
int in = analogRead(5); // Reading Sensed data from Arduino
digitalWrite(13,HIGH);
Serial.println(in);// Writing Sensed Data to Serial Port
}

GND
127
Digital 13
From Digital Pins Using an On/OFF button to control an LED

Reading light intensity using a photocell and turning an LED on and


From Analog Pins
off based on the read data

From Processing in real-time Controlling an LED from user manipulation in processing


Input
Turning and LED on and off based on the data that is being read in
From File
real-time from a file

From Internet Through


Turning an LED on and off based on input via tele-presence
Processing

From SMS Thorough


Turning an LED on and off based on user input via text messaging
Data Processing

Output to Digital Pins Turning an LED On and Off

Output to Digital Pins with


Diming the light intensity of an LED higher or lower
Analog Support

Output to Processing in real- Controlling what is happening on the screen in Processing based
Output
time on what a photocell is reading as light intensity

Output to File Writing the read light intensity from a photocell to a file for later use

Output to Internet Through Sending the read light intensity from the photocell to a distant
Processing location via processing running an applet to connect to Internet
128
From Digital Pins Using an On/OFF button to control an LED

Reading light intensity using a photocell and turning an LED on and


From Analog Pins
off based on the read data

From Processing in real-time Controlling an LED from user manipulation in processing


Input
Turning and LED on and off based on the data that is being read in
From File
real-time from a file

From Internet Through


Turning an LED on and off based on input via tele-presence
Processing

From SMS Thorough


Turning an LED on and off based on user input via text messaging
Data Processing

Output to Digital Pins Turning an LED On and Off

Output to Digital Pins with


Diming the light intensity of an LED higher or lower
Analog Support

Output to Processing in real- Controlling what is happening on the screen in Processing based
Output
time on what a photocell is reading as light intensity

Output to File Writing the read light intensity from a photocell to a file for later use

Output to Internet Through Sending the read light intensity from the photocell to a distant
Processing location via processing running an applet to connect to Internet
1
Digital Input – Output to Processing
Controlling the Screen with a Button
1. Controlling an LED with Push Button
A push‐button will open (or close) a circuit when pressed. Its circuit is shown below. The black
wire goes to ground, the yellow to the pin (2 for this case), and the 10K resistor connects to 5V.
If you connect the 10K resistor to ground and the black wire to 5V you inverse the state of the
push button.

2
Digital Input – Output to Processing
Controlling the Screen with a Button
1. Controlling an LED with Push Button
A push‐button will open (or close) a circuit when pressed. Its circuit is shown below. The black
wire goes to ground, the yellow to the pin (2 for this case), and the 10K resistor connects to 5V.

3
Digital Input – Output to Processing
Controlling the Screen with a Button
1. Controlling an LED with Push Button
A push‐button will open (or close) a circuit when pressed. Its circuit is shown below. The black
wire goes to ground, the yellow to the pin (2 for this case), and the 10K resistor connects to 5V.

void setup(){
Serial.begin(9600); //start the serial port in order to write
pinMode(2,INPUT); // set the pin 5 as input
pinMode(13, OUTPUT); // set the pin 13 as output
}
void loop(){
int val = digitalRead(2); //read from the pin 5
if(val==LOW)
{
digitalWrite(13, LOW); // sets the LED off
}
else
{
digitalWrite(13, HIGH); // sets the LED on
}
Serial.println(val);
}

4
Digital Input – Output to Processing
Controlling the Screen with a Button
2. Controlling Processing with Push Button
a. Upload the Arduino Code
b. Stop Arduino
c. Run Processing
d. Check which port is available and what is the index of the available port
e. Change the Index in Processing code
//This is Arduino Code // This is Processing Code
void setup(){ import processing.serial.*;
Serial.begin(9600); //start the serial port in order to write int val = 1;
pinMode(2,INPUT); // set the pin 5 as input Serial port;
pinMode(13, OUTPUT); // set the pin 13 as output void setup(){
} size(100,100);
void loop(){ // Use the first available port
int val = digitalRead(2); //read from the pin 5 port = new Serial(this, Serial.list()[1], 9600);
if(val==LOW) // if in arduino the first option in your list is the port that you are connecting to,
{ //change the 1 to Zero, if it is the second leave it as 1
digitalWrite(13, LOW); // sets the LED off println(Serial.list());
} background(255);
else }
{ void draw(){
digitalWrite(13, HIGH); // sets the LED on while (port.available() > 0)
} serialEvent(port.read()); //look for data
Serial.println(val); if (val==1)background(255);
} if (val==0)background(0);
}
void serialEvent(int serial) {
val=serial-48;// Change the character ascii code to numeric value
println(val);
} 5
Analog Input – Output to Processing
Controlling the Screen with a Photocell

void setup(){
Serial.begin(9600);
}
void loop(){
int in = analogRead(5);
Serial.println(in);
}

6
Analog Input – Output to Processing
Controlling the Screen with a Photocell

7
Analog Input – Output to Processing
Controlling the Screen with a Photocell
import processing.serial.*;
int val = 1;
String buff = "";
int NEWLINE = 10;
Serial port;
void setup() {
size(400,400);
// Use the first available port
port = new Serial(this, Serial.list()[1], 9600);
// if in arduino the first option in your list is the port that you are connecting to,
//change the 1 to Zero, if it is the second leave it as 1
println(Serial.list());
background(255);
delay(2000);
}
void draw() {
while (port.available() > 0)
serialEvent(port.read()); //look for data
background(val);
}
void serialEvent(int serial) {
// If the variable "serial" is not equal to the value for
// a new line, add the value to the variable "buff". If the
// value "serial" is equal to the value for a new line,
// save the value of the buffer into the variable "val".
if(serial != NEWLINE) {
buff += char(serial);
}
else {
if (buff.length()>2)
{
buff = buff.substring(0, buff.length()-1);
//println(buff);
//Parse the String into an integer
if(millis()>2000) {
//This is Arduino Code println("OK");
void setup(){ val = Integer.parseInt(buff);
Serial.begin(9600); val=int(map(val,0,800,0,255));
} }
void loop(){ }
int in = analogRead(5); // Clear the value of "buff"
buff = "";
Serial.println(in); } 8
} }
Analog Input – Output to Processing
Painting the Screen with a Photocell
import processing.serial.*;
int val = 1;
String buff = "";
int NEWLINE = 10;

int count;
int dir=1;
Serial port;
void setup(){
size(400,100);
// Use the first available port
port = new Serial(this, Serial.list()[1], 9600);
// if in arduino the first option in your list is the port that you are connecting to,
//change the 1 to Zero, if it is the second leave it as 1
println(Serial.list());
background(255);
}
void draw(){
while (port.available() > 0)
serialEvent(port.read()); //look for data

stroke(val);//Set the stroke color based on the sensed data


line(count,0,count,100);//Draw a line
count=count+dir;//Go one pixel forwards or backwards
if ((count>width)||(count<0)) dir=-dir;
// The dial gets to the limits of the screen,
//change direction
}
void serialEvent(int serial) {
// If the variable "serial" is not equal to the value for
// a new line, add the value to the variable "buff". If the
// value "serial" is equal to the value for a new line,
// save the value of the buffer into the variable "val".
if(serial != NEWLINE) {
buff += char(serial);
}
else {
if (buff.length()>2)
{
buff = buff.substring(0, buff.length()-1);
//println(buff);
//This is Arduino Code //Parse the String into an integer
void setup(){ if(millis()>2000) {
println("OK");
Serial.begin(9600); val = Integer.parseInt(buff);
} val=int(map(val,0,800,0,255));
void loop(){ }
}
int in = analogRead(5); // Clear the value of "buff"
Serial.println(in); buff = "";
9
}
} }
Analog Input – Output to Processing
Painting the Screen with a Two Photocell

10
Analog Pin 4 V5 GND Analog Pin 5
Analog Input – Output to Processing
Controlling the Screen with Two a Photocell

11
Analog Input – Output to Processing
Painting the Screen with Two a Photocell

12
//This is Processing Code
import processing.serial.*;
Analog Input – Output to Processing
int val = 1;
String buff = "";
int NEWLINE = 10;
Painting the Screen with Two a Photocell
Serial port;
int count=0;
Int dir=1;

int valA,valB;
int light_Min=0;
int light_Max=750;
void setup(){
size(400,200);
// Use the first available port
port = new Serial(this, Serial.list()[1], 9600);
// if in arduino the first option in your list is the port that you are connecting to,
//change the 1 to Zero, if it is the second leave it as 1
println(Serial.list());
background(255);
}
void draw(){
while (port.available() > 0)
serialEvent(port.read()); //look for data

stroke(valA);//Set the stroke color based on the sensed data


line(count, 0, count, 100);//Draw a line
stroke(valB);
line(count, 100, count, 200);//Draw a line
count=count+dir;//Go one pixel forwards or backwards
if ((count>width)||(count<0)) dir=-dir;}
void serialEvent(int serial) {
// If the variable "serial" is not equal to the value for
// a new line, add the value to the variable "buff". If the
// value "serial" is equal to the value for a new line,
// save the value of the buffer into the variable "val".
if(serial != NEWLINE) {
buff += char(serial);
}
else {
if (buff.length()>2)
//This is Arduino Code {
void setup(){ buff = buff.substring(0, buff.length()-1);
//println(buff);
Serial.begin(9600); //Parse the String into an integer
if(millis()>2000) {
} println("OK");
void loop(){ val = Integer.parseInt(buff);

int inA = analogRead(5); if (val<2000) valA=int(map((val-1000),light_Min,light_Max,0,255));


int inB = analogRead(4); if (val>=2000) valB=int(map((val-2000),light_Min,light_Max,0,255));
inA=1000+inA;// The photocell A sends data in 1000 Range println("A="+valA);
println("B="+valB);
inB=2000+inB;// The photocell B sends data in 2000 Range }
}
Serial.println(inA); // Clear the value of "buff"
Serial.println(inB); }
buff = "";
13
} }
Input – Output to file via Processing
//This is Processing Code
import processing.serial.*;
PrintWriter output;
int val = 1;
String buff = "";
int NEWLINE = 10;
Serial port;
int valA,valB;
int light_Min=0;
int light_Max=895;

void setup(){
size(200,100);
// Create a new file in the sketch directory
output = createWriter("log.txt");
// Use the first available port
port = new Serial(this, Serial.list()[1], 9600);
// if in arduino the first option in your list is the port that you are connecting to,
//change the 1 to Zero, if it is the second leave it as 1
println(Serial.list());
background(255);
}

void draw(){
while (port.available() > 0)
serialEvent(port.read()); //look for data
output.println("A"+valA+","+"B"+valB); // Write the coordinate to the file
fill(valA);
rect(0,0,100,100);
fill(valB);
rect(100,0,100,100);
}

void serialEvent(int serial) {


// If the variable "serial" is not equal to the value for
// a new line, add the value to the variable "buff". If the
// value "serial" is equal to the value for a new line,
// save the value of the buffer into the variable "val".
if(serial != NEWLINE) {
buff += char(serial);
}
else {
if (buff.length()>2)
{
buff = buff.substring(0, buff.length()-1);
//println(buff);
//Parse the String into an integer
//This is Arduino Code if(millis()>2000) {
println("OK");
void setup(){ val = Integer.parseInt(buff);
if (val<2000) valA=int(map((val-1000),light_Min,light_Max,0,255));
Serial.begin(9600); if (val>=2000) valB=int(map((val-2000),light_Min,light_Max,0,255));
} println("A="+valA);
println("B="+valB);
void loop(){ }
}
int inA = analogRead(5); // Clear the value of "buff"
int inB = analogRead(4); }
buff = "";

inA=1000+inA;// The photocell A sends data in 1000 Range }

inB=2000+inB;// The photocell B sends data in 2000 Range void keyPressed() {


Serial.println(inA); output.flush(); // Writes the remaining data to the file
Serial.println(inB); output.close(); // Finishes the file
exit(); // Stops the program
14
}
}
Reading Data from File-
String lines[];// Array of all the lines in the file
String light_A[];// Array of all the light readings of point A
String light_B[];// Array of all the light readings of point B
int counter=0;// counter that changes value in each loop
int graphScale;// The scale of the graph

Making Graphs
int xPrevA,xPrevB;//x Value of Previous point on the graph
int avrA,avrB;
int yPrevA,yPrevB;// y Value of Previouspoint on the graph
void setup(){
size(800,600);
background(255);
yPrevA=height-10;// Starting from the base line
yPrevB=height-310;// Starting from the base line
lines= loadStrings("log.txt");//loading the data from file to lines array
light_A= new String[lines.length];// set the size of the Array of the data read at point A
light_B= new String[lines.length];// set the size of the Array of the data read at point B
for (int i=0; i < lines.length; i++) {// for each entry in the lines Array
String each_Line[]= split(lines[i], ',');// Split the two values on each line at the ','
light_A[i]=each_Line[0].substring(1);// put the first value minus the 'A' to array A
light_B[i]=each_Line[1].substring(1);// put the second value minus the 'B' to array B
//println(light_A[i]+","+light_B[i]);
}
graphScale=lines.length/width;// Scale factor scales down the graph to the width of the window
line(0,height-10,width,height-10);// Base line of the data grapg of point A
line(0,height-310,width,height-310);// Base line of the data grapg of point B
stroke(200);
for(int i=1;i<10;i++){
line(0,height-10-i*20,width,height-10-i*20);// Grid lines of the data graph of Point A
line(0,height-310-i*20,width,height-310-i*20);// Grid lines of the data graph of Point B
}
}
void draw(){
if (counter<lines.length-1){// for each entry in array A and B
counter=counter+1;// Change the counter
stroke(0,0,0);// Frame color of the rectangles
fill(int(light_A[counter]));// Change the fill color of the rectangle representing the light intensity at
point A
rect(0,0,100,100);
fill(int(light_B[counter]));// Change the fill color of the rectangle representing the light intensity at
point B
rect(100,0,100,100);
// Scaleing and drawing the Graphs
if(counter%graphScale==0){
avrA=avrA/graphScale;// get the avrage of the reads for Point A
avrB=avrB/graphScale;// get the avrage of the reads for Point B
stroke(255,0,0);// Color of the grapg for Point A
line(xPrevA,yPrevA,counter/graphScale,height-10-avrA);// Draw the graph segment for Point A
stroke(0,255,0);// Color of the grapg for Point B
line(xPrevB,yPrevB,counter/graphScale,height-310-avrB);// Draw the graph segment for Point B
xPrevA=counter/graphScale;
xPrevB=counter/graphScale;
yPrevA=height-10-avrA;
yPrevB=height-310-avrB;
avrA=0;
avrB=0;
}
else{
avrA=avrA+int(light_A[counter]);
avrB=avrB+int(light_B[counter]);
}
} 15
}
Controlling Processing with Multiple input from Arduino -
Making RGB colors on Screen Manipulating Potentiometers

16
Controlling Processing with Multiple input from Arduino -
Making RGB colors on Screen Manipulating Potentiometers

Analog Pin 3

Analog Pin 4

Analog Pin 5
Ground

v5
17
Controlling Processing with Multiple input from Arduino - Making RGB colors on Screen
Manipulating Potentiometers
//This is Processing Code
import processing.serial.*;
int val = 1;
String buff = "";
int NEWLINE = 10;
Serial port;
int r,g,b;
void setup(){
size(400,400);
// Use the first available port
port = new Serial(this, Serial.list()[1], 9600);
// if in arduino the first option in your list is the port that you are connecting to,
//change the 1 to Zero, if it is the second leave it as 1
println(Serial.list());
background(255);
}
void draw(){
while (port.available() > 0)
serialEvent(port.read()); //look for data
color c=color(r,g,b);
background(c);
}
void serialEvent(int serial) {
// If the variable "serial" is not equal to the value for
// a new line, add the value to the variable "buff". If the
// value "serial" is equal to the value for a new line,
// save the value of the buffer into the variable "val".
if(serial != NEWLINE) {
buff += char(serial);
}
//This is Arduino Code else {
void setup(){ if (buff.length()>2)
Serial.begin(9600); {
buff = buff.substring(0, buff.length()-1);
} //println(buff);
void loop(){ //Parse the String into an integer
int inR = analogRead(5); if(millis()>2000) {
int inG = analogRead(4); println("OK");
val = Integer.parseInt(buff);
int inB = analogRead(3);
if (val<3000) r=int(map(val,1000,2023,0,255));
inR=1000+inR;// The Red ranges from 1000-2023 if ((val>=3000)&&(val<5000)) g=int(map(val,3000,4023,0,255));
inG=3000+inG;// The Green ranges from 3000-4023 if (val>=5000) b=int(map(val,5000,6023,0,255));
println("R="+r);
inB=5000+inB;// The Blue ranges from 5000-6023 println("G="+g);
println("B="+b);
Serial.println(inR); }
Serial.println(inG); }
Serial.println(inB); // Clear the value of "buff"
} buff = "";
} 18
}
From Digital Pins Using an On/OFF button to control an LED

Reading light intensity using a photocell and turning an LED on and


From Analog Pins
off based on the read data

From Processing in real-time Controlling an LED from user manipulation in processing


Input
Turning and LED on and off based on the data that is being read in
From File
real-time from a file

From Internet Through


Turning an LED on and off based on input via tele-presence
Processing

From SMS Thorough


Turning an LED on and off based on user input via text messaging
Data Processing

Output to Digital Pins Turning an LED On and Off

Output to Digital Pins with


Diming the light intensity of an LED higher or lower
Analog Support

Output to Processing in real- Controlling what is happening on the screen in Processing based
Output
time on what a photocell is reading as light intensity

Output to File Writing the read light intensity from a photocell to a file for later use

Output to Internet Through Sending the read light intensity from the photocell to a distant
Processing location via processing running an applet to connect to Internet
19
User Input from Processing
Controlling one Actuator On Arduino

20
User Input from Processing
Controlling one Actuator On Arduino
// THis is processing Code
import processing.serial.*;
Serial myPort;
color c= color(0,0,0);
void setup(){
background(255,255,255);
size(100,100);
myPort = new Serial(this, Serial.list()[1], 9600);
fill(0,0,0);
}
void draw(){
fill(c);
ellipse(50,50,50,50);
}
// This is Arduino Code void mouseClicked(){
int ledPin = 13; // LED connected to digital pin 13
int val = 0; if (((mouseX>25)&&(mouseX<75))&&((mouseY>25)&&(mouseY<75)))
void setup() if (red(c)==0){
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output c=color(255,0,0);
Serial.begin(9600); myPort.write(1);
} }
void loop()
{ else{
val = Serial.read(); c=color(0,0,0);
if (val==0){digitalWrite(13,LOW);} myPort.write(0);
if (val==1){digitalWrite(13,HIGH);} }
} } 21
User Input from Processing
Controlling Multiple Actuator On Arduino

22
User Input from Processing
Controlling Multiple Actuator On Arduino // THis is processing Code
import processing.serial.*;
Serial myPort;
color colorA,colorB,colorC= color(0,0,0);
void setup(){
background(255,255,255);
size(300,100);
myPort = new Serial(this, Serial.list()[1], 9600);
fill(0,0,0);
}
void draw(){
fill(colorA);
ellipse(50,50,50,50);
fill(colorB);
// This is Arduino Code ellipse(150,50,50,50);
//LED Connects to pin 13,12,11 fill(colorC);
ellipse(250,50,50,50);
int val = 0; }
void setup() void mouseClicked(){
{ if (((mouseX>25)&&(mouseX<75))&&((mouseY>25)&&(mouseY<75)))
pinMode(13, OUTPUT); // sets the digital pin as output if (red(colorA)==0){
colorA=color(255,0,0);
pinMode(12, OUTPUT); // sets the digital pin as output myPort.write(11);
pinMode(11, OUTPUT); // sets the digital pin as output }else{
Serial.begin(9600); colorA=color(0,0,0);
myPort.write(10);
} }
void loop() if (((mouseX>125)&&(mouseX<175))&&((mouseY>25)&&(mouseY<75)))
if (red(colorB)==0){
{ colorB=color(255,0,0);
val = Serial.read(); myPort.write(21);
}else{
if (val==10){digitalWrite(13,LOW);} colorB=color(0,0,0);
myPort.write(20);
if (val==11){digitalWrite(13,HIGH);} }
if (((mouseX>225)&&(mouseX<275))&&((mouseY>25)&&(mouseY<75)))
if (val==20){digitalWrite(12,LOW);} if (red(colorC)==0){

if (val==21){digitalWrite(12,HIGH);}
colorC=color(255,0,0);
myPort.write(31);
if (val==30){digitalWrite(11,LOW);} }else{
colorC=color(0,0,0);
if (val==31){digitalWrite(11,HIGH);} }
myPort.write(30);

} } 23
User Input from Processing
Sending Multiple Analog Data to Arduino-
RGB Colors

24
User Input from Processing
Sending Multiple Analog Data to Arduino-
RGB Colors

25
User Input from Processing
Sending Multiple Analog Data to Arduino-
RGB Colors
// This is Arduino Code // This is Processing Code
import processing.serial.*;
//maximum Amount that you can send to Arduino from Processing is 255 Serial myPort;
int redPin = 11; // this function works on pins 3, 5, 6, 9, 10, and 11. int k=255; color c;
int greenPin = 10; void setup(){
size(255,255);
int bluePin = 9; myPort = new Serial(this, Serial.list()[0], 9600);
int val = 0; colorMode(HSB);
int valR,valG,valB; for(int j=0;j<256;j++)
void setup() for(int i=0;i<256;i++)
{
{ stroke(i,j,k);
pinMode(redPin, OUTPUT); // sets the digital pin as output point(i,255-j);
pinMode(greenPin, OUTPUT); }
pinMode(bluePin, OUTPUT); fill(255);
stroke(0);
Serial.begin(9600); rect(255,0,10,255);
} line(255,127,265,127);
}
void loop() void draw(){
c= get(mouseX,mouseY);
{ int Red= int(map(red(c),0,255,0,84));
val = Serial.read(); int Green=int(map(green(c),0,255,85,179));
if ((val>-1)&&(val<85)) {// recieved data defines the Red value int Blue=int(map(blue(c),0,255,180,255));
valR=val*3; myPort.write(Red);
myPort.write(Green);
} else if ((val>84)&&(val<180)) {// recieved data defines the Green value myPort.write(Blue);
valG=(val-85)*3; println(Red);
} else if (val>179) {// recieved data defines the Blue value println(Green);
valB=(val-180)*3; println(Blue);
}
}
analogWrite(redPin, valR);
analogWrite(greenPin, valG);
analogWrite(bluePin, valB);
}
26
User Input from Processing
Sending Multiple Analog Data to Arduino
Sent Values : Red=0-84 Green=85-179 Blue=180-255
Sensed Value :Red =0-255 Green=0-255 Blue=0-255
Change the Sensed Data to
Identifiable Ranges

Red =Red/3 Green=Green/3+85 Blue=Blue/3+180


The actual values that are passed
to Processing

Red=0-84 Green=85-179 Blue=180-255


Changing the Range of the Value
back to 0-255

Red=Red*3 Green=(Green-85)*3 Blue=(Blue-160)*3


The Changed Values that result in
Actuation of Space

Red =0-255 Green=0-255 Blue=0-255


27
While Sending Data fromProcessing to Arduino the Sendable data range is 0-255
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling the Screen based on Distant User Input

Server Client

1
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling the Screen based on Distant User Input

Server Client

2
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling the Screen based on Distant User Input

1. On the Computer that the server is supposed to run:


1. Connect to Internet
2. Go to “what is my IP Adress website and check the current IP address
3. Run the Server Side Processing Code
2. On the Computer that the client is supposed to run:
1. Connect to Internet
2. Change the IP Address variable to the one that is provided from the server
computer
3. Run the Client Side Processing Code

3
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling the Screen based on Distant User Input
Obtaining IP Address of the Server : http://whatismyip.com/

IP Address (Internet Protocol Address): This number is an exclusive number all information
technology devices (printers, routers, modems, et al) use which identifies and allows them the
ability to communicate with each other on a computer network. There is a standard of
communication which is called an Internet Protocol standard (IP). In laymans terms it is the same
as your home address. In order for you to receive snail mail at home the sending party must have
your correct mailing address (IP address) in your town (network) or you do not receive bills,
pizza coupons or your tax refund. The same is true for all equipment on the internet. Without this
4
specific address, information cannot be received.
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling the Screen based on Distant User Input
// This is code for Client //This is the code for Server
import processing.net.*; import processing.net.*;
Client myClient; Server myServer;
String inString=“000000000; int port = 5204;
//Change to Provided ipAddress from Server int val = 0;
// For simulating Client and Server on the same System “127.0.0.1” void setup() {
String ipAddress="127.0.0.1"; size(100,100);
String Red, Green, Blue; // Starts a myServer on port 5204
void setup() {
size (300, 100);
myServer = new Server(this, port);
// Change the hue, saturation and brightness constant
myClient = new Client(this, ipAddress , 5204); // Paint the screen
} colorMode(HSB);
void draw() { for (int i = 0; i <100; i++) {
if (myClient.available() > 0) { stroke(i*2.5, 255, 255);//stroke(hue,Saturation,Brightness)
line(i, 0, i, 100);
inString = myClient.readString(); println(i);
delay(300); //delay is necessary to avoid system failure }
}
println(inString);
void draw() {
} color c = get(mouseX,mouseY);
// Reading three different data parts fromone incoming string
int Red = int(red(c));
Red = inString.substring(0,3); int Green = int(green(c));
Green =inString.substring(3,6); int Blue = int(blue(c));
// Write the color as a string built of three sets of three digit codes for R G and B
Blue = inString.substring(6,9); String Value = nf (Red,3)+nf (Green,3)+nf (Blue,3);
color c=color(int(Red),int(Green),int(Blue));
background(c); myServer.write(Value);
} println(Value);
} 5
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling the Screen based on Distant Arduino Input

Server Client

6
Tele-presence –
// This is Arduino Code //This is the code for Server
void setup(){ import processing.net.*;
import processing.serial.*;
Serial.begin(9600);
//Change based on range of data read in space
} int minVal=400;
void loop(){
int in = analogRead(5);
int maxVal=900; Connecting Two Processing Platforms via Internet
}
Serial.println(in); Server myServer;
Serial port; Controlling the Screen based on Distant Arduino Input
int InternetPort = 5204;
int val = 0;
String buff = "";
int NEWLINE = 10;
void setup() {
size(100,100);
//connect to Internet
// Starts a myServer on port 5204
myServer = new Server(this, InternetPort);
//Connect to Arduino
// Use the first available port
port = new Serial(this, Serial.list()[1], 9600);
// if in arduino the first option in your list is the port that you are connecting to,
//change the 1 to Zero, if it is the second leave it as 1
println(Serial.list());
background(255);
}
void draw() {
// This is the code for Client
while (port.available() > 0)
import processing.net.*;
serialEvent(port.read()); //look for data
Client myClient;
background(val);
String inString;
//println(val);
String grayColor=“000”;
String Value = nf (val,3);
//Change to Provided ipAddress from Server
myServer.write(Value);
// For simulating Client and Server on the same System “127.0.0.1”
}
void serialEvent(int serial) { String ipAddress="127.0.0.1";
// If the variable "serial" is not equal to the value for void setup() {
// a new line, add the value to the variable "buff". If the size (300, 100);
// value "serial" is equal to the value for a new line, myClient = new Client(this, ipAddress , 5204);
// save the value of the buffer into the variable "val". }
if(serial != NEWLINE) { void draw() {
buff += char(serial);
}
if (myClient.available() > 0) {
else { inString = myClient.readString();
buff = buff.substring(0, buff.length()-1); delay(300); //delay is necessary to avoid system failure
// Parse the String into an integer }
val = Integer.parseInt(buff); // Convering the incoming data to background color
val=int(map(val,minVal,maxVal,0,255));
// Clear the value of "buff" grayColor=inString.substring(0,3);
buff = ""; background(int(grayColor));
} println(grayColor); 7
} }
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling Arduino Output based on Distant Arduino Input

Server Client

8
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling Arduino Output based on Distant Arduino Input
//This is the code for Server
import processing.net.*;
import processing.serial.*;
Server myServer;
Serial port;
int InternetPort = 5204;
int val = 0;
String buff = "";
int NEWLINE = 10;
void setup() {
size(100,100);
//connect to Internet
// Starts a myServer on port 5204
myServer = new Server(this, InternetPort);
//Connect to Arduino
// Use the first available port
port = new Serial(this, Serial.list()[1], 9600);
// if in arduino the first option in your list is the port that you are connecting to,
//change the 1 to Zero, if it is the second leave it as 1 // This is the code for Client
println(Serial.list()); import processing.net.*;
background(255); import processing.serial.*;
} Serial myPort;
void draw() { Client myClient;
while (port.available() > 0) String inString=“000”;
serialEvent(port.read()); //look for data String grayColor;
background(val); //Change to Provided ipAddress from Server
//println(val); // For simulating Client and Server on the same System “127.0.0.1”
String Value = nf (val,3); String ipAddress="127.0.0.1";
// This is Arduino Code myServer.write(Value); void setup() {
int avrage; } myClient = new Client(this, ipAddress , 5204);
void setup(){ void serialEvent(int serial) { myPort = new Serial(this, Serial.list()[8], 9600);
Serial.begin(9600); // If the variable "serial" is not equal to the value for }
for (int i=0; i<20; i++){ // a new line, add the value to the variable "buff". If the void draw() {
avrage=avrage+analogRead(5); // value "serial" is equal to the value for a new line, if (myClient.available() > 0) {
} // save the value of the buffer into the variable "val". inString = myClient.readString(); int val = 0;
avrage=avrage/20; if(serial != NEWLINE) { delay(50); //delay is necessary to avoid system failure void setup()
} buff += char(serial); } {
void loop(){ } else { // Convering the incoming data to background color pinMode(13, OUTPUT); // sets the digital pin as
int in = analogRead(5); buff = buff.substring(0, buff.length()-1); println(inString); output
if (in<avrage-50){ // Parse the String into an integer println("OK"); Serial.begin(9600);
in=200;//Turn On Light val = Integer.parseInt(buff); if (inString!=null) }
Serial.println(in); val=int(val); { void loop()
}else{ // Clear the value of "buff" inString=inString.substring(0,3); {
in=100;//Turn Off Light buff = ""; background(int(inString)); val = Serial.read();
Serial.println(in); } myPort.write(int(inString)); if (val==100){digitalWrite(13,LOW);}
} } } if (val==200){digitalWrite(13,HIGH);}
} } }

9
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling Arduino Output based on Distant Arduino Input

10
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling Arduino Output based on Distant Arduino Input

11
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling Arduino Output based on Distant Arduino Input

12
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling Arduino Output based on Distant Arduino Input

13
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling Arduino Output based on Distant Arduino Input

14
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling Arduino Output based on Distant Arduino Input

15
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling Arduino Output based on Distant Arduino Input
1. First Arduino Connects to The first Processing Using Serial Port.
1. Serial.begin(9600);//Open Serial Port
2. Serial.println(in);//Sending Data via Serial Port

2. First Processing Function as a Server Connecting To the Second Processing via Net, Reading Data from Arduino Using Serial Port and Sending Data to
Client Processing Using Net
1. import processing.net.*;//Importing the net library to Connect to Second Processing and Send Data to it
2. import processing.serial.*;//Importing serial Library to Connect to Arduino and Read from It
3. Server myServer;//Initiating a Server to Send data to Client via net
4. Serial port;//Initiating a Serial Port to Receive Data from Arduino
5. myServer = new Server(this, InternetPort); //Connect to Internet by Starting myServer on port 5204
6. port = new Serial(this, Serial.list()[1], 9600); //Connect to Arduino Use the first available port
7. myServer.write(Value);//Send data to the client Processing via Net

3. Second Processing Functions as a Client Connecting to the First Processing via Net, Reading Data from Server Processing Using Net and Sending Data to
the Second Arduino Using Serial Port
1. import processing.net.*;
2. import processing.serial.*;
3. Serial myPort; //Innitiate a Serial Port
4. Client myClient; //Innitiate a Client
5. myClient = new Client(this, ipAddress , 5204); //Begin Client Connection to Server
6. myPort = new Serial(this, Serial.list()[8], 9600);//Begin Serial Port
7. inString = myClient.readString();//Receive Data from Server via Net
8. myPort.write(int(inString));//Send Data to Arduino via Serial Port

4. Second Arduino Connects to Client Processing and Read Data from it via Serial Port
1. Serial.begin(9600);//Open Serial Connection 16
2. val = Serial.read();//Read Data from Serial Port
Tele-presence –
Connecting Two Processing Platforms via Internet
Controlling Arduino Output based on Distant Arduino Input

17
(Client and Server on Different Computers)
Tele-presence –

Connecting Two Processing Platforms via Internet


Controlling Arduino Output based on Distant Arduino Input
vs.
(Client and Server on the Same Computer)
Synchronized Input/Output-

Actuating the Physical Space and Monitoring the Physical Properties of


the Space at the same time

18
Things that Talk to Eachother
Connecting Two Arduino Together
Master Slave

Master Arduino Can control the Slave Arduino by Sending Data to it. Thus it is better to connect
the devices that monitor the space and sense the changes in the physical properties of the space
to the Master one and connect the Actoators of the space that are activated based on sensed
changes in physical properties of the space to the Slave one

Master/Slave connection is one way if you are short in digital or analog pins and have more
sensors and actoators than the pins that are available on one Arduino 19
Things that Talk to Eachother
Hardware Serial Connection on TX and RX

20
Things that Talk to Eachother
Hardware Serial Connection on TX and RX

//Master //Slave
void setup(){ void setup(){
Serial.begin(9600); Serial.begin(9600);
pinMode(13,OUTPUT); pinMode(13,OUTPUT);
} }
void loop(){ void loop(){
digitalWrite(13,HIGH); int in=Serial.read();
Serial.println(0); if (in==48){
delay(1000); digitalWrite(13,HIGH);
digitalWrite(13,LOW); }
Serial.println(1); if(in==49){
delay(1000); digitalWrite(13,LOW);
} }
}
21
Things that Talk to Each other
Software Connection on pin2 and pin3

22
Things that Talk to Each other
Software Connection
on pin2 and pin3
// this is the code for the arduino board which is the master // this is the code for slave board
// the master can control the slave arduino board if connected to it // connect the slave board to the master board via digital pin 2 and 3
// through hardware serial port tx1 and rx0 or software serial ports // 3 on slave to 2 on master and 2 on slave to 3 on master
// which are introduced with softwareserial library #include <SoftwareSerial.h>
// in this program we are transforming digital pin 2 and 3 to serial transmitter and #define rxPin 2
reciever #define txPin 3
// connect this arduino to the other arduino via digital pin 2 and 3 SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);
// pin 2 of master arduino board is connected to pin 3 of the slave arduino board void setup(){
// pin 3 of master arduino board is connected to pin 2 of the slave arduino board pinMode(rxPin, INPUT);
#include <SoftwareSerial.h> pinMode(txPin, OUTPUT);
#define rxPin 2 pinMode(13,OUTPUT);
#define txPin 3 Serial.begin(9600);
SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin); mySerial.begin(9600);
void setup(){ }
pinMode(rxPin, INPUT); void loop(){
pinMode(txPin, OUTPUT); char in=mySerial.read();
pinMode(13,OUTPUT); Serial.println(in);
Serial.begin(9600); if (in==48){
mySerial.begin(9600); digitalWrite(13,HIGH);
} }
void loop(){ if(in==49){
if(millis()%2000<1000){ digitalWrite(13,LOW);
digitalWrite(13,HIGH); }
mySerial.println(0);
} }
if(millis()%2000>1000){
digitalWrite(13,LOW);
mySerial.println(1);
}
}
23
Things that Talk to Eachother
Multiple Software Connections

24

You might also like