Processing and Arduino Workshop Material PDF
Processing and Arduino Workshop Material PDF
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.
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
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.
size(400,400);
Hacking the Default Examples
background(255);
Hacking the Default Examples
Your code
Preexisting Code
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
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
You can print the code that you have , using print menu
option
Setting Preferences
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.
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
You find all the information that you need for any command or
code element in this list.
Getting Help-Online Reference
/*
A forward slash followed by an asterisk allows the
multi-line Comment to continue until the opposite
*/
Example:
Comment
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
5 5
122.3+3.1 125.4
((3+2)*-10) + 1 -46
6>3 true
54 < 50 false
Processing-Printing Expression Results
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:
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
It is just an electronic chip with input and output pins that can
send or receive electronical pulses.
Every thing that you sense from or send to an environment is in the form of data
Processing-Data-Variables
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:
if the value of “is it night yet?” is false, not to turn on the light
Processing-Variable Declaration/Assignment
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
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
point(x,y);
point(40,50);
Processing-Graphical Elements-Shapes
line(x1,y1,x2,y2);
line(20,30,70,80);
Processing-Graphical Elements-Shapes
triangle(x1,y1,x2,y2,x3,y3);
triangle(10,10,40,40,25,60);
Processing-Graphical Elements-Shapes
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:
quad(x1,y1,x2,y2,x3,y3,x4,y4);
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:
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
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
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);
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);
Red 255 0 0
Blue 0 0 255
Green 0 255 0
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:
noStroke();
stroke(grayValue);
stroke(grayValue , transparency);
stroke(Red , Green , Blue);
stroke(Red , Green , Blue , transparency);
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);
1 0 1 1 0 1 1 0
1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0
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
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
}
// 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
}
// 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
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:
NOT: if ( !(mouseX<50))
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
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:
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
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
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
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
}
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
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
void setup(){
int boxLength=10;
int boxWidth=30;
int boxHieght=25;
int boxVolume=volume(boxLength,boxWidth,boxHieght);
println(boxVolume);
}
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);
}
Non-Numerical Types:…………………………..
boolean true, false
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)
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.
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
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
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[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
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
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[] 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
/*
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
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.
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 :
(203-65)/(100-0)=1.38
3. The amount that is added at each step is :
Differential that is added at step i:
(180-45)/(800-350)=135/450=0.3
3. The amount that is added at each step is :
Differential that is added :
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[] 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
Wii controller
Kinect 3D camera
Audio
Video
Interactive Screen
Image-
Graphics
Processing output Save to File
Text
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
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.
image(name, x, y) ;
//Place the top corner of the image at (x,y) and displays the image at its original size
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.
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.
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
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;
}
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
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
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
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
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()
translate(33,0);
rect(0, 20, 66, 30);
rect(0, 50, 66, 30);
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:
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
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
float a = sin(PI);
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
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:
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:
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
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
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
.
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
void setup(){
pinMode(13,OUTPUT);
}
void loop(){
digitalWrite(13,LOW);
delay(1000);
digitalWrite(13,HIGH);
delay(1000);
}
Sparkfun Shopping Lists:
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.
9
http://ladyada.net
Other Hardware Choices-Sheilds
Liquidware TouchShield
OLED touch screen shield.
http://www.liquidware.com
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
Movement
Output
Wind Fan
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
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
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
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
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);
}
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
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
}
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()
{
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
}
91
Arduino- Digital Output–Rotation–
V5
Stepper Motor
2
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
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.
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).
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
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).
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)
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):
A0
1k
50
Two-legged sensor
void setup(){
55
Arduino- Analog Input/Digital Output- Your
First Interactive System
//Connect Photocell to Analog pin 0
//Connect LED to Digital Pin 13
void setup(){
if(in<250) digitalWrite(13,HIGH);
if(in>250) digitalWrite(13,LOW);
}
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);
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
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
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
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
The user was outside and point A is passed >>>>>> The user is entering the space from point A
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
The user was outside and point A is passed >>>>>> The user is entering the space from point A
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;
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;
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
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
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.
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
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
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);
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
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)
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Ω)
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)
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
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
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/]
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
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
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
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
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);
}
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
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
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
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 –
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