Serial Lab

The serial lab was a quick one, but serial communication is somethingI’ll certainly be returning to in future projects.

Simple Serial Output

First, we wire up a simple potentiometer to an analog input, and pass the readings to Serial.print and from there, the computer.

In the serial monitor, the values are interpreted as ASCII characters. I had some fun trying to hit the “carriage return” character to break the flow of input up.

This code makes it all work:


int analogPin = 0;
int analogValue = 0;

void setup()
{
// start serial port at 9600 bps:
Serial.begin(9600);
}

void loop()
{
// read analog input, divide by 4 to make the range 0-255:
analogValue = analogRead(analogPin);
analogValue = analogValue / 4;
Serial.print(analogValue, BYTE);
// pause for 10 milliseconds:
delay(10);
}

Simple Serial Output

With a little more code in Processing, we’re able to visualize the serial input. Somewhere along the line, I developed the strange habit of choosing the “cu” interface for the Arduino instead of “tty”, so I had to make the appropriate change to the code. Otherwise, everything went smoothly. Code follows:


/*
Sensor Graphing Sketch

This sketch takes raw bytes from the serial port at 9600 baud and graphs them.

Created 20 April 2005
Updated 5 August 2008
by Tom Igoe
Updated 2 November 2009
by Rob Faludi
*/

import processing.serial.*;

Serial myPort; // The serial port
int graphXPos = 1; // the horizontal position of the graph:

void setup () {
size(400, 300); // window size

// List all the available serial ports
println(Serial.list());
// I know that the fisrt port in the serial list on my mac
// is usually my Arduino module, so I open Serial.list()[0].
// Open whatever port is the one you're using.
try { // attempt to open this port
myPort = new Serial(this, Serial.list()[1], 9600);
}
// if the port cannot be opened, print an error message, then quit
catch (Exception e) {
println("** Error selecting serial port! **");
println(" Have you attached your Arduino? Does your code specify the right port?");
exit();
}
// set inital background:
background(48,31,65);
}
void draw () {
// nothing happens in draw. It all happens in SerialEvent()
}

void serialEvent (Serial myPort) {
// get the byte:
int inByte = myPort.read();
// print it:
println(inByte);
// set the drawing color. Pick a pretty color:
stroke(123,128,158);
// draw the line:
line(graphXPos, height, graphXPos, height - inByte);

// at the edge of the screen, go back to the beginning:
if (graphXPos >= width) {
graphXPos = 0;
// clear the screen:
background(48,31,65);
}
else {
// increment the horizontal position for the next reading:
graphXPos++;
}
}

And that’s about that. Full lab info available here.


About this entry