Copyright © https://mongoose-os.com

Mongoose OS Forum

frame

How to use api_uart.js and byte arrays?

Hello!!

I am trying to use MongooseOS to communicate with a hardware throught the serial port, for this I'm using uart lib, but without success.

I am doing the same thing in NodeJS, using the SerialPort to write the values in code above and I received the proper response from the serial.

var SerialPort = require('serialport'); 

var serialPort = new SerialPort(portName, {
  baudRate: 57600
}); // open the port

function write(){
  var command = new Buffer([
     0x04,  
     0x00, 
     0x21, 
     0xD9, 
     0x6A 
   ]);

   serialPort.write(command);
}

serialPort.on('data', function(data){
  console.log(data);
});

serialPort.on('open', write);

To do the same thing in MongooseOS, I used this code adaptation of example-uart-js , but when i do the write, the RFID reader always return: \x00\x00\x00\x00 but the expected value is \0x0d\0x00\0x21\0x00\0x03\0x3f\0x09\0x03\0x13\0x13\0x1e\0x0a\0xeb\0xc4, code as follow:

load('api_timer.js');
load('api_uart.js');
load('api_sys.js');


let uartNo = 2;   // Uart number used for this example
let rxAcc = '';   // Accumulated Rx data, will be echoed back to Tx
let value = false;

// Configure UART at 115200 baud
UART.setConfig(uartNo, {
  baudRate: 57600,
  esp32: {
    gpio: {
      rx: 16,
      tx: 17,
    },
  },
});

// Set dispatcher callback, it will be called whenver new Rx data or space in
// the Tx buffer becomes available
UART.setDispatcher(uartNo, function(uartNo) {
  let ra = UART.readAvail(uartNo);
  if (ra > 0) {
    // Received new data: print it immediately to the console, and also
    // accumulate in the "rxAcc" variable which will be echoed back to UART later
    let data = UART.read(uartNo);
    print('Received UART data:', data);
    rxAcc += data;
  }
}, null);

// Enable Rx
UART.setRxEnabled(uartNo, true);

// Send UART data every second
Timer.set(1000 /* milliseconds */, Timer.REPEAT, function() {
    print("|---------------------|");
  value = !value;
  let bytes = chr(0x04) +
              chr(0x00) +
              chr(0x21) +
              chr(0xD9) +
              chr(0x6A);

UART.write(
    uartNo,
    bytes
  );
  rxAcc = '';
}, null);

The major difference between the APIs is that the NodeJS's SerialPort uses the Buffer object to send my 4 bytes data, while uart_lib expects an string. There's some error in my code to write these bytes throught the serial port?

Thanks in advance.

Sign In or Register to comment.