javascriptnode.jsarduinoanalog-digital-converternode-serialport

Bad data received from Arduino serial while reading from analog port


Maybe this is just a nonsense, but it's driving me crazy. I'm trying to read one analog port in Arduino and send the value through the serial port to JavaScript using node. When I show the data in the Arduino console, everything works fine, but when I use the terminal in Mac, some values appear splited in two lines.

460
460
4
60
460

The code I'm using is:

Arduino:

const int analogInPin = A0;
int sensorValue = 0;

void setup() {
  Serial.begin(500000);
}

void loop() {
  sensorValue = analogRead(analogInPin);
  Serial.print(sensorValue);
  delay(200);
}

Node:

var com = require('serialport').SerialPort;

var opts = {baudrate: 500000};

var serialPort = new com('/dev/tty.usbmodem641', opts);

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

The code couldn't be simpler, but still doesn't work properly. I know I'm missing something but I can't see it. I have tested different baudrates, but nothings works. Could you please help me?

Thanks in advance


Solution

  • I think maybe Elias Benevedes is trying to suggest this in their answer: right now your Arduino data is not delimited at all. Suppose your sensorValue always reads as 1. In this case the output from Arduino will be

    11111111111111111111111111111111111111111111111111111111111....
    

    And so on; because you print the integer value without any delimiters. The way it is parsed into different numbers, therefore, has to do with the timing of the arrival of the data. Continuing with the example above then, sometimes your value is read as 1, sometimes as 11, sometimes as 111 and so on, just depending on the timing of the reads and the writes.

    The way to begin to fix it is to insert some non-numeric data between your sensor reading outpus. One (again, this is perhaps what Elias Benevedes has in mind) is to insert line breaks between every number printed

     Serial.println(sensorValue);
    

    Another way would be to add spaces between the data

     Serial.print(sensorValue);
     Serial.print(" ");
    

    Either solution would separate your numeric readings from each other, which is what you want.