Initial commit

parents
Showing with 2459 additions and 0 deletions
## Example files for the title:
# Programming Interactivity 2nd Edition, by Joshua Noble
[![Programming Interactivity 2nd Edition, by Joshua Noble](http://akamaicovers.oreilly.com/images/9781449311445/cat.gif)](https://www.safaribooksonline.com/library/view/title/9781449321482//)
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.
fill(0, 0, 255);
rect(0, 0, 100, 100);
print(" I'm working ");
void setup(){
size(200, 200);
frameRate(30);
print(" all done setting up");
}
void draw() {
println("hi");
}
\ No newline at end of file
int x = 0;
void setup() {
size(300, 300);
}
void draw() {
// make x a little bit bigger
x += 2;
// draw a circle using x as the height and width of the circle
ellipse(150, 150, x, x);
// if x is too big, we can't see it in our window, so put it back
// to 0 and start over
if(x > 300) {
x = 0;
}
}
\ No newline at end of file
void setup() {
size(300, 300);
}
void draw() {
rect(100, 100, 50, 50);
ellipse(200, 200, 40, 40);
line(0, 0, 300, 300);
}
\ No newline at end of file
void setup()
{
}
void draw(){
stroke(0xFFCCFF00); // here we set the color to yellow
strokeWeight(5); // set the stroke weight to 5
// draw the lines
line(0, 100, 600, 400);
line(600, 400, 300, 0);
line(300, 0, 0, 100);
}
\ No newline at end of file
void setup(){
size(400, 400);
}
void draw(){
background(255);
fill(0);
int xVal = mouseX*3-100;
int yVal = mouseY*3-100;
curve(xVal, yVal, 100, 100, 100, 300, xVal, yVal);
curve(xVal, yVal, 100, 300, 300, 300, xVal, yVal);
curve(xVal, yVal, 300, 300, 300, 100, xVal, yVal);
curve(xVal, yVal, 300, 100, 100, 100, xVal, yVal);
}
\ No newline at end of file
void setup() {
size(400, 400);
}
void draw(){
background(255);
fill(0);
beginShape();
vertex(0, 0);
vertex(400, 400);
vertex(mouseX, mouseY);
endShape();
}
\ No newline at end of file
PFont arial;
void setup() {
// make the size of our window
size(300, 300);
// load the font from the system
arial = createFont("Arial", 32);
// set up font so our application is using the font whenever
// we call the text method to write things into the window
textFont(arial, 15);
}
void draw() {
// this makes the background black, overwriting anything there
// we're doing this because we want to make sure we don't end up
// with every set of numbers on the screen at the same time.
background(0);
// here's where we really do the work, putting the mouse position
// in the window at the location where the mouse is currently
text(" position is "+mouseX+" "+mouseY, mouseX, mouseY);
}
\ No newline at end of file
int alphaValue = 0;
void setup() {
size(350, 300);
background(0xFFFFFFFF);
}
void draw() {
background(0xFFFFFFFF);
fill(255, 0, 0, alphaValue);
rect(100, 100, 100, 100);
}
void mousePressed() {
print(mouseX + "\n");
alphaValue = mouseX;
}
\ No newline at end of file
int lastX = 0;
int lastY = 0;
void setup() {
size(400, 400);
}
void draw() {
lastX = mouseX;
lastY = mouseY;
}
void mouseDragged() {
line(lastX, lastY, mouseX, mouseY);
}
\ No newline at end of file
Point[] pts = new Point[6];
int count = 0;
void setup(){
size(500, 500);
}
void draw(){
background(255);
fill(0);
beginShape();
for(int i = 0; i < pts.length; i++){
vertex(pts[i].x, pts[i].y);
}
}
void mousePressed(){
if(count > 5){
count = 0;
}
Point newPoint = new Point(mouseX, mouseY);
pts[count] = newPoint;
count++;
}
class Point{
float x;
float y;
Point(float _x, float _y){
x = _x;
y = _y;
}
}
\ No newline at end of file
PImage img;
void setup() {
size(400, 400);
img = loadImage("sample.jpg");
image(img, 0, 0);
}
void draw() {
image(img, 0, 0);
}
\ No newline at end of file
import processing.video.*;
Movie mov;
void setup() {
size(320, 240);
mov = new Movie(this, "sample.mov");
mov.play();
}
void movieEvent(Movie m) {
m.read();
}
void draw() {
image(mov, 0, 0);
}
\ No newline at end of file
No preview for this file type
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at velit eros, venenatis fringilla mi. Ut mattis aliquet mauris, in dictum elit pellentesque et. Suspendisse et lectus odio. Fusce gravida ultricies diam, id congue nulla rutrum porta. Morbi in libero dui, nec accumsan mauris. Mauris sit amet nunc tellus, ut mollis orci. Proin sapien nunc, iaculis et luctus et, viverra vel tortor. Cras sodales, leo in egestas malesuada, sem nunc rutrum tellus, vel iaculis sapien nisl ac ante. Vestibulum tincidunt, metus eu pharetra varius, augue est posuere dui, vitae pellentesque orci nulla malesuada libero. Donec quis est vel sapien luctus eleifend. Integer fringilla, lectus non faucibus sollicitudin, mauris quam laoreet mauris, ut tempus odio quam non sem. Curabitur a leo at sem faucibus condimentum id non magna.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam dignissim euismod purus, at vestibulum velit dignissim quis. In rhoncus cursus justo id pretium. Etiam pulvinar lacus a eros convallis porta. Fusce et nibh velit. Sed vitae lectus vitae lorem suscipit blandit. Sed id sem in felis mattis sagittis non tincidunt nibh. Ut ultrices ipsum a sapien congue ornare. Nunc nec lacus id est venenatis molestie. Proin facilisis lobortis felis vitae sollicitudin. Fusce ut sem dolor, eu rutrum sapien. Nulla in dignissim diam.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed eu ultrices massa. Nam consectetur velit vitae nisi blandit eget pretium libero varius. Maecenas nisl odio, fermentum sit amet suscipit eu, pellentesque vitae lorem. Nulla pellentesque nulla elementum lectus condimentum pharetra congue nisl aliquam. Vivamus interdum hendrerit est et mollis. In viverra nunc non quam gravida scelerisque. Nam diam arcu, pharetra eget mattis mollis, malesuada vitae dui. Aliquam erat volutpat. Nam auctor molestie dolor vel commodo. Etiam egestas bibendum enim id accumsan. In hac habitasse platea dictumst. Fusce sed ligula eget urna tempus molestie. Quisque id ligula eros. Aenean venenatis odio vel mauris laoreet sit amet dictum nisl gravida.
Ut imperdiet consectetur egestas. Aliquam erat tellus, luctus volutpat bibendum a, mollis vitae lectus. Aliquam a neque sem, vel blandit urna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus vitae velit nec diam semper faucibus. Vestibulum ac justo eget urna aliquam vehicula vitae sit amet velit. Pellentesque vitae tellus orci, eget mollis purus. Sed scelerisque porta lacus nec eleifend. Sed turpis libero, euismod ac varius eu, feugiat id enim. Donec et quam elit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam ligula leo, iaculis quis vehicula quis, lobortis id est. Phasellus vulputate malesuada neque. Pellentesque dictum ornare nulla, ac dictum felis interdum a. Nulla feugiat, est vitae pharetra congue, felis velit tempus turpis, nec dictum velit sem quis ante.
Aliquam accumsan, nulla ultricies lacinia condimentum, tellus sem fringilla felis, ut commodo urna enim facilisis quam. Donec nec odio non dolor vehicula aliquam in vitae dolor. Pellentesque tempor neque aliquet dolor porttitor sit amet adipiscing enim lobortis. Phasellus ut felis ligula, sed interdum nisl. Duis eu rhoncus purus. Cras tellus purus, scelerisque nec ultrices nec, porta sit amet diam. Quisque eu vulputate dui. Nunc gravida lectus commodo libero venenatis venenatis. Mauris viverra adipiscing ligula vitae facilisis. Aenean non ultricies neque. Maecenas in aliquet leo. Nulla mi mauris, dapibus non faucibus sit amet, convallis et lacus. Integer rutrum lobortis mattis. Sed et neque dui, eu dictum arcu.
\ No newline at end of file
void setup(){ size(500, 400); PFont font; font = loadFont("Ziggurat-HTF-Black-32.vlw"); textFont(font, 32); String[] lines = loadStrings("list.txt"); print("there are " + lines.length + " lines in your file"); for (int i=0; i < lines.length; i++) { text(lines[i], 20 + i*30, 50 + i*30);//put each line in a new place } }
void draw()
{
// nothing here
}
void mousePressed()
{
String[] lines = new String[4];lines[0] = "hello";lines[1] = "out";lines[2] = "there";lines[3] = "!";
saveStrings("data/greeting.txt", lines);
}
\ No newline at end of file
void setup() {
pinMode(13, OUTPUT); // sets digital pin 13 as output
}
void loop() {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}
\ No newline at end of file
int ledPin = 9;int brightness = 0;boolean increase; void setup() // run once, when the application starts{ pinMode(ledPin, OUTPUT); // sets the pin where our LED is as an output increase = true;} void loop() // run over and over again{ if(increase) brightness++; else brightness--; if(brightness == 1023 || brightness == 0) increase != increase; analogWrite(ledPin, brightness); // sets the LED on}
\ No newline at end of file
int buttonPin = 10; // choose the input pin (for a pushbutton)
void setup() {
// set the pin for the light as an output pin
pinMode(ledPin, OUTPUT);
// set the pin for the button as an input pin
pinMode(buttonPin, INPUT);
}
void loop() {
// get the value on the pin that the button is connected to
int val = digitalRead(buttonPin);
// check if the input is LOW, this will indicate
// whether the button is pressed
if (val == 0) {
// if the button is pressed, then turn the light on
digitalWrite(lightPin, HIGH); // turn LED ON
// otherwise, turn the light on
} else {
digitalWrite(lightPin, LOW); // turn LED OFF
}
}
\ No newline at end of file
int i = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print(" hey there, just saying hi for the ");
Serial.print(i);
Serial.print("th time. \n");
delay(2000);
i++;
}
\ No newline at end of file
#include <Stepper.h>
Stepper stepper(100, 8, 9, 10, 11); // note that we don't use = new Stepper();
void setup()
{
// set the speed of the motor to 50 RPM
stepper.setSpeed(50);
}
void loop()
{
stepper.step(1);
delay(500);
stepper.step(2);
delay(500);
stepper.step(2);
delay(500);
}
\ No newline at end of file
// first import our header file#include "FirstClass.h"// then import the file that contains the 'print' method#include <iostream> // this is our constructor for the FirstClass objectFirstClass::FirstClass(){ // this is a little magic to get something printed // to the screen printf(" FirstClass \n"); classProperty = 1; // initialize our property} int FirstClass::howManyClasses(){ // once again, just a little message to say 'hello' printf(" howManyClasses method says: 'just one class' \n"); // note that we're returning classProperty, take a look at the method // declaration to understand why we're doing this (hint, it says 'int') return classProperty; // do something else with our property}
\ No newline at end of file
// make sure we have one and only one "First class"#pragma once // give the class a nameclass FirstClass{// declare all the public variables and methods, that is, all the values that can// be sharedpublic: FirstClass(); int howManyClasses();// declare all the private variables and methods, that is, all the values that are// only for the internal workings of the class, not for sharingprivate: int classProperty;};
\ No newline at end of file
#include "FirstClass.h" // all applications must have a 'main' method int main() { FirstClass firstClass; // here is an instance of our class firstClass.howManyClasses(); // here we call a method of that inst. return 0; // here we're all done }
\ No newline at end of file
#include "HelloWorldApp.h"
void HelloWorldApp::setup(){
// no need to do anything here
cout << " just get started here " << endl;
}
void HelloWorldApp::draw(){
ofBackground(255, 255, 255); // background white
ofSetColor(0, 0, 0); // text black
cout << " say hello " << endl;
ofDrawBitmapString("HELLO WORLD!", 100,380);
}
\ No newline at end of file
#pragma once
#include "ofMain.h" // we need to include all the oF files, linked here
class HelloWorldApp : public ofBaseApp{
public:
void setup(); // we need this to start the application
void draw(); // we need this to draw something on the screen
};
#include "HelloWorldApp.h"
int main( ){
// can be oF_WINDOW or oF_FULLSCREEN
// pass in width and height too:
ofSetupOpenGL(1024,768, OF_WINDOW);// <-------- setup the GL context
// this kicks off the running of my app
ofRunApp(new HelloWorldApp());
}
\ No newline at end of file
#include "simpleGraphics.h"
int main( ){
// can be oF_WINDOW or oF_FULLSCREEN
// pass in width and height too:
ofSetupOpenGL(1024,768, OF_WINDOW);// <-------- setup the GL context
// this kicks off the running of my app
ofRunApp(new simpleGraphics());
}
\ No newline at end of file
#include "simpleGraphics.h"
void simpleGraphics::setup(){
ofSetCircleResolution(100);
ofBackground(255,255,255);
ofSetVerticalSync(true);
fillColor.set(255, 0, 0);
}
void simpleGraphics::update()
{
fillColor.setHue(fillColor.getHue()+1);
if(fillColor.getHue() > 254)
fillColor.setHue(0);
}
void simpleGraphics::draw(){
ofBackground(255,255,255);
ofSetColor(fillColor);
ofFill(); // draw "filled shapes"
ofCircle(100,400,100);
// now just an outline
ofNoFill();
ofSetLineWidth(10);
ofSetColor(fillColor);
ofCircle(400,400,200);
}
\ No newline at end of file
#pragma mark once
#include "ofMain.h"
class simpleGraphics : public ofBaseApp{
public:
void setup();
void update();
void draw();
ofColor fillColor;
};
#include "bezierGraphics.h"
void bezierGraphics::setup(){
ofSetCircleResolution(100);
ofBackground(255,255,255);
ofSetVerticalSync(true);
fillColor.setHue(0);
fillColor.setSaturation(255.f);
fillColor.setBrightness(255.f);
}
void bezierGraphics::update()
{
fillColor.setHue(fillColor.getHue()+1);
if(fillColor.getHue() > 254) fillColor.setHue(0);
}
void bezierGraphics::draw(){
float bez1X1 = 400 + (100 * cos(ofGetElapsedTimef()));
float bez1Y1 = 500 + (100 * sin(ofGetElapsedTimef()));
float bez1X2 = 600 + (100 * cos(ofGetElapsedTimef()));
float bez1Y2 = 500 + (100 * sin(ofGetElapsedTimef()));
float bez2X1 = 400 - (100 * cos(ofGetElapsedTimef()));
float bez2Y1 = 500 - (100 * sin(ofGetElapsedTimef()));
float bez2X2 = 600 - (100 * cos(ofGetElapsedTimef()));
float bez2Y2 = 500 - (100 * sin(ofGetElapsedTimef()));
ofFill();
ofSetHexColor(0xffffff - fillColor.getHex());
ofBeginShape();
// first we create the point from which to begin drawing
ofVertex(0,300);
// then create the Bezier vertex
ofBezierVertex(bez1X1,bez1Y1,bez1X2,bez1Y2,900,300);
ofBezierVertex(bez2X1,bez2Y1,bez2X2,bez2Y2,100,300);
// finish the shape
ofVertex(1000,300);
ofEndShape();
ofFill();
ofSetColor(fillColor);
ofBeginShape();
ofVertex(0,300);
ofBezierVertex(650,300,bez2X2,bez2Y2,900,300);
ofBezierVertex(100,300,bez1X2,bez1Y2,100,300);
ofVertex(1000,300);
ofEndShape();
}
\ No newline at end of file
#pragma mark once
#include "ofMain.h"
class bezierGraphics : public ofBaseApp{
public:
void setup();
void update();
void draw();
ofColor fillColor;
};
#include "bezierGraphics.h"
int main( ){
// can be oF_WINDOW or oF_FULLSCREEN
// pass in width and height too:
ofSetupOpenGL(1024,768, OF_WINDOW);// <-------- setup the GL context
// this kicks off the running of my app
ofRunApp(new bezierGraphics());
}
\ No newline at end of file
#include "imageApp.h"
void imageApp::setup(){
milkShakeImg.loadImage("http://programminginteractivity.com/milkshake.jpg");
friesImg.loadImage("http://programminginteractivity.com/fries.jpg");
}
void imageApp::update()
{
friesPosition.y = sin( ofGetElapsedTimef() ) * 50;
shakePosition.x = cos( ofGetElapsedTimef() ) * 50;
}
void imageApp::draw(){
ofBackground(255,255,255);
friesImg.draw( friesPosition.x, friesPosition.y );
milkShakeImg.draw( shakePosition.x, shakePosition.y );
}
\ No newline at end of file
#pragma mark once
#include "ofMain.h"
class imageApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
ofImage milkShakeImg;
ofImage friesImg;
ofVec2f friesPosition;
ofVec2f shakePosition;
};
#include "imageApp.h"
int main( ){
// can be oF_WINDOW or oF_FULLSCREEN
// pass in width and height too:
ofSetupOpenGL(1024,768, OF_WINDOW);// <-------- setup the GL context
// this kicks off the running of my app
ofRunApp(new imageApp());
}
\ No newline at end of file
#include "videoApp.h"
int main( ){
// can be oF_WINDOW or oF_FULLSCREEN
// pass in width and height too:
ofSetupOpenGL(1024,768, OF_WINDOW);// <-------- setup the GL context
// this kicks off the running of my app
ofRunApp(new videoApp());
}
\ No newline at end of file
#include "videoApp.h"
void videoApp::setup()
{
ofBackground(255,255,255);
screenHeight = float(ofGetScreenHeight());
//player.loadMovie("a_movie2.mpeg");// this loads from the data folder
player.loadMovie("http://programminginteractivity.com/fingers.mov"); // this loads from a website
player.play();
player.play();
isPaused = false;
}
void videoApp::update()
{
player.idleMovie();
}
void videoApp::draw()
{
player.draw(20, 20);
}
void videoApp::mouseMoved( int x, int y )
{
float yPos = (mouseY / screenHeight ) * 2.0;
player.setSpeed(yPos);
}
void videoApp::keyPressed (int key) {
if( isPaused ) {
isPaused = false;
} else {
isPaused = true;
}
player.setPaused(isPaused);
}
\ No newline at end of file
#pragma mark once
#include "ofMain.h"
class videoApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
ofVideoPlayer player;
float screenHeight;
bool isPaused;
void mouseMoved( int x, int y );
void keyPressed (int key);
};
#pragma mark once
#include "ofxOpenCv.h"
// everything else as usual
class opencvApp : public ofBaseApp{
// rest of our app
};
\ No newline at end of file
int potentiometerPin = 0;
int ledPin = 13;
int val = 0;
void setup(){
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
val = analogRead(potentiometerPin);
Serial.println(val);
digitalWrite(ledPin, HIGH);
delay(val);
digitalWrite(ledPin, LOW);
delay(val);
}
\ No newline at end of file
int potentiometerPin = 0;
int ledPin = 9;
int val = 0;
void setup(){
// setup isn't doing anything, but we still need it here
}
void loop(){
val = analogRead(potentiometerPin);
Serial.println(val);
analogWrite(ledPin, val/4);
}
\ No newline at end of file
int ledPin = 9;
int amountOfLight = 0;
void setup(){
}
void loop(){
if(amountOfLight &gt; 254) {
amountOfLight = 0;
}
analogWrite(ledPin, amountOfLight);
amountOfLight+=1;
delay(10);
}
\ No newline at end of file
File mode changed
#include <CapSense.h>
CapSense cSensor(4,2); // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
void setup()
{
Serial.begin(9600);
}
void loop()
{
long sensor = cSensor.capSense(30);
Serial.print(" Reading ");
Serial.println(sensor);
delay(50);
}
int alarmPin = 3; // motion alarm output from PIR
int ledPin = 13; // output pin for the LED
int motionAlarm = 0;
void setup(){
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
void loop(){
motionAlarm = digitalRead(alarmPin);
// this is a very simple loop that lights an LED if motion detected
if(motionAlarm == HIGH){
digitalWrite(ledPin, HIGH);// we've detected motion
delay(500);
digitalWrite(ledPin, LOW); // turn off the light
}
}
\ No newline at end of file
long echo = 0;
int usPin = 9; // Ultrasound signal pin
long val = 0;
void setup() {
Serial.begin(9600);
}
long ping(){
pinMode(usPin, OUTPUT); // Switch signalpin to output
digitalWrite(usPin, LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(usPin, HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(usPin, LOW); // Holdoff
pinMode(usPin, INPUT); // Switch signalpin to input
digitalWrite(usPin, HIGH); // Turn on pullup resistor
echo = pulseIn(usPin, HIGH); // Listen for echo
long ultrasoundValue = (echo / 58.138);
return ultrasoundValue;
}
void loop() {
long x = ping();
Serial.println(x);
delay(250); //delay 1/4 seconds.
}
\ No newline at end of file
File mode changed
import processing.serial.*;
// Declare the serial port that we're going to use
Serial arduinoPort;
void setup() {
// uncomment the next line if you want to
// see all the available controllers
// println(Serial.list());
arduinoPort = new Serial(this, Serial.list()[0], 9600);
}
void draw() {}
void keyPressed() {
// Send the key that was pressed
arduinoPort.write(key);
}
\ No newline at end of file
int message = 0; // for incoming serial data
int ledPin = 13;
void setup(){
pinMode(ledPin, OUTPUT);
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() { // do something only when we receive data:
if (Serial.available() < 0) {
// read the incoming byte:
message = Serial.read();
if(message == '!') {
digitalWrite(ledPin, HIGH);
}
if(message == '?') {
digitalWrite(ledPin, LOW);
}
}
}
\ No newline at end of file
#include "OFSendSerial.h"
void OFSendSerial::setup(){
serial.setup("/dev/tty.usbserial-A6004920", 19200);
}
void OFSendSerial::keyPressed (int key){
serial.writeByte(key);
}
\ No newline at end of file
#pragma mark once
#include "ofMain.h"
class OFSendSerial : public ofBaseApp{
public:
void setup();
void keyPressed(int key);
ofSerial serial; // here's our ofSerial object that we'll use
};
int buttonPin = 13;
void setup() {
// open the serial port at 9600 bps:
Serial.begin(9600);
}
void loop() {
if(digitalRead(buttonPin ) == HIGH) {
Serial.print("!");
} else {
Serial.print("?");
}
delay(200);
}
\ No newline at end of file
import processing.serial.*;
Serial arduinoPort;