I made this script for eight buttons. The values are added binary
Code:
ARDUINO:
int pins[] = { 3, 4, 5, 6, 7, 8, 9, 10};
int num_pins = 8;
int old_val, new_val;
void setup()
{
beginSerial(9600);
for (int i = 0; i < num_pins; i++) pinMode(pins[i], INPUT);
old_val = 0; new_val = 0;
}
void loop()
{
new_val = 0;
int pow = 1;
for (int i = 0; i < num_pins; i++) {
new_val += digitalRead(pins[i]) * pow;
pow = pow * 2;
}
if(old_val!=new_val) {
Serial.println(new_val);
delay(100);
}
old_val = new_val;
}
Code:
PROCESSING:
import processing.serial.*;
// ---------------------------------------------------------
Serial myPort;
PFont myFont;
float val;
int[] pin_val;
int lf = 10; // ASCII linefeed
boolean received;
// ---------------------------------------------------------
void setup() {
size(400,200);
myFont = createFont("Arial",18);
textFont(myFont, 18);
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 9600);
myPort.bufferUntil(lf);
pin_val = new int[8];
val = 0;
received = false;
}
// ---------------------------------------------------------
void draw() {
background(0);
fill(255);
textFont(myFont, 18);
text("received: " + val, 10,50);
if (received) rect(10,10,16,16);
received = false;
show_boxes();
}
// ---------------------------------------------------------
void serialEvent(Serial p) {
String myString = myPort.readStringUntil(lf);
if(myString != null){
val = float(myString);
float val2 = val;
received = true;
for(int i=7; i>=0;i--) {
pin_val[i] = 0;
if(val2>=pow(2,i)) {
val2 -= pow(2,i);
pin_val[i] = 1;
}
}
}
}
// ---------------------------------------------------------
void show_boxes() {
for(int i=0; i<pin_val.length; i++) {
fill(255);
textFont(myFont, 9);
text(i+3, 14+i*20, 95);
if(pin_val[i]!=0) fill (200, 100, 0);
rect (10+i*20, 100, 16, 16);
}
}
greetings ascorbin