Saturday, June 25, 2011

Displaying Serial data from an Arduino UNO on your computer screen - using Processing

Here is a very basic Processing Sketch that will allow you to receive data from the Serial port attached to the Arduino and display the reading on your computer screen. In my case, the Arduino is connected to COM13. You may need to change this if you decide to follow in my footsteps.


You will need to setup an Arduino sketch to send serial data to the computer using a Serial.println(value) command. The processing sketch will look for the line feed character ' \n' coming from COM13, which will trigger a serialEvent(). You can get processing to look for another character if you want to: just change the character within the bufferUntil() command.
The draw() method is made redundant because the screen updating is handled by the serialEvent() in response to serial data communication with the Arduino UNO



Here is the Processing sketch code:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import processing.serial.*;
Serial myPort;
String sensorReading="";
PFont font;


void setup() {
size(400,200);
myPort = new Serial(this, "COM13", 9600);
myPort.bufferUntil('\n');
font = createFont(PFont.list()[2],32);
textFont(font);
}

void draw() {
//The serialEvent controls the display
}

void serialEvent (Serial myPort){
sensorReading = myPort.readStringUntil('\n');
if(sensorReading != null){
sensorReading=trim(sensorReading);
}

writeText("Sensor Reading: " + sensorReading);
}


void writeText(String textToWrite){
background(255);
fill(0);
text(textToWrite, width/20, height/2);
}
This was formatted using this site.

If you want an Arduino project that goes well with this code, see this post.





No comments:

Post a Comment