Arduino code:
const int ledPin = 9; // the pin that the LED is attached to
void setup()
{
// initialize the serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
}
void loop()
{
byte brightness;
// check if data has been sent from the computer:
if (Serial.available())
{
// read the most recent byte (which will be from 0 to 255):
brightness = Serial.read();
Serial.print("brightness: [");
Serial.print(brightness);
Serial.println("]"); // set the brightness of the LED:
analogWrite(ledPin, brightness);
}
}
Processing code:
import processing.serial.*;
Serial port;
void setup()
{
size(256, 150);
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()[1], 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()
{
// draw a gradient from black to white
for (int i = 0; i < 256; i++)
{
stroke(i);
line(i, 0, i, 150);
}
// write the current X-position of the mouse to the serial port as
// a single byte
port.write(mouseX);
}
void serialEvent(Serial port)
{
char c = (char)port.read();
print(c);
}
Processing output:
Available serial ports:
WARNING: RXTX Version mismatch
Jar version = RXTX-2.2pre1
native lib Version = RXTX-2.2pre2
[0] "COM3"
[1] "COM13"
brightness: [0]
brightness: [0]
brightness: [0]
brightness: [0]
brightness: [0]
brightness: [1]
brightness: [3]
brightness: [5]
brightness: [6]
brightness: [8]
brightness: [10]
brightness: [10]
brightness: [11]
brightness: [12]
brightness: [13]
brightness: [13]
brightness: [13]
brightness: [13]
brightness: [13]
brightness: [13]
brightness: [13]
brightness: [13]