Help with serial communication

Hello,

I wrote a simple example.

Arduino sends data every 1000ms +/- 200ms (random).

Arduino Code
void setup()
  {
  Serial.begin(9600);
  }

void loop()
  {
  for(int i=0; i<256; i++)
    {
    int ran = random(0, 200);   
    delay(1000 + int(ran));
    Serial.write(i);
    }
  }

Processing receives data and prints messages and changes background depending on time since last event.

Processing Code
// Receive serial data and visualize
// v1. 0. 0
// GLV 2020-05-03

import processing.serial.*;

Serial serialPort;

int timeNow, timeLast, timeDiff;
color col;

void setup()
  {
  size(200, 200);

  // List all the available serial ports:
  printArray(Serial.list());

  String portName = Serial.list()[4];
  serialPort = new Serial(this, portName, 9600);
  timeLast = millis();
  }

void draw() 
  {
  background(col);
  }

void serialEvent(Serial serialPort) 
  {
  int inByte = serialPort.read();

  timeNow = millis();
  timeDiff = timeNow - timeLast;
  
  println(inByte, timeDiff);
  
  if (timeDiff > 1000+100) 
    {
    println("time > 1100");
    col = color(255, 0, 0);
    }
    
  else if (timeDiff < 1000-100) 
    {
    println("time < 900");    
    col = color(255, 0, 0);
    }
  
  else 
     {
     println("900 <= time <= 1100"); 
     col = color(0, 255, 0); 
     }
  
  timeLast = timeNow;
  }
1 Like