How do I stop all of the code I have running after a given period of time if the running code is in the middle of a command

Hello, I am very new to robotics and I have been having a little trouble the past few days. I want everything that I have running to completely stop after my timer reaches a given amount of time (20 seconds), my first thought was to use an if-else statement, for example:

if (sensorValue (Timer1) >= 20000)
{
Stop code
}
else
{
Run code
}

It seems to run the code just fine, but if a line of code is executed at lets say 16 seconds, and it runs for more than 4 seconds, it will continue to run the code even though the timer reads higher than 20000ms, it will finish the line of code that it is on; however, it will not run any code beyond that.

How do I get my stop command to “interrupt” the code that it is running. I was thinking that maybe I could write two separate tasks, the first task being the one that runs my code, and the second task is programmed to wait 20 seconds and then shut off all motors, but I’m not certain if that is the correct path to take. I also tried to program an e_stop, but I wasn’t exactly sure if I could make one based off of a timer rather than a button press.

Is there something very trivial that I am missing? If not, what would be the best way to approach this? Can anyone sort of guide me into the right direction? Sorry if this seems like a very basic question, I am very new to robotics. Thanks in advance!

You are mostly on the right track. The simplest method is going to be a second task, timing and then killing your task. It will also have almost no overhead if you just make it sleep 20 seconds. Effectively you are just making your own competition template.

The other method is just reformatting your code so that it never sits in a function for 4 seconds. Using some sort of larger state machine etc.

7 Likes

Theres really no point in doing this. Just write code that either makes use of loops to breakout when it needs to, or otherwise something that can complete faster.

3 Likes