Lab: Two-way Serial Communication

Before Start:

Two-Way Serial Communication using An Arduino and the p5.webserial Library

GOAL: Moving the circle in the P5 editor by changing the sensors

Reference: https://itp.nyu.edu/physcomp/labs/labs-serial-communication/lab-two-way-duplex-webserial-communication/

Preparation

Arduino Nano 33 IoT, Jumper Wires, A breadboard, A pushbutton, and Two potentiometers.

Connect the sensors

Two potentiometers are connected to A0 and A1. The pushbutton is connected to D2 with a 10-kilohm resistor.

Sending Multiple Serial Data using Punctuation

Program the microcontroller to read the pushbutton and two analog sensors. The program shown below sends the two sensor values and then the pushbutton. When I run the program, I got output likr this:

Receive the data in P5.js

The final full P5 js sketch is here: https://editor.p5js.org/yd2512/sketches/0oExVPgvf

After setup the sketch like what I did in the past Labs, serialEvent( ) function is changed to read the incoming serial data as a string until it encounters a carriage return and newline. and the readings are mapped to the height and the width of the canvas.

Then the draw( ) function draws a circle that the position is controlled by the mapped reading value.

When I run this program, the circle moved onscreen when I change my sensors. When I press the pushbutton, the circle stays soild.

Flow Control: Call and Response (Handshaking)


To solve the problem of when the sender sends faster than the receiver can read. the receiver program slows down as the serial buffer fills up. The setup( ) and loop( ) are updated. The loop in setup( ) sends out a message until it gets a byte of data from the remote computer and the if( ) statement is for looking for incoming serial data and read it.

Here is what I got when I run the updated program. And when I typed any character in the output box, I got a string of sensor value at the end of hellos.

Next, I updated the P5.jd sketch. The serialEvent( ) is changed to when getting a “hello” or any string and sends a byte back, so the Arduino has a byte to read. I also add a line to the initiateSerial( ). By sending a byte when the port has been opened in P5.js, I force the Arduino to send new data.

After all these changes, the sketch still runs as it before but with a better managed serial communication.

Previous
Previous

I/O:Force Sensing Showcase with adjustable LEDs

Next
Next

Lab: Serial Input & Output with P5.js