Numeric value and serial communication

Hi all,
I'm quite newbye. I communicate via serial port with Arduino board, using Serial.read() function I am able to send single byte and Arduino works as "actuator" making many functions. Now I need to pass at Arduino a value inserted in my PC interface developed usind ui-dashboard nodes. Could someone advise me which is the best way to implement an easy communcation in order to pass integer values o string between Arduino and node-red?
Thanks in advance.
n

Hi @Nic,

Sorry I can't quite grasp the last comment

integer values o string between Arduino and node-red?

Do you want to send a string containing numbers, or send numbers represented as bytes?

  • As a string, send as is "12334456"
  • As a collection of bytes

Lets assume a 32bit Integer

const num = 123456;
const buffer = Buffer.alloc(4); /* 4 bytes in a 32bit integer */
buffer.writeInt32BE(num, 0);    /* Big Endian */
//buffer.writeInt32LE(num, 0);  /* Little Endian */

msg.payload = buffer
return msg;

As for reading back integers passed to you as a byte array:

const int32 = msg.payload.readInt32BE(0); // Big Endian

For the 'easy way' - I do recommend however, looking at this node by our own @Steve-Mcl

1 Like

I suspect the better solution is to always send and receive JSON. That way you can add meta data and perform different operations depending on the meta info.

2 Likes

Hi, thanks for your advises. Finally I set the fw on arduino side in order to have something like a "metadata" where I include strings and integers. Working with the "string node" on node-red side I can divide the data in every part I need.
Thank you for the support.
n

That is really not necessary & you are really re-inventing a perfectly good wheel that almost all of the JavaScript community already use - it is called JavaScript Object Notation (or JSON for short).

There are LOTS (and lots and lots) of reasons to go with a well established data interchange format (which JSON is) but the most important reasons are:

  • It is highly extensible (future changes to your data will NOT break your project)
  • It is literally built into JavaScript (JSON.parse / JSON.stringify) and built into Node-RED (the JSON node)
  • It already exists and it works well
  • Almost EVERY programmer knows exactly how to work with it (as opposed to some custom formatted string you invent)
  • etc
  • etc

Steve, you are right but what you don't know is that I'm not able to work with JavaScript :wink:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.