How split data received from serial port

#1

Hi All,
My Node-red is receiving data from Arduino serial port.

The data Arduino is sending cam from this code:

 Serial.print(rpm_SetPoint);
  Serial.print("\t");
  Serial.print(angleValue);
  Serial.print("\t");
  Serial.println(rpmValue);

I need to separete every line Arduino is sending in e single value to elaborate separatly.
From Node-Red I write this function:
var output = msg.payload.split("\t");

var velimp = parseInt(output[1]);
var angle  = parseInt(output[2]);
var vel    = parseInt(output[3]);

var msg1 = {payload : velimp};
var msg1 = {payload : angle};
var msg1 = {payload : vel};

return [msg1, msg2, msg3];

But don't work
Arduino is correcly connected.

Can you help me to find the mistake.

Vincenzo

0 Likes

#2

attach a debug node to your arduino node to see what Node-RED is receiving

0 Likes

#3

I get this:
155 90 255

code

0 Likes

#4

So your string would also appear to contain something else ( i"m guessing a carriage return on the end as 155<tab>90<tab>255 would be 10 characters.

You use

var msg1 = {payload : velimp};
var msg1 = {payload : angle};
var msg1 = {payload : vel};

but then return

return [msg1, msg2, msg3];

So I'm guessing two of those msg1 should be msg2 and msg3

Also if you are returning like that you need 3 outputs from your function node . If you wish them to be sent as separate messages to the same output see
https://nodered.org/docs/writing-functions#multiple-messages

0 Likes

#5

Also arrays in Javascript start from index 0 not 1...
image

0 Likes

#6

Sorry my mistake is very stupid.
I rewritten the code and it's all ok.

Thi is new code:

var output = msg.payload.split("\t");

var velimp = parseInt(output[0]);
var angle  = parseInt(output[1]);
var vel    = parseInt(output[2]);

var msg1 = {payload : velimp};
var msg2 = {payload : angle};
var msg3 = {payload : vel};

return [msg1, msg2, msg3];

Last question:
It' possible to do get same results with split function?

Thanks

0 Likes

#7

When programming there are almost always multiple ways of achieving a result. You could use regular expressions here for example. However the clue is in your question. You ask how to split the data up so it is likely that a function called split that splits the data up is likely to be a good match.

0 Likes