A
A
Alex2014-03-28 16:03:38
PHP
Alex, 2014-03-28 16:03:38

Pause while executing a script

It is necessary to send commands over the network (UDP) to Arduino. There is PHP. Yes, PHP is not the best option, but what is there.
There is an array $asciiCommandsArray, where each cell is a command as a string of ASCII characters. In the loop, I send each line to the Arduino. Arduino clearly accepts everything, but there must be a certain pause between sending commands. 10 milliseconds. I insert the function usleep(10000); which is equal to 10 milliseconds. To check the accuracy of the pause time, I then write to the $commandTime array how much time has passed since the previous iteration. Commands > 2000. The script runs for about 30 seconds. Pause between iterations, according to var_dump($commandTime); is 30 milliseconds. Those. more than I need. I thought, like you, that the functions usleep(10000); and microtime(); take this time. I did this: usleep(10); the pause is still 20 milliseconds. I commented out usleep(10);. Here the whole script was executed in 15 milliseconds. Tried time_nanosleep(); and set a few nanoseconds - the result is still 15 milliseconds. I tried it first on a laptop with Denwer, then I threw it on a powerful VDS, it runs strictly 20 milliseconds there. Those. if you write usleep(large number); will run >= 15 milliseconds, but no less! I don't even know what to guess. Any ideas?

//Подключаемся к Ардуино
$fp = fsockopen('udp://172.16.1.1', 8000, $errno, $errstr);

//Засекаем время начала выполнения отправки данных
$start = microtime(true);

//Отправляем в цикле команды в Ардуино
for($i = 0; $i <= count($asciiCommandsArray) - 1; $i++){
    //Отправляем АСКИ строчку в Ардуино
    fwrite($fp, $asciiCommandsArray[$i]);
    //Делаем паузу
    usleep(10000);

    //Вычисляем и запоминаем сколько прошло секунд
    $commandTime[] = microtime(true) - $start;
}

echo '<br>Время выполнения скрипта:  '.(microtime(true) - $start).' сек. <br>';

var_dump($commandTime);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Makarov, 2014-03-28
@FlipLab

The increment operation is atomic, which means that its execution time depends only on the processor frequency.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question