Plotting Analog Values with Processing

Processing Visualization of Analog Values
Sometimes you need to test the Analog values that you are receiving from the Arduino Board. It’s good to have a sketch that plots the values for you. I’ve written this sketch so that it adjust for the screen height and width. The Arduino code to get the Analog Values can be found here.
import processing.serial.*;
import processing.opengl.*;
Serial port; // Setup a Serial Object
String message = null; // Stores Incomming messages
String elements[] = null; // Stores String Values from Incoming Message
int values[] = { 0,0,0,0,0,0 }; // Holds Values of the current Analog Inputs
int numOfSensors = 4; // Total number of pins being used
int buffHistSize = 120; // Array size that hold history of Analog pin reading
int[][] sensorValues = new int[numOfSensors][buffHistSize]; // Range(0-1024)
int[][] avgAdjSensorValues = new int[numOfSensors][buffHistSize]; // Adjust Avg
void setup() {
smooth();
frameRate(22);
size(640,480, OPENGL);
// INTIATE SERIAL CONNECTION
println(Serial.list());
println("Opening Serial: "+Serial.list()[2]);
port = new Serial(this, Serial.list()[2], 1000000);
println("...Opening the Serial port forces the Diecimila to reboot...");
println("...so wait till the Arduino boots and send out a message...");
// Wait till Arduino boots
while (port.available() == 0 ) { };
println("...Arduino has Completed Booting...");
}
void draw() {
background(0);
readSerialAndParse(); // Load our Array with values from the Serial Port
for(int p = 0; p < numOfSensors; p++) {
updateAbsValueHistory(p, sensorValues[p]); // Calculate Adj Values
drawSensorReadings(p); // Graph Analog Input Values
drawAverageLine(p); // Draw the running Average of the Analog Input
}
}
/**************************************************************
* Check Serial Port and Read in Message, and Parse Info
***************************************************************/
void readSerialAndParse(){
while (port.available() > 0) {
message = port.readStringUntil(10); // Read message until a newline return
if (message != null) {
// println(message); // DEBUG LINE
elements = splitTokens(message);
for (int i =0; i < elements.length && i < 6; i++ ) {
values[i] = int(elements[i]);
}
}
}
// Shift Values Over One, Before we Store the incomingBuffer
// [0][1][2][3] Before Values Move Over, Don't Move the Last One
// [1][2][3][3] After
for( int j = 0; j < numOfSensors; j++ ) {
for (int k = 0; k < buffHistSize - 1; k++) {
sensorValues[j][k] = sensorValues[j][k + 1];
}
}
// Stores the incomingBuffer in the last indexed position
// [1][2][3][3] Make sure you replace the Index Value
// [1][2][3][x] With the latest value, represented with 'x'
for( int a = 0; a < numOfSensors; a++ ) {
sensorValues[a][buffHistSize - 1] = values[a];
}
}
/**************************************************************
* Uses drawGraph to draw all SensorReadings
* Auto Generates Color Value Based on HSB Color Map
* COLOR MAPPING ONLY APPLIES TO 4 SENSORS
* int k represents the index of the sensor Array
*
* PIN
* 1 = Red, index = 0
* 2 = Green, index = 1
* 3 = Cyan, index = 2
* 4 = Purple, index = 3
***************************************************************/
void drawSensorReadings(int k) {
// We are gonna Change the Color Mode Here
colorMode(HSB,100);
pushMatrix();
strokeWeight(2);
stroke( k*(100/numOfSensors), 100, 100, 60);
drawGraph(sensorValues[k]);
//drawGraph(avgAdjSensorValues[k]);
popMatrix();
colorMode(RGB,255);
}
/**************************************************************
* Takes an Array of Values and Plots it out
* Function Adjust for Sketch Size
* Porportionally Maps Range of Analog Values (0-1024) to Height of Sketch
***************************************************************/
void drawGraph(int[] plotData) {
// Adjust for Canvas Size
// Analog input Range is from 0 -
float hRatio = height / 1024.0;
for (int i = 0; i < plotData.length - 1; i++) {
float plotValueCur = plotData[i] * hRatio;
float plotValueNext = plotData[i + 1] * hRatio;
float lineLenght = float(width) / ( plotData.length - 1 );
line(i * lineLenght, plotValueCur, (i + 1) * lineLenght, plotValueNext);
ellipse( (i + 1) * lineLenght, plotValueNext, 3, 3);
}
}
/**************************************************************
* plotData holds a history of the Analog pin Readings
* Make room for the latest by shifting the array from right to left
* Take the raw SensorValue, and calculate it's absolute value from
* the average. Store that number in 'avgAdjSensorValues'
***************************************************************/
void updateAbsValueHistory(int x, int[] plotData) {
// Shift Array values from Right to Left
// Before we find out curent Absolute Value
for (int k = 0; k < plotData.length - 1; k++) {
avgAdjSensorValues[x][k] = avgAdjSensorValues[x][k + 1];
}
int runningAvg = calcAverage(sensorValues[x]);
// Load the last element in Our Array with the Adjusted Value
// It's a Relative Increment from the Average
avgAdjSensorValues[x][plotData.length - 1] = abs(runningAvg - sensorValues[x][plotData.length - 1]);
// println("avgAdjSensor:"+x+" "+avgAdjSensorValues[x][buffHistSize - 1]); // DEBUG LINE
}
/**************************************************************
* Returns the Average Value from a Group of Numbers
* PlotData Values Correlate with Analog Readings Range: (0-1023)
***************************************************************/
int calcAverage(int[] plotData) {
int total = 0;
int average = 0;
for (int i = 0; i < plotData.length - 1; i++) {
total = total + plotData[i];
}
average = int(total/plotData.length);
// println("Avg: "+average); // DEBUGLINE
return average;
}
/**************************************************************
* Draws a line that indicates the Average Value
* 'x' parameter is the index of an array that correlates to the Pin
* Drawn line is adjusted for Height Ratio of Sketch
* Line Color Matches Analog Graph
***************************************************************/
void drawAverageLine(int x) {
// We are gonna Change the Color Mode Here
colorMode(HSB,100);
float hRatio = height / 1024.0;
int adjAnalogAvg = calcAverage(sensorValues[x]);
stroke( x*(100/numOfSensors), 100, 100, 60);
line( 0, adjAnalogAvg * hRatio, width, adjAnalogAvg * hRatio);
colorMode(RGB,255);
}
Arduino’s Analog In Pins

Location of 'Analog In' pins is indicated by highlight.
I’ve got an Arduino Diecimila board that I’m using for a project. It’s has a handy ATMEL microcontroller and a few bells and whistles. One of my project requires the usage of sound sensors which are feed into the Arduino Analog In pins. See the image attached to this post.
Here is an example of Arduino Code, that sends the Analog Read to the Serial Port
// Metronome for Serial Communication
unsigned long previousMillis = 0;
void setup() {
Serial.begin(1000000); // Initiate Serial Communication
}
void loop() {
// [1] SEND ANALOG DATA VIA SERIAL
// CHECK TIME INSTEAD OF USING DELAY
if ( millis() - previousMillis > 33 ) {
previousMillis = millis();
// SEND ANALOG DATA FROM PIN 0 - 5, INCLUSIVE, USING A LOOP
for ( byte i = 0; i < 5; i++) {
Serial.print( analogRead(i) );
Serial.print(' ');
}
// INDICATE CONCLUSION OF DATA, ASCII CARRIAGE RETURN VALUE
Serial.println(10);
}
}
Sketch Template
I’ve put together a “Sketch” Template for Processing, that includes a skeleton for mouse and keyboard interaction. It also includes code for recording your sketch in PDF, Quicktime Movie, and PNG. It’s a little rough. I do have to advise that the more complicated you make your sketch, the higher likely hood that you can have conflicting code. So if you start of with this template, parts of it might conflict with other libraries and code. But for fairly basic sketches this should be a good starting point.
Attached Files:
Cognitive Dissonance
I wonder if I experience cognitive dissonance. Here is the definition according to Wikipedia.
Cognitive dissonance is an uncomfortable feeling caused by holding two contradictory ideas simultaneously. The “ideas” or “cognitions” in question may include attitudes and beliefs, and also the awareness of one’s behavior. The theory of cognitive dissonance proposes that people have a motivational drive to reduce dissonance by changing their attitudes, beliefs, and behaviors, or by justifying or rationalizing their attitudes, beliefs, and behaviors. Cognitive dissonance theory is one of the most influential and extensively studied theories in social psychology.
You are my husband
No man is an island. No man is truly self made. We all depend on each other, whether we choose to recognize our dependance.
Two days ago, a homeless women visited my house, unannounced. She was harmless…
I gave her oatmeal and some cigarettes I had inherited. I only smoke with one person in this whole world. She insited that I was her husband, and I let her stay in the backyard. My roommate came home early, so I decided to go to the market. When I came back, she had entered the house, and he called the police. Apparently, the police could not transport her to the shelter, she was left to wander into someone elses yard.