I am trying to receive sensor data from Arduino and write the readings into a file using Processing IDE (using serial communication / USB).
After doing a large amount of tests, I am pretty sure it's the Processing side unable to process the data. Only the first few (< 100) "samples" are written successfully, after that Serial.available()
always returns false.
I am sending two-byte chunks from Arduino, 57600 baud, default settings (8 bit, no parity, 1 stop bit).
Arduino code:
unsigned int data = 0;
unsigned char buf[2];
void setup() {
Serial.begin(57600);
}
void loop() {
data = analogRead(A0);
buf[0] = data & 0xFF; // low byte
buf[1] = data >> 8; // high byte
Serial.write(buf, 2);
Serial.flush();
delayMicroseconds(300);
}
Processing code:
import processing.serial.*;
Serial serialPort;
String serialData;
PrintWriter output;
int recordingTime = 1000; // how many miliseconds of data stream to record
byte[] dataBuffer = new byte[2]; // reserve memory for 2 bytes and initialize to 0 (java stuff)
int receivedBytes = 0;
void setup()
{
serialPort = new Serial(this, "/dev/ttyUSB0", 57600);
output = createWriter("serialData.txt");
}
void draw()
{
while(millis() < recordingTime) {
if (serialPort.available() > 0) {
receivedBytes = serialPort.readBytes(dataBuffer);
output.print("\n");
output.print("Received bytes: ");
output.print(receivedBytes);
output.print("\n");
output.println(binary(dataBuffer[0])); // low byte
output.println(binary(dataBuffer[1])); // high byte
output.println("");
}
else {
output.print("\n");
output.println("No data available");
}
}
output.flush();
output.close();
exit();
}
Output:
Received bytes: 2
11101001
00000011
Received bytes: 2
11101001
00000011
Received bytes: 2
11101001
00000011
...after some lines...
No data available
No data available
No data available
No data available
No data available
No data available
Why is this happening? Why is there "no data available" after few samples? If I watch the serial monitor output in Arduino IDE, it works fine.