Date time into byte array for modbus protocol

#1

Hi, can somebody help me, i’m using node-red-contrib modbus and I have a button on dashboard that when actuated will synchronize the datetime between node red and my controller, need help to create Function to pack the Date & Time into byte array to send via modbus protocol from RPI to my controller, it would be 2 bytes per Modbus register.

Rox

0 Likes

#2

To answer that we need to know exactly what format the device expects for the time.

0 Likes

#3

I just want to put last 2 digit of a year in byte0 and the month value in byte1, day value in byte2, hour value in byte3,mins. value in byte4, secs value in byte5; byte 0 and 1 will be one 16 Bit unsigned integer, byte1 & 2, next 16 bit integer.. i will then input it to a modbus node.

Thanks for looking.

0 Likes

#4

Which bit don't you know how to do? Getting the year, month etc or packing them into the integers?
If you don't know how to the get the date/time values then have a look at [1]. Have a play with those methods in a function node and see how you get on. While experimenting you can use node.warn to show values in the debug panel. So you might start with

let now = new Date();
let year = now.getUTCFullYear();
node.warn("year is " + year);

[1] https://www.w3schools.com/jsref/jsref_obj_date.asp

0 Likes

#5

Thank you Colin for giving me direction.. now i can write the year to my controller , now i need to pack it to integer with the one byte containing the month, can you please show me. here's what I did.

let now = new Date();
let year = now.getUTCFullYear();
let month = now.setUTCMonth();
msg.payload = year - 2000;
node.warn( msg);
return msg;

0 Likes

#6

Something like

let monthYear = year - 2000 + (month << 8);

That shifts the month value left 8 bits before adding it to the year which should be what you want I think. You will be in trouble after the year 2127 but I don't suppose you will lose much sleep over that. Of course that is exactly what the first programmers thought about the year 2000 :slight_smile:

0 Likes

#7

I realized i used set instead of get just after posting it. im still trying.

0 Likes

#8

Thank you ill try that, its just a hobby project so just getting started, so after its running ill keep improving it, Ill remember ur advise about 2127.

0 Likes

#9

Im getting there! only the strange thing ,is i'm getting 10 instead of 11 for the month.

0 Likes

#10

Look again at the function definition in the link I posted.

0 Likes

#11

I got it! I can now take it from here.
thank you very much!

0 Likes