Adding time to my state machine

Hello!

I am trying to build a state machine in node red, but the problem is that it keeps going back to 0 before it gets to states 2 and 3. I have implemented it all in one function. I have been trying to add some time constraints to solve the issue but I am not sure how to.

Here is the code:

var A_x = msg.payload.d.X;
var A_y = msg.payload.d.Y;
var A_z = msg.payload.d.Z;
state = 0;

var A_r = Math.sqrt(A_x*A_x + A_y*A_y + A_z*A_z);
var A_r_prev = context.get("A_r_prev") || 0;

context.set("A_r_prev", A_r);

msg.payload = ""+ Math.abs(A_r - A_r_prev);



if (state === 0 && (A_r - A_r_prev) > 600) {
     msg.payload = "Passed";
     state = 1;
    }
else if (state === 1 && (A_r - A_r_prev) > 600) {
    msg.payload = "Passed 2";
    state = 2;
    }
else if (state === 3 && (A_r - A_r_prev) > 600) {
    msg.payload = "Passed 3";
    state = 3;
    }


var NewMsg = {payload: "state:" + state};
return [[msg, NewMsg]];


I have initially created my state machine in C, here is what I am trying to implement:

if (*state == 0) {
if (abs(glob_prev_r - r) > 2000 && (msTick - *msTickStateChange > keeptime)) {
*msTickStateChange = msTick;
sprintf(dataOut, "\n\n\r\t\tFirst Movement Detected!\t\t\r\n"
);
//BSP_LED_On(LED1);
*state = 1;
CDC_Fill_Buffer((uint8_t *) dataOut, strlen(dataOut));
}

 else if (*state == 1) {
	 if (abs(glob_prev_r - r) > 2000  && (msTick - *msTickStateChange > keeptime)) {
		 *msTickStateChange = msTick;
		 sprintf(dataOut, "\n\n\r\t\tSecond Movement Detected!!!\t\t\r\n"
		    		 );
		 *state = 2;
		 CDC_Fill_Buffer((uint8_t *) dataOut, strlen(dataOut));
	 }
	 if (msTick-*msTickStateChange > resettime) {
		 sprintf(dataOut, "\n\n\r\t\tFalset\t\r\n"
		    		 );
		    		 //BSP_LED_On(LED1);
		             *state = 0;
		    		 CDC_Fill_Buffer((uint8_t *) dataOut, strlen(dataOut));
		     }
	 } }
 else if ((*state == 2)  && (msTick - *msTickStateChange > keeptime)) {
	 if(msTick-*msTickStateChange > resettime) {
		 *msTickStateChange = msTick;
		 sprintf(dataOut, "\n\n\r\t\tFalse Alarm\t\t\r\n");
		  *state = 1;
		 CDC_Fill_Buffer((uint8_t *) dataOut, strlen(dataOut));
	 }
	 else if (abs(glob_prev_r - r) > 2000 && (msTick - *msTickStateChange > keeptime)) {
		 *msTickStateChange = msTick;
		   sprintf(dataOut, "\n\n\r\t\tOPASSED PASSED\t\t\r\n");
		    		  *state = 3;
		    		 CDC_Fill_Buffer((uint8_t *) dataOut, strlen(dataOut));
	 }

Please help me fix the first code so that it performs a similar function to the second code.

Please try reformatting your post as the code blocks run into each other.

The problem is your state value is a local variable that you set to 0 every time the function is called.

You need to store it in context in the same way you store A_r_prev in context.