Send and Read Multiple Data

In Arduino, use punctuation to seperate multiple data and send then as one string.

	int sensor1 = analogRead(A0);
  Serial.print(sensor1);
  Serial.print(",");

  int sensor2 = analogRead(A1);
  Serial.print(sensor2);
  Serial.print(",");

  int sensor3 = digitalRead(buttonPin);
  Serial.println(sensor3);

In P5, read data as a string first, then split it in to an array of strings.

var inString = serial.readStringUntil('\\r\\n'); // read string until carriage return adn newline

if(inString.length >0) {    //check available string
	var sensors = split(inString, ',');
	if(sensors.length>2) {      //check three sensors readings available
		w = map(sensors[0], 0, 1023, 0, width);
		h = map(sensors[1], 0, 1023, 0, height);
		col = 255 - sensors[2]*255;
	}
}

Data readings are good, however, due to the unstable analog reading, the circle drawed in P5 is shaking.

Serial_communication_multiple.mp4

Flow Control: Call and Response

In Arduino, send a start message in setup(), and read incoming data in loop().

void setup() {
	Serial.begin(9600);
	while(Serial.available() <=0 ) {
	Serial.println("hello");
	delay(300);
}

void loop() {
	if(Serial.available() >0) {
		int inByte = Serial.read();  //control the buffer
		...   
	}
}

In P5, add send out message to request serial data. And send the first message in function portOpen() to start the serial.

function serialEvent() {
...
serial.write('x');
}

Screen Shot 2021-10-26 at 4.59.02 PM.png

In my sketch, every time I send a message, I get two sensor values back. And when it connects to P5, the drawing is still shaking rather than more responsive data communication.

Questions: