How to add a delay in Webots

The best way to add a delay

Protonest IoT
2 min readMay 6, 2021
Adding a delay in webots

Adding a delay

When adding a delay in webots you need to be aware of some things. Basically you can calculate time using a function.

Cpp

Eg :- float currentTime = float(robot->getTime());

(In the example the Current time is assigned to a variable named currentTime. )

The way of finding current time for the other languges such as C, python, matlab, java can be found in the official documentation given below.

To add a delay you need to know another thing. That is the way of using a do-while loop. When using a do-while loop you need to call robot->step().

Cpp

Eg:- do {

//relevant command

robot->step();

} while(condition);

(If you don’t use step(), the webots simulation won’t progress and the time will remain the same)

Now let’s see the delay code

float current_time_1 = float(robot->getTime());

float current_time_2= float(robot->getTime());

do {

current_time_2 = float(robot->getTime());

robot->step(1);

} while(current_time_2 < (current_time_1 + 2));

(From this a delay of 2 seconds is created. If you need to change the delay just change 2 to another value.)

The full cpp code for a 2 second delay is given below.

#include <webots/Robot.hpp>

#define TIME_STEP 32

using namespace webots;

void delay_function();

Robot *robot = new Robot();

int main() {

while (robot->step(TIME_STEP) != -1) {

//One command

delay_function();

//Another command

};

delete robot;

return 0;

}

void delay_function() {

float current_time_1 = float(robot->getTime());

float current_time_2= float(robot->getTime());

do {

current_time_2 = float(robot->getTime());

robot->step(1);

} while(current_time_2 < (current_time_1 + 2));

}

Cheers.

If you enjoyed this article and would like to show some support, consider buying me a coffee on Ko-Fi.

Your support not only helps me keep creating content like this but also fuels me! ☕️📚

Thank you for being an amazing reader!

Here’s my Ko-Fi link: https://ko-fi.com/udarakumarasena

--

--

Protonest IoT
Protonest IoT

Written by Protonest IoT

We make your IoT ideas a reality

No responses yet