Skip to content

Instantly share code, notes, and snippets.

@sdkfz181tiger
Last active November 28, 2022 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdkfz181tiger/6f8a83522a9514234ce0b025fcd2bb18 to your computer and use it in GitHub Desktop.
Save sdkfz181tiger/6f8a83522a9514234ce0b025fcd2bb18 to your computer and use it in GitHub Desktop.
SerialPort x Chrome x M5Atom
"use strict";
//==========
// SerialPort <-> Chrome
// Port
let port = null;
let msg = "";
async function connectSerial(){
// Serial
if(!("serial" in navigator)){
consoleInfo("Error", "The Web Serial API is not supported...");
return;
}
// Request
try{
port = await navigator.serial.requestPort();
await port.open({baudRate: 115200});
receiveMsg();
}catch(error){
consoleInfo("Error", error);
}
}
async function receiveMsg(){
while(port.readable){
const reader = port.readable.getReader();
try{
while(true){
const {value, done} = await reader.read();
if(done){
consoleInfo("Canceled", "canceled");
break;
}
const chunk = new TextDecoder().decode(value);
msg += chunk;
if(msg[msg.length-1] == "\n"){
consoleInfo("Received", msg);
msg = "";
}
}
}catch(error){
consoleInfo("Error", error);
break;
}finally{
reader.releaseLock();
}
}
}
async function sendMsg(msg){
if(port == null) return;
consoleInfo("sendMsg", msg);
const writer = port.writable.getWriter();
await writer.write(new TextEncoder().encode(msg));
writer.releaseLock();
}
function emptyInfo(){
console.clear();
}
function consoleInfo(tag, ...msg){
console.log(tag, msg.join(","));
}
#include "M5Atom.h"
using namespace std;
unsigned long counter = 0;
// Send to browser
void sendMsg(const string msg){
Serial.println(msg.c_str());
}
void setup(){
Serial.begin(115200);
Serial.println("Starting Serial!!\n");
// M5
M5.begin(true, false, true);
delay(50);
M5.dis.drawpix(0, 0xffffff);// White
}
void loop(){
//Serial.println("Serial_Controller working...\n");
while(Serial.available()){
String command = Serial.readStringUntil('\n');
Serial.println(command);
}
// Test
//char msg[24];
//sprintf(msg, "Morning, Serial:%01d", counter++);
//sendMsg(msg);// Send
// M5
if(M5.Btn.wasPressed()){
char msg[24];
sprintf(msg, "Hello, Serial:%01d", counter++);
sendMsg(msg);// Send
}
M5.update();// M5
delay(100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment