lunedì 3 ottobre 2011

Arduino and Processing serial communication

This a tutorial about serial communication between processing and arduino.
There are two way to communicate from processing to arduino:
-Using "arduino" library in processing and "Firmata" library in arduino
-Using serial library in processing and arduino
In this tutorial I will use the second way because so you haven't to use any extra library.
First of all connect a potentiometer to arduino like in this image:

Then open arduino software and write the following code:

int potPin = 0;

void setup(){

void loop(){
  int val = map(analogRead(potPin), 0, 1023, 0, 255);

Using Serial.begin(9600) we start a serial communication between arduino and pc,  then using  
int val = map(analogRead(potPin), 0, 1023, 0, 255);
we assign the analog input from pin 0 to the integer "val" and we modify its value using map() function; finally we write the value of  "val" in the serial port.
Now we have to communicate to arduino shield using processing (in this tutorial I use processing because it's more simple but you can do the same thing using other programming language), so open the processing sketch editor and write the following code:

import processing.serial.*;
Serial port;
float brightness = 0;

void setup(){
  size(500, 500);
  port = new Serial(this, "COM3", 9600);

void draw(){

void serialEvent (Serial port){
  brightness = float(port.readStringUntil('\n'));

Using import processing.serial.* we import the processing serial library that we will use to communicate with arduino, then we create a Serial object called "port" and a float called brightness.
In void setup we set the window size and we start communicating with arduino, that is connected to the serial port "COM3" (in this case the arduino port is COM3 but your arduino can be connected in another serial port so if you want to know it, go to start>control panel>devices and printers>device manager and then look for your arduino in the "ports" section) using  
port = new Serial(this, "COM3", 9600);

In void draw we set the background color and we assign the blu color to the "brightness" float.
Finally we create a function called serialEvent and we add the "Serial port"  to its arguments.
In this function we assign the serial port value to the brightness float.

Now if you upload the sketch to arduino and you run the processing code the window bakcgound will change if you move potenziometer.
You can download this project here.
I hope you like this post, please comment or send me an e-mail to

P.S.: I'm happy to say you that my blog has more than 8000 views :DD

Bye, Dami

1 commento: