Potentiometer with Arduino sent to Javascript

184 views Asked by At

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

1

There are 1 answers

0
Antonio Della Fortuna On

It may be that you need another interpretation of your Uint8Array.

For example, if you are expecting a Float32 or a Uint32, 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:

const yourUint8Array = new Uint8Array([13, 10, 55, 57]);

console.log(yourUint8Array); // this is your 'value'

//Interpret the underlying buffer as a Uint32Array
const uint32Array = new Uint32Array(yourUint8Array.buffer); 

// uint32Array[0] would be your uint32 reinterpreted value
console.log(uint32Array); 

//Interpret the underlying buffer as a Float32Array
const float32Array = new Float32Array(yourUint8Array.buffer); 

// float32Array[0] would be your float32 reinterpreted value
console.log(float32Array); 

If you expect some text:

var enc = new TextDecoder("utf-8");

//Interpret the underlying buffer as a UTF-8 string 
console.log(enc.decode(yourUint8Array.buffer));

Output from the console:

// Uint8Array {0: 13, 1: 10, 2: 55, 3: 57}
// Uint32Array {0: 959908365}
// Float32Array {0: 0.00017455984198022634}
// 79 // <-- output from text decoder