Time stamp / get Time

Dear all,

I am trying to get some information from my old drilling machine.
With the help of some ultrasonic sensors I would like to measure the distance of a part and also generate a timestamp so I know how long the part was resting under the drill head.

Therefore I created a code which is unfortunately not working.
Task:
The distance is uploaded every second, so far so good.
If the distance is below 10 cm the part is set to 1 and as long as it is 1 time should be added.

My idea was to set a timestamp when it becomes 1 and another one when it becomes 0 and in the end I will subtract the 1 timestamp from the 0 timestamp.

Attached you can find my code

let part;
let end;
let start;
let processingTime;

if (msg.payload.distancecm < 10) {
part = 1;
} else {
part = 0;
}

if (part === 1) {
start = new Date();
} else {
(part === 0){
end = new Date();
processingTime = end.getTime() - start.getTime();
}
}

msg.payload="[{"Timestamp" :"" + Date() + "","distance" :"" + msg.payload.distancecm + "","part" :"" + part + "","end" :"" + end + "","start" :"" + start + "","processingTime" :"" + processingTime + ""}]"
return msg;

Thank you very much in advance for your help.

Greetings

One thing, you have an if...else... but you have a conditional after the else so I think you want this

if (part === 1) {
start = new Date();
} else {
(part === 0){
end = new Date();
processingTime = end.getTime() - start.getTime();
}

to be

if (part === 1) {
start = new Date();
} else if (part === 0){
end = new Date();
processingTime = end.getTime() - start.getTime();
}

1 Like

Also you will need to save the start time in the node context and pick it up again when you determine the end time. Variables set in a function node are lost at the end of the function unless you save them in the context. Look in the node-red docs on writing functions to find details of how to do that.

1 Like