Actualmente estoy haciendo un ejercicio para enviar los datos del potenciómetro a través de un Arduino a una página web. Preferiría hacer esto a través de Web Serial API y no un servidor de nodo o algo así. mi codigo arduino es
void setup() { Serial.begin(9600); } void loop() { int sensorValue = analogRead(A0); Serial.println(sensorValue); delay(1); }Esto muestra los valores en el monitor serial sin problema.
El código javascript es así (en script, incrustado en 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(); } } });lo que significa que tengo un botón que me permite conectarme al USB donde está el Arduino, y está pasando un flujo de información, pero en realidad no se puede usar
{value: Uint8Array(4)} value: Uint8Array(4) [13, 10, 55, 57, buffer: ArrayBuffer(4), byteLength: 4, byteOffset: 0, length: 4] [[Prototype]]: Objectya que no es el valor de la posición del potenciómetro. Supongo que se requiere algún mapeo, pero no veo cómo. Además, actualmente solo funciona en Google Chrome debido a la API de serie web.
¿Alguna idea sobre cómo recibir los datos del potenciómetro correctamente?
gracias saludos
Puede ser que necesite otra interpretación de su Uint8Array.
Por ejemplo, si espera un Float32 o un Uint32 , debe usar explícitamente esas vistas de búfer (o interpretaciones).
Aquí hay una lista de todas las vistas de búfer disponibles en javascript .
Ejemplo si espera un número:
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);Si espera algún texto:
var enc = new TextDecoder("utf-8"); //Interpret the underlying buffer as a UTF-8 string console.log(enc.decode(yourUint8Array.buffer));Salida desde la consola:
// Uint8Array {0: 13, 1: 10, 2: 55, 3: 57} // Uint32Array {0: 959908365} // Float32Array {0: 0.00017455984198022634} // 79 // <-- output from text decoder