I made a project wherein a push button connected to Arduino controls the size of a pair of circles in Processing.
Here’s the code:
Arduino
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(3, INPUT);
}
void loop() {
int digitalVal = digitalRead(3);
Serial.write(digitalVal);
}
Processing
import processing.serial.*;
Serial myPort;
int previousVal = 0;
Sphere mySphere0;
Sphere mySphere1;
void setup(){
printArray(Serial.list());
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
size(800, 600);
mySphere0 = new Sphere(random(10,width-10), random(10, height - 10),10);
mySphere1 = new Sphere(width/2,height/2,200);
}
void draw(){
background(0);
mySphere0.render();
mySphere0.update();
mySphere0.checkBounds();
mySphere1.render();
mySphere1.update();
mySphere1.checkBounds();
}
void serialEvent (Serial myPort) {
int inByte = myPort.read();
println(inByte);
if(inByte == 1){
previousVal = 1;
}
else if(inByte == 0){
if(previousVal == 1){
mySphere0.changeSize();
mySphere1.changeSize();
}
previousVal = 0;
}
}
Sphere class
class Sphere{
//declare variables
float xPos;
float yPos;
float xSpeed;
float ySpeed;
float diam;
color c;
//constructor - define variables, setup for the class
Sphere(float x_, float y_, float d_){
c = color(random(0,255),random(0,255),random(0,255));
xPos = x_;
yPos = y_;
xSpeed = random(-3.,5.);
ySpeed = random(-3.,5.);
diam = d_;
}
//declare functions//methods
void render(){
fill(c);
ellipse(xPos, yPos, diam, diam);
}
void update(){
xPos += xSpeed;
yPos += ySpeed;
}
void checkBounds(){
if(xPos >= width || xPos <= 0){
xSpeed = xSpeed * -1;
}
if(yPos >= height ||yPos <= 0){
ySpeed = ySpeed * -1;
}
}
void changeSize(){
diam = random(10, 200);
}
}