I'm currently doing an exercise to send the potentiometer data through an Arduino into a webpage. I would prefer to do this through Web Serial API and not a node server or some thing like that. My Arduino code is
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(1);
}
This shows the values in the serial monitor no problem.
The javascript code is like this ( in script, embedded in html):
var b = document.getElementById('button');
b.addEventListener('click', async () => {
// Prompt user to select any serial port.
const port = await navigator.serial.requestPort();
await port.open({ baudRate: 9600 });
console.log('working');
while (port.readable) {
const reader = port.readable.getReader();
try {
while (true) {
const { value, done } = await reader.read();
console.log({ value });
if (done) {
break;
}
}
} catch (error) {
console.log('error');
} finally {
reader.releaseLock();
}
}
});
which means I have a button that allows me to connect to USB where the Arduino is, and it's passing a stream of information, but it's not really usable
{value: Uint8Array(4)}
value: Uint8Array(4) [13, 10, 55, 57, buffer: ArrayBuffer(4), byteLength: 4, byteOffset: 0, length: 4]
[[Prototype]]: Object
as it is not the value of the position of the potentiometer. I assume some mapping is required, but I fail to see how. Also, this is currently only working on Google Chrome because of the Web Serial API.
Any ideas on how to receive the potentiometer data correctly?
Thank you Cheers
It may be that you need another interpretation of your Uint8Array.
For example, if you are expecting a
Float32
or aUint32
, you need to explicitly use those buffer views (or interpretations).Here's a list of all the available buffer views in javascript.
Example if you expect a number:
If you expect some text:
Output from the console: