Is Processing messing with my serial data?

I’m trying to get a light sensor connected to my Arduino to talk to Processing. it should be simple enough. I’ve written this very basic Arduino sketch…

// Take value from analogue in (0) and write it to serial

 #define sensor 0
 int sensorVal = 0;
 
 void setup() {
   Serial.begin(9600);
 }
 
 void loop() {
   sensorVal = analogRead(sensor);
   Serial.println(sensorVal);
   delay(100);
 }

It runs fine. If I open Serial Monitor i get a stream of values from the light sensor like this

40
40
41
40
41
40
40
41
41
41
41
41
40
41

It responds to me shining a torch at the sensor so I know that’s working.

I’ve now got this Processing sketch…

import processing.serial.*;   // Load the serial library
Serial myPort;                // The serial port
int val = 0;

void setup () {
 myPort = new Serial(this, Serial.list()[0], 9600);
}

void draw () {
 val = myPort.read();
 println(val);
}

What happens is that when I run this sketch the stream of values in the Arduino Serial Monitor seems to start dropping carriage returns, so I start getting values like this…

3
4
3
443
4
3
43
4443
34
4
34
344
4
43

The output of the Processing script looks like this

-1
-1
52
13
10
-1
-1
53
-1
10
-1
-1
-1
-1
53

What’s going on? Why are the values so different, and why is the Processing sketch messing with the values coming from Arduino? Surely the processing script shouldn’t be messing with the serial data.

Any help would be much appreciated as I’ve only been doing this for a day.

For one thing, the Processing sketch is not checking for the presence of serial data before reading the data.

I would first suggest that you put in a small delay to let everything catch up...

Mowcius