Intro to Asynchronous Serial Communication

Back again with blogging, I feel I lost some track since Midterms. However, here we are! This week’s labs were really interesting because I feel they open a very broad world of possibilities

const int switchPin = 2;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (Serial.available() <= 0) {
    Serial.println("hello");  //send starting message
    delay(300);               // wait 1/3 second
  }
}

void loop() {
  if (Serial.available()) {
    //set value for sensor 1
    //read sensor
    int sensorValue = analogRead(A0);
    //print the results
    Serial.print(sensorValue);
    Serial.print(",");

    //read sensor 2
    sensorValue = analogRead(A1);
    //print
    Serial.print(sensorValue);
    Serial.print(",");

    //read the sensor:
    sensorValue = digitalRead(switchPin);
    //print results
    Serial.println(sensorValue);
  }
}

Serial Input to P5.js using Web Serial

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int pot = analogRead(A0); // potentiometer
  int mapPot = map(pot, 0, 1023, 0, 255); //remap potentiometer
    //print
  Serial.println(mapPot);
  delay(1);
}

// variable to hold an instance of the p5.webserial library:
const serial = new p5.WebSerial();
 
// HTML button object:
let portButton;
let inData;                   // for incoming serial data
let outByte = 0;              // for outgoing data
let xPos = 0;
 
function setup() {
  createCanvas(400, 300);          // make the canvas
  background(0x08, 0x16, 0x40);
  // check to see if serial is available:
  if (!navigator.serial) {
    alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
  }
  // if serial is available, add connect/disconnect listeners:
  navigator.serial.addEventListener("connect", portConnect);
  navigator.serial.addEventListener("disconnect", portDisconnect);
  // check for any ports that are available:
  serial.getPorts();
  // if there's no port chosen, choose one:
  serial.on("noport", makePortButton);
  // open whatever port is available:
  serial.on("portavailable", openPort);
  // handle serial errors:
  serial.on("requesterror", portError);
  // handle any incoming serial data:
  serial.on("data", serialEvent);
  serial.on("close", makePortButton);
}
 
function draw() {
  graphData(inData);
}

// if there's no port selected, 
// make a port select button appear:
function makePortButton() {
  // create and position a port chooser button:
  portButton = createButton("choose port");
  portButton.position(10, 10);
  // give the port button a mousepressed handler:
  portButton.mousePressed(choosePort);
}
 
// make the port selector window appear:
function choosePort() {
  if (portButton) portButton.show();
  serial.requestPort();
}
 
// open the selected port, and make the port 
// button invisible:
function openPort() {
  // wait for the serial.open promise to return,
  // then call the initiateSerial function
  serial.open().then(initiateSerial);
 
  // once the port opens, let the user know:
  function initiateSerial() {
    console.log("port open");
  }
  // hide the port button once a port is chosen:
  if (portButton) portButton.hide();
}
 
// pop up an alert if there's a port error:
function portError(err) {
  alert("Serial port error: " + err);
}
// read any incoming data as a string
// (assumes a newline at the end of it):
function serialEvent() {
  //read a string from serial port
  var inString = serial.readLine();
  //check to see that tere's actually a string there
  if(inString){
    inData = Number(inString);
  }
  
  
  // inData = Number(serial.read());
  // // console.log(inData);
  // inData = serial.readLine();
}
 
// try to connect if a new serial port 
// gets added (i.e. plugged in via USB):
function portConnect() {
  console.log("port connected");
  serial.getPorts();
}
 
// if a port is disconnected:
function portDisconnect() {
  serial.close();
  console.log("port disconnected");
}
 
function closePort() {
  serial.close();
}

function graphData(newData){
  //map the range of the input to the window height
  var yPos = map(newData, 0, 255,0,height);
  //draw the line in a pretty color;
  stroke(0xA8, 0xD9, 0xA7);
  line(xPos, height, xPos, height - yPos);
  //at the edge of the screen go back to the beginning
  if(xPos >= width){
    xPos = 0;
    //clear the screen by resetting the background:
    background(0x08, 0x16, 0x40);
  }else{
    //increment the horizontal position for the next reading
    xPos++;
  }
}

Serial Output From P5.js using Web Serial

void setup() {
  Serial.begin(9600);
  pinMode(5,OUTPUT);
}

void loop() {
  if(Serial.available() > 0){ // if there's serial data
    int inByte = Serial.read(); //read it
    Serial.write(inByte); //send it back out as raw binary data
    analogWrite(5, inByte); //use it to set the LED brightness
    //if speaker is used use tone function
    //tone(5, inByte*10);
  }

}

// variable to hold an instance of the p5.webserial library:
const serial = new p5.WebSerial();
 
// HTML button object:
let portButton;
let inData;                            // for incoming serial data
let outByte = 0;                       // for outgoing data
 
function setup() {
  createCanvas(400, 300);          // make the canvas
  // check to see if serial is available:
  if (!navigator.serial) {
    alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
  }
  // if serial is available, add connect/disconnect listeners:
  navigator.serial.addEventListener("connect", portConnect);
  navigator.serial.addEventListener("disconnect", portDisconnect);
  // check for any ports that are available:
  serial.getPorts();
  // if there's no port chosen, choose one:
  serial.on("noport", makePortButton);
  // open whatever port is available:
  serial.on("portavailable", openPort);
  // handle serial errors:
  serial.on("requesterror", portError);
  // handle any incoming serial data:
  serial.on("data", serialEvent);
  serial.on("close", makePortButton);
}
 
function draw() {
  // black background, white text:
  background(0);
  fill(255);
  // display the incoming serial data as a string:
  text("incoming value: " + inData, 30, 30);
}

// if there's no port selected, 
// make a port select button appear:
function makePortButton() {
  // create and position a port chooser button:
  portButton = createButton("choose port");
  portButton.position(10, 10);
  // give the port button a mousepressed handler:
  portButton.mousePressed(choosePort);
}
 
// make the port selector window appear:
function choosePort() {
  serial.requestPort();
}
 
// open the selected port, and make the port 
// button invisible:
function openPort() {
  // wait for the serial.open promise to return,
  // then call the initiateSerial function
  serial.open().then(initiateSerial);
 
  // once the port opens, let the user know:
  function initiateSerial() {
    console.log("port open");
  }
  // hide the port button once a port is chosen:
  if (portButton) portButton.hide();
}
 
// read any incoming data as a byte:
function serialEvent() {
  // read a byte from the serial port:
  var inByte = serial.read();
  // store it in a global variable:
  inData = inByte;
}
 
// pop up an alert if there's a port error:
function portError(err) {
  alert("Serial port error: " + err);
}
 
// try to connect if a new serial port 
// gets added (i.e. plugged in via USB):
function portConnect() {
  console.log("port connected");
  serial.getPorts();
}
 
// if a port is disconnected:
function portDisconnect() {
  serial.close();
  console.log("port disconnected");
}
 
function closePort() {
  serial.close();
}

function mouseDragged(){
  //map the mouseY to a range from 0 to 255
  outByte = byte(map(mouseY, 0, height, 0, 255));
  //send it out the serial port
  serial.write(outByte);
}

function keyPressed(){
  if(key >= 0 && key <= 9){ //if the user presses 0 through 9
    outByte = (key*25); // map the key to a range from 0 to 255
    serial.write(outByte); // send it out the serial port
  }
}

Next

const int ledPin = 5;  //the pin that the LED is attached to
int incomingByte;      // a variable to read incoming serial data into

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {    // if there's serial data
    incomingByte = Serial.read();  //read it
    if (incomingByte == 'H') {     // if its capital H ASCII 72
      digitalWrite(ledPin, HIGH);  // turn on LED
      //if you're using a speaker  instead of an LED, uncomment line below and use
      //tone(5,440);
    }
    if (incomingByte == 'L') {    // if it's an L (ASCII 76)
      digitalWrite(ledPin, LOW);  //turn off the LED
      //for speaker just
      // noTone(5);
    }
  }
}

// variable to hold an instance of the p5.webserial library:
const serial = new p5.WebSerial();
 
// HTML button object:
let portButton;
let inData;                            // for incoming serial data
let outByte = 0;                       // for outgoing data
 
function setup() {
  createCanvas(400, 300);          // make the canvas
  // check to see if serial is available:
  if (!navigator.serial) {
    alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
  }
  // if serial is available, add connect/disconnect listeners:
  navigator.serial.addEventListener("connect", portConnect);
  navigator.serial.addEventListener("disconnect", portDisconnect);
  // check for any ports that are available:
  serial.getPorts();
  // if there's no port chosen, choose one:
  serial.on("noport", makePortButton);
  // open whatever port is available:
  serial.on("portavailable", openPort);
  // handle serial errors:
  serial.on("requesterror", portError);
  // handle any incoming serial data:
  serial.on("data", serialEvent);
  serial.on("close", makePortButton);
}
 
function draw() {
  // black background, white text:
  background(0);
  fill(255);
  // display the incoming serial data as a string:
  text("incoming value: " + inData, 30, 30);
}

// if there's no port selected, 
// make a port select button appear:
function makePortButton() {
  // create and position a port chooser button:
  portButton = createButton("choose port");
  portButton.position(10, 10);
  // give the port button a mousepressed handler:
  portButton.mousePressed(choosePort);
}
 
// make the port selector window appear:
function choosePort() {
  serial.requestPort();
}
 
// open the selected port, and make the port 
// button invisible:
function openPort() {
  // wait for the serial.open promise to return,
  // then call the initiateSerial function
  serial.open().then(initiateSerial);
 
  // once the port opens, let the user know:
  function initiateSerial() {
    console.log("port open");
  }
  // hide the port button once a port is chosen:
  if (portButton) portButton.hide();
}
 
// read any incoming data as a byte:
function serialEvent() {
  // read a byte from the serial port:
  var inByte = serial.read();
  // store it in a global variable:
  inData = inByte;
}
 
// pop up an alert if there's a port error:
function portError(err) {
  alert("Serial port error: " + err);
}
 
// try to connect if a new serial port 
// gets added (i.e. plugged in via USB):
function portConnect() {
  console.log("port connected");
  serial.getPorts();
}
 
// if a port is disconnected:
function portDisconnect() {
  serial.close();
  console.log("port disconnected");
}
 
function closePort() {
  serial.close();
}

function mouseDragged(){
  //map the mouseY to a range from 0 to 255
  outByte = byte(map(mouseY, 0, height, 0, 255));
  //send it out the serial port
  serial.write(outByte);
}

function keyPressed(){
  if(key >= 0 && key <= 9){ //if the user presses 0 through 9
    outByte = (key*25); // map the key to a range from 0 to 255
    serial.write(outByte); // send it out the serial port
  }
  if(key === "H" || key === "L"){
    //if user presses H or L
    serial.write(key); // send serial port
  }
}