Serial buffer contains old data on new connection?

Hello @YoSteve,

This will answer your question:

Examples:

// Arduino

int counter = 0;

void setup()
  {
  Serial.begin(38400);
  delay(400); // Delay before sending
  Serial.write('P');  Serial.write('P');  Serial.write('P');
  Serial.write('Q');  Serial.write('Q');  Serial.write('Q');
  }
  
void loop()
  {
  Serial.write(counter); // This will only send a byte which is 0 to 255!
  counter++;
  }
// Processing

import processing.serial.*;
Serial port;

void setup()
  {
  port = new Serial(this, Serial.list()[2], 38400);
  delay(200); // Some delay needed here to receive the leftovers < 400 delay in Arduino!
  println("D0:", port.available()); // Data available in buffer
  port.clear();
  println("D1:", port.available()); // Data available in buffer. Should be 0 after clearing!
  }

int count = 0;

void draw()
  {  
  while(port.available() > 0) // Reads entire buffer each cycle of draw
  //if (port.available() > 0)   // Only reads one byte each cycle of draw!
    {
    int i = port.read();
    print(i + " ");  // 80 is 'P', 81 is 'Q'
    count++;
    if (count>50) exit();
    }  
  }

I did something similar to you in past:

See “Processing Code 2” in above:

I have different strategies now for receiving data depending on what I am interfacing to (not always an Arduino). I can use serial ports (there are 3 additional ones) on my Arduino Mega 2560 that do not reset when connecting.

If you are programming the device then you have full control over the code.
Try adding some handshaking to request the Arduino to send data.

References:

:)