Answer the question
In order to leave comments, you need to log in
Why is the data being read from the COM port broken on stream?
Hi everyone again.
Not so long ago I asked for help and again there was a problem with the buffer.
Now the goal is this:
Arduino sends an int number to the output stream, and we read this COM port on NODE JS and translate it into string and write it to array. But when writing, sometimes the data breaks.
NODE.JS
var SerialPort = require('serialport');
var array = [];
var port = new SerialPort('/dev/ttyACM0', {
baudRate: 9600
});
port.on('readable', function () {
array.push(port.read().toString());
console.log(array);
});
// Open errors will be emitted as an error event
port.on('error', function(err) {
console.log('Error: ', err.message);
})
[ '22' ]
[ '22', '22' ]
[ '22', '22', '22' ]
[ '22', '22', '22', '2' ]
[ '22', '22', '22', '2', '2' ]
[ '22', '22', '22', '2', '2', '22' ]
[ '22', '22', '22', '2', '2', '22', '2' ]
[ '22', '22', '22', '2', '2', '22', '2', '2' ]
[ '22', '22', '22', '2', '2', '22', '2', '2', '22' ]
//TMP36 Pin Variables
int sensorPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to
//the resolution is 10 mV / degree centigrade with a
//500 mV offset to allow for negative temperatures
/*
* setup() - this function runs once when you turn your Arduino on
* We initialize the serial connection with the computer
*/
void setup()
{
Serial.begin(9600); //Start the serial connection with the computer
//to view the result open the serial monitor
}
void loop() // run over and over again
{
//getting the voltage reading from the temperature sensor
int reading = analogRead(sensorPin);
// converting that reading to voltage, for 3.3v arduino use 3.3
float voltage = reading * 5.0;
voltage /= 1024.0;
// now print out the temperature
int temperatureC = (voltage - 0.5) * 100 ; //converting from 10 mv per degree wit 500 mV offset
//to degrees ((voltage - 500mV) times 100)
Serial.print(temperatureC);
delay(1000); //waiting a second
}
Answer the question
In order to leave comments, you need to log in
The above code uses the Serial.print() function . That is, the code simply writes two characters to the port - '2' and '2'.
At the input we accept the following text - '22222222222222222222222222222222222222222222222222222'.
At some point, the buffer fills up and reading takes place, followed by parsing. How many characters are in the buffer - how many there are, so many will be transferred.
It would be more logical to use some separator character. For example, a line break. So that the buffer would be '22\r\n22\r\n22\r\n22\r\n'.
To do this, it is enough to use the Serial.println() function instead of Serial.print() .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question