Lab: Serial Output from P5
October 15, 2020
Physical ComputingIn this lab I used serial communication to control an LED using JavaScript code. I rewired the breadboard to contain a single LED connected to the arduino. Beginning from where I left off in the previous lab, I modified the code to send serial data instead of just receive it.
I implemented the P5 mouseDragged
function so that dragging the mouse changed the LED’s brightness.
Controlling an LED with the mouse
I then wrote logic to toggle the LED on or off using the H
and L
keys on the keyboard. The JS code sent the key that was pressed which was then decoded and acted upon by the embedded code.
Controlling an LED with the keyboard
The JavaScript code:
var serial;
const PORT_NAME = '/dev/tty.usbmodem142301';
var inData;
var xPos = 0;
var outByte = 0;
function setup() {
serial = new p5.SerialPort();
serial.on('connected', serverConnected);
serial.on('open', portOpen);
serial.on('data', serialEvent);
serial.on('error', serialError);
serial.on('close', portClose);
serial.list();
serial.open(PORT_NAME);
createCanvas(400, 300);
}
function draw() {
background(0);
fill(255);
text('incoming value: ' + inData, 30, 30);
}
function serverConnected() {
console.log('connected to server.');
}
function portOpen() {
console.log('the serial port opened.');
}
function mouseDragged() {
outByte = int(map(mouseY, 0, height, 0, 255));
serial.write(outByte);
}
function serialEvent() {
var inByte = serial.read();
inData = inByte;
}
function keyPressed() {
if (key === 'H' || key === 'L') {
serial.write(key);
}
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}
function portClose() {
console.log('The serial port closed.');
}
The Arduino code:
const int ledPin = A0;
int incomingByte;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
incomingByte = Serial.read();
if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
}
if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);
}
}
}