Skip to content

Improving delay() #57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
mikaelpatel opened this issue Dec 26, 2018 · 2 comments
Closed

Improving delay() #57

mikaelpatel opened this issue Dec 26, 2018 · 2 comments

Comments

@mikaelpatel
Copy link

mikaelpatel commented Dec 26, 2018

The current implementation only calls yield() once (https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c#L106)

void delay(unsigned long ms)
{
	uint32_t start = micros();

	while (ms > 0) {
		yield();
		while ( ms > 0 && (micros() - start) >= 1000) {
			ms--;
			start += 1000;
		}
	}
}

Could be improved to something like:

void delay(unsigned long ms)
{
	uint32_t start = micros();
	while ( ms > 0 && (micros() - start) >= 1000) {
		yield();
		ms--;
		start += 1000;
	}
}

Also adding the attribute "weak" could allow redefinition when needed, e.g. allow support for low power mode in Cooperative Scheduler, https://github.com/mikaelpatel/Arduino-Scheduler

void delay(unsigned long ms) __attribute__ ((weak));

@cmaglie
Copy link
Member

cmaglie commented Jan 3, 2019

Looks like the "improved" version will never enter the while loop because (micros() - start) >= 1000 can not be true?

@mikaelpatel
Copy link
Author

@cmaglie My bad. Got confused over the two while-loops. Sorry about that.

There was a second request which actually is more "urgent"; making delay() a weak definition so that it could be redefined as yield() allows. I would like to add a low-power mode to my Scheduler library (when all tasks are in delay()).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants