Jason's notes

Week6 Serial Communication

Lab1 Intro to Asynchronous Serial Communications

Useful Commands for macOS

# list all serial ports
ls -1 /dev/cu.*

# print what the serial port is sending
cat /dev/cu.xxx

# for duplex communication
# control-A control-\ to close
screen /dev/cu.xxx

Flow Control: Call and Response (Handshaking)

because asynchronous serial communication is asynchronous, you can run into a problem when the sender sends faster than the receiver can read. The simplest way to fix it is using a call-and-response methods.

void setup() {
   while (Serial.available() <= 0) {
     Serial.println("hello"); // start msg
     delay(300);              // wait
void loop() {
   if (Serial.available()) {
      // read the incoming byte:
      int inByte = Serial.read();

      // read and send the sensor's value:
      sensorValue = analogRead(A0);


  • Only one program can control a serial port at a time.
  • Sending raw binary is more efficient while sending ASCII is simpler.
  • The punctuation method can’t be used when sending binaries.
  • Call-and-response method is better.

Lab2 Serial Input to P5.js

Which method to use:

Data to Send0 ~ 255characters
Send as:BinaryASCII
Arduino ->Serial.write()Serial.println()
-> p5.jsserial.read()serial.readLine()

I made a small demo with the Arduino Nano 33 IOT’s build-in gyroscope. However, It didn’t act like what I thought. Instead of returning the status of the arduino board, it returns the rate of how it rotate. So the X, Y, Z values are always zero when the board is static. I also wonder why these numbers are not close enough to zero and having values like 4 or 5. (Is it the gravity?)

const ellipseX = windowWidth / 2 - float(x);
const ellipseY = windowHeight / 2 - float(y);
const radius = float(z);
ellipse(ellipseX, ellipseY, radius);


Lab3 Serial output from P5.js

Which method to use:

Number of Bytes1 ByteMulti
Send as:BinaryASCII
p5.js ->serial.write()serial.write(value + ’,‘)
-> ArduinoSerial.read()serial.parseInt

A simple light switch from p5.js to Arduino. The following code are the main part of the communication between them.

// p5.js
function lightCheckEvent() {
  if (this.checked()) {
  } else {
// Arduino
void loop() {
  // see if there's incoming serial data
  if (Serial.available() > 0) {
    incomingByte = Serial.read(); // read it
    if (incomingByte == 'H') {
      digitalWrite(ledPin, HIGH);
    if (incomingByte == 'L') {
      digitalWrite(ledPin, LOW);