I want to create a graph where the old data scrolls off the left side of the window while the newest data is plotted on the right side of the window. Eventually, I’m going to use this for a display to plot the readings of a temperature probe. But for now, I just want to see if I can make it work using Processing. So instead of trying to read from the serial port, I’m just going to plot a bunch of random points.

Here’s the code I used.

// Set the width and height of the window to make
int windowWidth = 400;
int windowHeight = 300;
float maxTemp = 500; //Maximum temperature expect to read
float[] readings = new float[windowWidth]; // initialized to zeroes

void setup()
{
  size(windowWidth, windowHeight);  // Set up the window
  stroke(255,0,0);  // stroke will be red on dots plotted
  fill(255,0,0);  // fill will be red on dots plotted
}

void draw()
{
  background(255);  // Sets the background to white and clears screen each time through loop
  readings[windowWidth - 1] = random(maxTemp); // Put a random number in the last value of the array
  
  // Map the element so it fits in our graph
  readings[windowWidth - 1] = map(readings[windowWidth - 1], 0, maxTemp, 0, height);
  
  // Plot all the points
  for (int i = 0; i < windowWidth - 1; i++)
  {
    if (readings[i] != 0) // Don't plot anything at zero, as that's the default value in the array
    {
      ellipse(i, height - readings[i], 3, 3);
    }
    readings[i] = readings[i + 1]; // Shift the readings to the left so can put the newest reading in
  }  
}

Click here to see the script running

A couple of things I’ve learned.

Processing is NOT java. If you try to use something from java (I had tried to use some array stuff, import java.util.Arrays;), the script will not work when you put it on a webpage. So only use things in Processing itself.

When you create an array in Processing (think this is true in java as well) it automatically puts a zero in every element. For the eventual temperature plot I’ll be making, this isn’t a problem because we’re not working with cold temps. That’s why I added the line of not plotting any values of zero. However, if zero would be an accepted value, I’d have to change something.