Code to transmit and receive an array of values

by leah

Arduino code


//define the size of array
#define ARRAYX 2
#define ARRAYY 2
//create the array
int sensorArray [ARRAYX][ARRAYY];
int i,j,x;

void setup()
{
// initialize the serial communication:
Serial.begin(9600);
}

void loop() {
if (x>255)
{
x=0;
}
for (i=0;i
<ARRAYX;i++)
{
for (j=0;j
<ARRAYY;j++)
{
sensorArray[i][j]=x;
x++;
}
}
sendArray();
delay(500);
}

void sendArray ()
{
for (i=0;i
<ARRAYX;i++)
{
for (j=0;j
<ARRAYY;j++)
{
Serial.print(sensorArray[i][j]);
Serial.print('\t'); //tab character
}
Serial.print('\n'); //new line c
}
Serial.print('!');
}

Processing code
import processing.serial.*;
Serial myPort; // The serial port

//variables for collecting and storing information
int ARRAYX = 2;
int ARRAYY = 2;
int [][] sensorArray = new int[ARRAYX][ARRAYY];

//variables for drawing information on the screen
int spacing = 100;
PFont font;

void setup () {
//set the window size:
size(400, 400);
//initialize the font variables
font = loadFont("SansSerif-20.vlw");
textFont(font);

// list all the available serial ports
println(Serial.list());
// open the appropriate port
myPort = new Serial(this, Serial.list()[0], 9600);
// don't generate a serialEvent() until you get an exclamation mark character
myPort.bufferUntil('!');
// set inital background:
background(0);
}

void draw () {
background(40,90,0);
//loop through the array
for (int i=0;i<ARRAYX;i++)
{
for (int j=0;j
<ARRAYY;j++)
{
//calculate the position for each entry so that print out is approximately centered onscreen
int xPosition = width/2-((ARRAYX-1)*spacing/2)+j*spacing;
int yPosition = height/2-((ARRAYY-1)*spacing/2)+i*spacing;
//draw the array entries on the screen
text(sensorArray[i][j], xPosition, yPosition);
}
}
}

void serialEvent (Serial myPort) {
//store a batch of data into variable "inString"
//batches are separated by exclamation mark characters
String inString = myPort.readStringUntil('!');
//split the data into rows (rows separated by new line characters)
String[] incomingArrayRows = splitTokens(inString, "\n");
//loop through all of the rows
for (int i=0;i
<ARRAYX;i++)
{
//split each row into entries (entries separated by tab characters)
String[] incomingArrayEntries = splitTokens(incomingArrayRows[i], "\t");
//loop through all of these entries
for (int j=0;j
<ARRAYY;j++)
{
//store entries in the "sensorArray" variable
sensorArray[i][j]=int(incomingArrayEntries[j]);
//print the entries to the terminal, separated by tab characters
print(sensorArray[i][j]);
print('\t');
}
//print a new line after each row
println();
}
//print a new line after each batch of data
println();
}