I coded this to create a simple way to interact with physical buttons and send their status to a computer. The goal was to design a basic input system where pressing the buttons could trigger actions in a program like Processing. By using the Arduino to read the button states and send them via serial communication, I can integrate simple physical controls into digital projects, such as building a DIY drum pad or interactive interface. The small delay between readings ensures the data is sent smoothly, without overloading the system, making it easy to expand and refine the project as needed.
import processing.serial.*;
import processing.sound.*;
SoundFile kickDrum;
Serial myConnection;
String incomingData = "";
float pot = 0;
float photo = 0;
float button = 0;
void setup(){
size(600, 600);
printArray(Serial.list()); // List all available ports to verify the correct one
//kick drum:
kickDrum = new SoundFile(this, "BT7AADA.WAV");
// Open serial connection; adjust index if needed
myConnection = new Serial(this, Serial.list()[3], 9600);
myConnection.bufferUntil('\n'); // Buffer until newline character
}
// Change Color Visual
void draw() {
// Change background based on button state
if (button > 0){
background(255); // White when button is pressed
kickDrum.play();
} else {
background(0); // Black otherwise
}
// Use photoresistor value to influence color of the square
fill(photo, 255 - photo, 100 + photo); // Color changes with light sensor
// Draw square shape using pot as the "size"
float halfSize = pot / 2;
rectMode(CENTER); // Draw rectangle from the center
rect(width / 2, height / 2, pot, pot); // Square with side length 'pot'
}
void serialEvent(Serial conn){
incomingData = conn.readString(); // Read the incoming serial data
String[] values = split(trim(incomingData), ","); // Split the data
println(values); // Print received values for debugging
// Map the received values for use in Processing
pot = map(float(values[0]), 0, 4095, 50, width); // Potentiometer to size
photo = map(float(values[1]), 0, 4095, 0, 255); // Photoresistor to color
button = float(values[2]); // Button state
printArray(values); // For debugging, print received values
}