P5js-WebSerial

From Digipool-Wiki
Revision as of 22:16, 31 October 2024 by WikiSysop (Talk | contribs) (Created page with " == P5JS Code == <pre> // WebSerial // This code receives the value of A0 and displays it on the screen. // Make sure to turn on WebSerial API in Chrome to connect USB-Contr...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

P5JS Code


// WebSerial
// This code receives the value of A0 and displays it on the screen.
// Make sure to turn on WebSerial API in Chrome to connect USB-Controller (Arduino)
// Use the Basics/AnalogReadSerial example on the arduino

/*
Use this command to send data to the Arduino:

  if (serialDevice) {
    serialDevice.writeString("1");      
    serialDevice.writeString("\n");
  }
  
*/

let baud = 9600;
let serialDevice;
let serialValue = 0;
let inString = "1";
let inStringList = "";

let serialOn = 0;

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  background(0);
  noStroke();
  fill(255, 127);
  text(serialValue, 100, 100);
}

function mousePressed() {
  if (!!serialDevice) {
    if (serialOn == 0) {
      serialOn = 1;
    } else {
      serialOn = 0;
    }
    return;
  }
  serialDevice = new SerialDevice(
    baud,
    (data) => serialRead(data),
    (err) => serialError(err)
  );
  serialOn = 1;
}

function serialRead(data) {
  console.log("serial data:", data);
  inStringList = splitTokens(data, " ");
  if (serialOn == 1) {
    if (inStringList.length == 1) {
      serialValue = int(map(parseInt(inStringList[0]), 0, 1024, 0, 1001));
    }
  }
}

function serialError(err) {
  print("Error:", err);
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

HTML Code


<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/addons/p5.sound.min.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

  </head>
  <body>
    <script src="serial-device.js"></script>
    <script src="sketch.js"></script>
  </body>
</html>