Arm Mbed OS support forum

Thread fail to geneate right number for pre-calculated pulses

I have some simple code for my stepper motor controller. This following code suppose to generate right number of pulses per second. If waiting period is 10000us, then program is supposed to print out 100 ( 10^6/10000 = 100). But If I change waiting period is 5000us, then program still prints out 100. Could someone explain what is missing here?

Environment: Mbed studio 1.0/ Nucleo-F401RE

#include “mbed.h”
BufferedSerial pc(USBTX, USBRX);
FileHandle *mbed::mbed_override_console(int fd)
{
return &pc;
}
Thread thread;
int pulses = 0;
void motor_thread()
{
while (true) {
wait_us(10000);
pulses++;
}
}
int main()
{
Timer t;
t.start();
thread.start(motor_thread);
while (true) {
if(t.read() >= 1) {
printf(“pulse: %d\n”, pulses);
pulses = 0;
t.reset();
}
}
}

Hi Xuan,

Try int pulses = 0;

Not sure which mbedOS version you’re using but it seems common in the docs:

https://os.mbed.com/docs/mbed-os/v6.1/mbed-os-api-doxy/mbed__wait__api_8h_source.html

that ‘wait_us’ shouldn’t be used for delays greater than 10us.

I was able to recreate your observed behaviour with OS5.12.4 (just what I’m currently using).

The OS6.1 doc: https://os.mbed.com/docs/mbed-os/v6.1/apis/wait.html says to use sleep functions as wait is deprecated but sleep resolution is only down to the ms.

Even then, I was only able to see expected results using a delay range of 10-100ms in steps of 10ms.

I think the sleep/wait methods are not ‘fine’ enough to get the timing resolutions you require. This is my test code:

#include "mbed.h"

Serial pc(USBTX, USBRX);

Thread thread;
DigitalOut led(LED1);

volatile int pulses, delay;

void motor_thread() {
	while (true) {
        ThisThread::sleep_for(delay);
        pulses++;
	}
}

int main() {
	Timer t;

	t.start();

    pulses = 0;
    delay = 10;

	thread.start(motor_thread);

	while (true) {
		if(t.read() >= 1.0) {
            led = !led;
			printf("pulse: %d, delay: %d\n", pulses, delay);
			pulses = 0;
            if((delay+=10) > 100)
                delay = 10;
			t.reset();
		}
	}
}

it outputs the following:

pulse: 10, delay: 100
pulse: 91, delay: 10
pulse: 50, delay: 20
pulse: 34, delay: 30
pulse: 25, delay: 40
pulse: 20, delay: 50
pulse: 17, delay: 60
pulse: 15, delay: 70
pulse: 13, delay: 80
pulse: 11, delay: 90
pulse: 10, delay: 100
pulse: 91, delay: 10
pulse: 50, delay: 20
pulse: 34, delay: 30
pulse: 25, delay: 40
...