For this week’s lab, we practiced using two-way serial communication between P5 and Arduino.
Firstly, I set up my analog inputs on the breadboard, plugging in two potentiometers and one button. The breadboard can be found on the left picture below. The arduino code for testing out the analog and digital inputs (separated with punctuation) can be found on the right picture below.
Next, I plugged in a p5 sketch importing p5.webSerial to take the inputs and translate them into the movement of the circle in the sketch. One pot is tied to the circle’s X position, the other is tied to it’s circle’s Y position, and the button makes the circle disappear when pressed. The majority of the interaction code is under serialEvent() and draw().
Next, I adjusted the code so that the Arduino is only reading and sending back the input data when prompted (call-and-response / handshaking). The code isn’t shown below but the program prints “hello\n\r” until it receives a prompt (can be anything, it’s mostly just to tell the program to start), and then print the input data whenever it receives a prompt to do so.
Next, it’s time to implement this interaction on the p5 sketch as well. The main change is to add “serial.print(‘x’);” in initiateSerial()
At first, I made this error where I thought initiateSerial() had to be its own independent function. The code did not work.
Then, I realized that the initiateSerial() was within the openPort() function and that’s the one I needed to modify. This code works!
Next, I explored my own application by adding serial communication to an ICM homework exercise I did in the past. I modified the p5 sketch to respond to the red circle (position on sketch controlled by two pots) instead of mouse interaction. To click a button on the remote, your circle would need to be in the correct position and the button would need to be pressed (instead of mouse click). It took a bit of time adjusting the code, but I was excited to find my fake “mouse” work. The circle was quite jittery in movement so if I were to repeat this exercise in the future, I would add some code to filter out the noise and make the circle movement smoother. I accidentally closed this sketch without saving and screenshotting the code. Lesson learned, always save your work!