This is some example code for communicating between Arduino and processing. It just reads a digital input pin, then changes a Processing window background color to match the input. You can use this with a switch, for instance.
-Bill
---ARDUINO CODE-------
// This is a hyper-simple bit of code that just fires off the digital
// input from pin 2, as a serial port output to Processing.
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println(digitalRead(2));
// you can add the delay below, if you want it to be more sluggish and less good.
//delay(1);
}
-----PROCESSING SKETCH------
// Digital Input Color Changer by Bill Graner
// based on Graph by David A. Mellis (Arduino example app).
// Processing gets Arduino's output as if it is a serial port.
import processing.serial.*;
Serial port;
String buff = "";
int NEWLINE = 10;
String clicker;
void setup()
{
size(1024 , 768);
clicker = "0";
println("Available serial ports:");
println(Serial.list());
// Uses the first port in this list (number 0). Change this to
// select the port corresponding to your Arduino board. The last
// parameter (e.g. 9600) is the speed of the communication. It
// has to correspond to the value passed to Serial.begin() in your
// Arduino sketch.
port = new Serial(this, Serial.list()[0], 9600);
// If you know the name of the port used by the Arduino board, you
// can specify it directly like this.
//port = new Serial(this, "COM1", 9600);
}
void draw()
{
// this code just changes the background color based on the Arduino input.
if (clicker.charAt(0) == '1') {
background(255,0,0);
} else {
background(0,255,0);
}
while (port.available() > 0)
serialEvent(port.read());
}
// This is called when the sketch reads something from Arduino.
void serialEvent(int serial)
{
// This code is all from the Graph example, and it sometimes doesn't work.
// It's usually ok, though, but someone might want to fix it.
if (serial != NEWLINE) {
// Store all the characters on the line.
buff += char(serial);
} else {
// The end of each line is marked by two characters, a carriage
// return and a newline. We're here because we've gotten a newline,
// but we still need to strip off the carriage return.
if (buff.length() > 0) {
buff = buff.substring(0, buff.length()-1);
}
clicker = buff;
buff = "";
}
}
Comments (1)
Do you use any .h files with this code?
Posted by blank | 05.24.09 14:36
Posted on 24. mai 2009 14:36