Question

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

Was it helpful?

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.

OTHER TIPS

I had this happen to me once also. Serial.print() sends data to the arduino. Serial.println() will send information from the arduino to the computer Serial message board (or whatever you want to call it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top