Aqui é o espaço reservado para a modificações feitas nos sketches do Processing. O originais são encontrados na pasta exemples do Processing.
O primeiro a ser modificado é o Serial Call-Response. Antes de sofrer a alteração, o Arduino (ver no final o sketch do Arduino) envia o caractere 'A'. Ao receber esse caractere pela serial o Processing envia de volta o mesmo caractere, estabelecendo assim a comunicação com o Arduino (handshaking). Depois, o Arduino envia na sequência o valor das três entradas analógicas (A0 até A1)), intercalados, após receber um 'A' solicitando a próxima medida. Com esse artifício, garantimos que nenhum dado seja perdido.
A nossa modificação preservou o mecanismo de handshaking para receber os valores de accelX, accelY, accelZ e joystickX de um Wii Nunchuk, conectado ao Arduino via TWI (I2C). Para isso ou para acrescentar ou diminuir a quantidade de dados é imprescindível alterar da variável int[] serialInArray = new int[n], substituindo o valor de n pela quantidade de dados que vamos receber. Nesse exemplo n=4.
Do mesmo, é necessário mudar o loop em if (serialCount > n-1 ), logo para n=4 o loop fica if(serialCount>3). O debug no final não precisa mudar, mas se quiser ver todos os valores lidos do Arduino tem que modificar e acrescentar as novas variáveis lidas:
println(accelX + "\t" + accelY + "\t" + accelZ +"\t" + joystickX .... etc);
SKETCH DO PROCESSING
/**
* Serial Call-Response
* by Tom Igoe.
*
* Sends a byte out the serial port, and reads 3 bytes in.
* Sets foregound color, xpos, and ypos of a circle onstage
* using the values returned from the serial port.
* Thanks to Daniel Shiffman and Greg Shakar for the improvements.
*
* Note: This sketch assumes that the device on the other end of the serial
* port is going to send a single byte of value 65 (ASCII A) on startup.
* The sketch waits for that byte, then sends an ASCII A whenever
* it wants more data.
* Modificado por Solucionática/
import processing.serial.*;
int bgcolor; // Background color
int fgcolor; // Fill color
Serial myPort; // The serial port
int[] serialInArray = new int[4]; // Where we'll put what we receive
int serialCount = 0; // A count of how many bytes we receive
int xpos, ypos, xjoy, yjoy; // Starting position of the ball
boolean firstContact = false; // Whether we've heard from the microcontroller
float x, y;
float angle1 = 0.0;
float angle2 = 0.0;
float segLength = 100;
int yrep=0;
int xrep =0;
void setup() {
//size(256, 256); // Stage size
//noStroke(); // No border on the next thing drawn
size(640, 360);
strokeWeight(30);
stroke(255, 160);
// Set the starting position of the ball (middle of the stage)
xpos = width/2;
ypos = height/2;
x = width * 0.3;
y = height * 0.5;
// Print a list of the serial ports, for debugging purposes:
println(Serial.list());
// I know that the first port in the serial list on my mac
// is always my FTDI adaptor, so I open Serial.list()[0].
// On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}
void draw() {
//background(bgcolor);
//fill(fgcolor);
// Draw the shape
//ellipse(xpos, ypos, 20, 20);
background(0);
float distan=dist(0,0,xjoy,yjoy);
translate(distan,xjoy);
delay(30);
angle1 = (map(xrep,0,255,0,128)/float(width) - 0.5) * -PI;
angle2 = (map(yrep,0,255,0,128)/float(height) - 0.5) * PI;
pushMatrix();
segment(x, y, angle1);
segment(segLength, 0, angle2);
popMatrix();
}
void serialEvent(Serial myPort) {
// read a byte from the serial port:
int inByte = myPort.read();
// if this is the first byte received, and it's an A,
// clear the serial buffer and note that you've
// had first contact from the microcontroller.
// Otherwise, add the incoming byte to the array:
if (firstContact == false) {
if (inByte == 'A') {
myPort.clear(); // clear the serial port buffer
firstContact = true; // you've had first contact from the microcontroller
myPort.write('A'); // ask for more
}
}
else {
// Add the latest byte from the serial port to array:
serialInArray[serialCount] = inByte;
serialCount++;
// If we have 3 bytes:
if (serialCount > 3 ) {
xpos = serialInArray[0];
ypos = serialInArray[1];
xjoy = serialInArray[2];
yjoy = serialInArray[3];
//if (xpos == 124||ypos==233) {
while((xpos!=243 || ypos!=243)&&serialCount<20) {
if (xpos==124) {
xrep++;
delay(3);
serialCount++;
}
else {xpos=243;
}
if(ypos==233) {
yrep++;
delay(3);
serialCount++;
}
else {ypos=243;
}
}
//fgcolor = serialInArray[2];
// print the values (for debugging purposes only):
println(xpos + "\t" + ypos + "\t" + fgcolor);
// Send a capital A to request new sensor readings:
myPort.write('A');
// Reset serialCount:
serialCount = 0;
}
}
}
void segment(float x, float y, float a) {
translate(x, y);
rotate(a);
line(0, 0, segLength, 0);
}
SKETCH DO ARDUINO (ORIGINAL):
Aqui, ainda tem que ser feitas as modificações, que se restringem ao nome das variáveis e ao valor que elas podem assumir.
Por exemplo, como o valor enviado pelo Wii Nunchuk precisa ser condicionado para ser perfeitamente compreendido pelo Processing,
precisamos usar instruções do tipo map() e constrain(). Essas duas intruções são uma mão na roda para o programador, pois permite adequar os valores enviados para
se encaixarem com os que serão lidos
/*
// Serial Call and Response
// by Tom Igoe
// Language: Wiring/Arduino
// This program sends an ASCII A (byte of value 65) on startup
// and repeats that until it gets some data in.
// Then it waits for a byte in the serial port, and
// sends three sensor values whenever it gets a byte in.
// Thanks to Greg Shakar for the improvements
// Created 26 Sept. 2005
// Updated 18 April 2008
int firstSensor = 0; // first analog sensor
int secondSensor = 0; // second analog sensor
int thirdSensor = 0; // digital sensor
int inByte = 0; // incoming serial byte
void setup()
{
// start serial port at 9600 bps:
Serial.begin(9600);
pinMode(2, INPUT); // digital sensor is on digital pin 2
establishContact(); // send a byte to establish contact until Processing responds
}
void loop()
{
// if we get a valid byte, read analog ins:
if (Serial.available() > 0) {
// get incoming byte:
inByte = Serial.read();
// read first analog input, divide by 4 to make the range 0-255:
firstSensor = analogRead(0)/4;
// delay 10ms to let the ADC recover:
delay(10);
// read second analog input, divide by 4 to make the range 0-255:
secondSensor = analogRead(1)/4;
// read switch, multiply by 155 and add 100
// so that you're sending 100 or 255:
thirdSensor = 100 + (155 * digitalRead(2));
// send sensor values:
Serial.print(firstSensor, BYTE);
Serial.print(secondSensor, BYTE);
Serial.print(thirdSensor, BYTE);
}
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.print('A', BYTE); // send a capital A
delay(300);
}
}
*/
31/01/2014
/**
* Serial Call-Response
* by Tom Igoe.
*
* Sends a byte out the serial port, and reads 3 bytes in.
* Sets foregound color, xpos, and ypos of a circle onstage
* using the values returned from the serial port.
* Thanks to Daniel Shiffman and Greg Shakar for the improvements.
*
* Note: This sketch assumes that the device on the other end of the serial
* port is going to send a single byte of value 65 (ASCII A) on startup.
* The sketch waits for that byte, then sends an ASCII A whenever
* it wants more data.
*/
import processing.serial.*;
int bgcolor; // Background color
int fgcolor; // Fill color
Serial myPort; // The serial port
int[] serialInArray = new int[100]; // Where we'll put what we receive
int serialCount = 0; // A count of how many bytes we receive
int xpos, ypos; // Starting position of the ball
boolean firstContact = false; // Whether we've heard from the microcontroller
void setup() {
size(256, 256); // Stage size
noStroke(); // No border on the next thing drawn
// Set the starting position of the ball (middle of the stage)
xpos = width/2;
ypos = height/2;
// Print a list of the serial ports, for debugging purposes:
printArray(Serial.list());
// I know that the first port in the serial list on my mac
// is always my FTDI adaptor, so I open Serial.list()[0].
// On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}
void draw() {
background(bgcolor);
fill(fgcolor);
// Draw the shape
ellipse(xpos, ypos, 20, 20);
}
void serialEvent(Serial myPort) {
// read a byte from the serial port:
int inByte = myPort.read();
// if this is the first byte received, and it's an A,
// clear the serial buffer and note that you've
// had first contact from the microcontroller.
// Otherwise, add the incoming byte to the array:
//if (firstContact == false) {
//if (inByte == 'A') {
// myPort.clear(); // clear the serial port buffer
// firstContact = true; // you've had first contact from the microcontroller
//myPort.write('A'); // ask for more
// }
//}
// else {
// Add the latest byte from the serial port to array:
serialInArray[serialCount] = inByte;
serialCount++;
// If we have 3 bytes:
if (serialCount > 99 ) {
// xpos = serialInArray[0];
// ypos = serialInArray[1];
// fgcolor = serialInArray[2];
// print the values (for debugging purposes only):
for(int i = 0; i < 100; i++) {
println(serialInArray[i]);
// Send a capital A to request new sensor readings:
// myPort.write('A');
// Reset serialCount:
serialCount = 0;
}
}
}
MOUSE SIGNALS
/**
* Serial Call-Response
* by Tom Igoe.
*
* Sends a byte out the serial port, and reads 3 bytes in.
* Sets foregound color, xpos, and ypos of a circle onstage
* using the values returned from the serial port.
* Thanks to Daniel Shiffman and Greg Shakar for the improvements.
*
* Note: This sketch assumes that the device on the other end of the serial
* port is going to send a single byte of value 65 (ASCII A) on startup.
* The sketch waits for that byte, then sends an ASCII A whenever
* it wants more data.
*/
import processing.serial.*;
int bgcolor; // Background color
int fgcolor; // Fill color
Serial myPort; // The serial port
int[] serialInArray = new int[100]; // Where we'll put what we receive
int serialCount = 0; // A count of how many bytes we receive
int xpos, ypos; // Starting position of the ball
boolean firstContact = false; // Whether we've heard from the microcontroller
void setup() {
size(256, 256); // Stage size
noStroke(); // No border on the next thing drawn
// Set the starting position of the ball (middle of the stage)
xpos = width/2;
ypos = height/2;
// Print a list of the serial ports, for debugging purposes:
printArray(Serial.list());
// I know that the first port in the serial list on my mac
// is always my FTDI adaptor, so I open Serial.list()[0].
// On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}
void serialEvent(Serial myPort) {
// read a byte from the serial port:
int inByte = myPort.read();
// if this is the first byte received, and it's an A,
// clear the serial buffer and note that you've
// had first contact from the microcontroller.
// Otherwise, add the incoming byte to the array:
//if (firstContact == false) {
//if (inByte == 'A') {
// myPort.clear(); // clear the serial port buffer
// firstContact = true; // you've had first contact from the microcontroller
//myPort.write('A'); // ask for more
// }
//}
// else {
// Add the latest byte from the serial port to array:
serialInArray[serialCount] = inByte;
serialCount++;
// If we have 3 bytes:
if (serialCount > 49 ) {
// xpos = serialInArray[0];
// ypos = serialInArray[1];
// fgcolor = serialInArray[2];
// print the values (for debugging purposes only):
//for(int i = 0; i < 100; i++) {
//println(serialInArray[i]);
// Send a capital A to request new sensor readings:
// myPort.write('A');
// Reset serialCount:
serialCount = 0;
}
}
void draw()
{
background(102);
for(int i = 0; i < 50; i++) {
fill(255);
noStroke();
rect(0, height/3, width, height/3+1);
//for(int i=1; i<width; i++) {
stroke(255);
point(i, serialInArray[i]);
stroke(0);
//point(i, height/3+yvals[i]/3);
stroke(255);
//line(i, 2*height/3+bvals[i]/3, i, (2*height/3+bvals[i-1]/3));
}
}