I've currently got an Arduino program communicating accelerometer values via a Serial event to processing working perfectly. I'm trying to add a thermometer to my setup however processing is only receiving 0 from reading the pin. If I Serial.print the reading in setup it does print to the serial monitor just fine, however I can't get it to send proper values alongside my accelerometer readings.
Arduino code:
int inByte = 0;
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
establishContact(); // send a byte to establish contact until receiver responds
}
void loop() {
if (Serial.available() > 0) {
// get incoming byte:
inByte = Serial.read();
// send sensor values:
Serial.write(analogRead(A3)); // X AXIS
Serial.write(analogRead(A2)); // Y AXIS
Serial.write(analogRead(A1)); // Z AXIS
Serial.write(analogRead(A0)); // TEMPERATURE
}
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.print('A'); // send a capital A
delay(300);
}
}
Processing code:
import processing.serial.*;
Serial myPort;
int[] serialInArray = new int[4];
int serialCount = 0;
int xInput, yInput, zInput;
float temperature;
boolean firstContact = false;
void setup() {
size(600, 600, P3D);
pixelDensity(2);
noStroke();
background(0);
printArray(Serial.list());
String portName = Serial.list()[4];
myPort = new Serial(this, portName, 9600);
}
void draw() {
}
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 > 2 ) {
zInput = serialInArray[0]-80;
yInput = serialInArray[1]-80+69;
xInput = serialInArray[2]-77;
temperature = serialInArray[3]; // should return voltage reading (i.e 16ºc = 130);
//println("x = " + xInput + ", y = " + yInput + ", z = " + zInput + ", Temp = " + serialInArray[3]);
// Send a capital A to request new sensor readings:
myPort.write('A');
// Reset serialCount:
serialCount = 0;
}
}
}
The accelerometer values print perfectly, but temperature just returns a 0. Serial.print(analogRead(A0)) in the serial monitor gives me the correct values, so the thermometer is definitely working.
Any help would be greatly appreciated, thank you!