xxxxxxxxxx
149
let port, reader, writer;
let serialActive = false;
async function getPort(baud = 9600) {
let port = await navigator.serial.requestPort();
// Wait for the serial port to open.
await port.open({ baudRate: baud });
// create read & write streams
textDecoder = new TextDecoderStream();
textEncoder = new TextEncoderStream();
readableStreamClosed = port.readable.pipeTo(textDecoder.writable);
writableStreamClosed = textEncoder.readable.pipeTo(port.writable);
reader = textDecoder.readable
.pipeThrough(new TransformStream(new LineBreakTransformer()))
.getReader();
writer = textEncoder.writable.getWriter();
return { port, reader, writer };
}
class LineBreakTransformer {
constructor() {
// A container for holding stream data until a new line.
this.chunks = "";
}
transform(chunk, controller) {
// Append new chunks to existing chunks.
this.chunks += chunk;
// For each line breaks in chunks, send the parsed lines out.
const lines = this.chunks.split("\r\n");
this.chunks = lines.pop();
lines.forEach((line) => controller.enqueue(line));
}
flush(controller) {
// When the stream is closed, flush any remaining chunks out.
controller.enqueue(this.chunks);
}
}
async function setUpSerial() {
noLoop();
({ port, reader, writer } = await getPort());
serialActive = true;
runSerial();
loop();
}
async function runSerial() {
try {
while (true) {
if (typeof readSerial === "undefined") {
console.log("No readSerial() function found.");
serialActive = false;
break;
} else {
const { value, done } = await reader.read();
if (done) {
// Allow the serial port to be closed later.
reader.releaseLock();
break;
}
readSerial(value);
}
}
} catch (e) {
console.error(e);
}
}
async function writeSerial(msg) {
await writer.write(msg);
}
// This function will be called by the web-serial library
// with each new *line* of data. The serial library reads
// the data until the newline and then gives it to us through
// this callback function
function readSerial(data) {
////////////////////////////////////
//READ FROM ARDUINO HERE
////////////////////////////////////
if (data != null) {
// make sure there is actually a message
// split the message
let fromArduino = split(trim(data), ",");
// if the right length, then proceed
if (fromArduino.length == 2) {
// only store values here
// do everything with those values in the main draw loop
// We take the string we get from Arduino and explicitly
// convert it to a number by using int()
// e.g. "103" becomes 103
rVal = int(fromArduino[0]);
alpha = int(fromArduino[1]);
}
//////////////////////////////////
//SEND TO ARDUINO HERE (handshake)
//////////////////////////////////
let sendToArduino = left + "," + right + "\n";
writeSerial(sendToArduino);
}
}
// p5.js setup function
function setup() {
createCanvas(400, 400);
// Connect button
let connectButton = createButton("Connect to Serial");
connectButton.position(20, 20);
connectButton.mousePressed(setUpSerial);
// Button to trigger wheel and Servo 1 movement
let button1 = createButton("Move Wheel & Servo 1");
button1.position(20, 60);
button1.mousePressed(() => writeSerial("A"));
// Button to trigger Servo 2 movement
let button2 = createButton("Move Servo 2");
button2.position(20, 100);
button2.mousePressed(() => writeSerial("B"));
// Button to display LCD message
let button3 = createButton("Display Reading Message");
button3.position(20, 140);
button3.mousePressed(() => writeSerial("C"));
// Button to display LCD message
let button4 = createButton("Display Break Message");
button4.position(20, 180);
button4.mousePressed(() => writeSerial("D"));
}
// p5.js draw function
function draw() {
background(220);
textAlign(CENTER);
textSize(16);
text("Use buttons to control the Arduino", width / 2, height / 2+40);
}