1

The following script prints everything fine, it recognizes integers from the serial port, but cannot recognize characters. The if statement does not work with characters. I have tried both == and === in the if statement

var SerialPort = require('serialport')
var Readline = SerialPort.parsers.Readline
var serialPort = new SerialPort('/dev/ttyAMA0', {//ttyAMA0
  baudRate: 9600
})

var parser = new Readline()
serialPort.pipe(parser)
parser.on('data', function (data) {
if(data === 'c'){/// c is not recognized
  console.log('data received: ' + data)
}

})
serialPort.on('open', function () {
  console.log('Communication is on!')
})

The Arduino code is as follows:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(12, 13); // RX, TX
int x = 0;
int y = -30000;
int z = 0;
String data;
char command = 'q';
int left = 0;
int right = 0;
int left_pwm = 0;
int right_pwm = 0;

void setup() {
  mySerial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  Serial.begin(9600);
  }
void loop() {//map and compass data
if (y==30000) {
 mySerial.println('c');
 delay(5);
 mySerial.println(299);
 delay(5);
 z = -25000;
 } 

 if(z==30000){
 mySerial.println('lon');   
 delay(5);    
  mySerial.println(529);
  delay(5);
  mySerial.println('lat');   
 delay(5);
   mySerial.println(522);
          y = -30000;
    }
  y++; z++;

  if (!mySerial.available()) {
    return;
  }

  data = mySerial.readString();
   sscanf(data.c_str(), "%c%01d%01d%03d,%03d", &command, &left, &right, &left_pwm, &right_pwm);

  if (command == 'n') { // we got a navigation command
    // update the GPIO accordingly, this only happens once after a new 'n' command has been received
    Serial.print(command);
    Serial.print(left);
    Serial.print(right);
    Serial.print(left_pwm);
    Serial.print(",");
    Serial.println(right_pwm);
    }

    }////end loop

1 Answers1

0

If you use the line parser in Nodejs, it does not remove all line ending characters. I think (though I currently cannot cite it), that only the 'ņ' character is removed from the string. But Serial.println() sends "\r\n" as line ending. That means, that your string is "c\r", which is not equal to "c".

By using the trim() method of the String type, you can remove all white space from start and end of the string, including line ending characters like '\r'.

chrisl
  • 16,622
  • 2
  • 18
  • 27