Weird DHT11 reading

I’m trying read values from a DHT11 sensor on my arduino uno. I have a very simple arduino sketch that writes just humidity, that’s the only value I want. I wrote a very simple processing sketch (see below) that reads and displays this value, it works but I get weird results. When I run the sketch it displays the value every 1 second, but right before displaying the next reading, it very quickly cycles through numbers 0-255 then displays the value. What is causing this? any ideas how to fix it? Thanks!

import processing.serial.*;

Serial myPort; 

int humidity;

void setup() {
  size(200, 200);
  
  myPort = new Serial(this, "COM3", 9600);
}

void draw() {
  if (myPort.available() > 0) {
    humidity = myPort.read();
  }
  background (0, 0, 255);
  if (humidity >= 0) {
    fill(255);
    textSize(20);
    text(humidity, 10, 10);
  }
}

Hello @bkeith ,

What are you seeing on the Arduino monitor without Processing?

You may have some garbage in your buffers… try it with while() and report back.
I experience this when starting Processing when receiving from Arduino in some cases and have various strategies to address this.

I am assuming you are sending one byte of data (value 0 to 255) every 1000ms from Arduino.

while (mySerial.available() > 0) will receive multiple bytes of data per frame and flush out the buffers.
In your code you will use the last byte that was read.

if (mySerial.available() > 0) will only receive one bye of data per frame; the data will be stuck in the buffer until it is read() the next frame and eventually cleared.
You may be seeing some garbage in your buffers using the if() statement until you clear it out… one frame per byte.

You can monitor the buffer with a simple statement:

println(mySerial.available());

Reference:

:)