As I wrote in the previous post I bought a 3-axis accelerometer and I want to plot its data using Processing but first .. how do I link Arduino with Processing ?
After around 30-35 minutes of try-fail and reading the docs/forums of both softwares I came up with the solution … I’ll link them using their common Serial library.
To make a proof-of-concept … lets write a simple Arduino code that controls the on-board LED based on 2 commands received from the Serial port … if it reads “1” the LED is ON and if it reads “0” the LED is OFF.
int pin_led = 13;
int reply = 0;
void setup()
{
Serial.begin(9600);
pinMode(pin_led, OUTPUT);
}
void loop()
{
if (Serial.available() > 0)
{
reply = Serial.read();
if (reply == '1')
{
digitalWrite(pin_led, HIGH);
}
else if (reply == '0')
{
digitalWrite(pin_led, LOW);
}
}
}
and then lets write a simple Processing code that sends “1” and “0” with a small delay :
import processing.serial.*;
import cc.arduino.*;
Serial serial_port;
void setup()
{
serial_port = new Serial(this, Serial.list()[0], 9600);
}
void draw()
{
serial_port.write('1');
delay(400);
serial_port.write('0');
delay(400);
}
After you upload the Arduino code to the Arduino board and you run Processing code you should see the on-board LED blinking 🙂 Simple, huh?