From 4e8a2b6b8ddc91886788aa30956971e1034c83ef Mon Sep 17 00:00:00 2001 From: Mateusz Piwek Date: Sat, 20 Jul 2024 15:18:43 +0200 Subject: [PATCH] msDelay added --- wiringPi/wiringPi.c | 35 +++++++++++++++++++++++++++++++++++ wiringPi/wiringPi.h | 1 + 2 files changed, 36 insertions(+) diff --git a/wiringPi/wiringPi.c b/wiringPi/wiringPi.c index 22d2010..1fff468 100644 --- a/wiringPi/wiringPi.c +++ b/wiringPi/wiringPi.c @@ -2617,6 +2617,41 @@ void delay (unsigned int howLong) nanosleep (&sleeper, &dummy) ; } +/* + * msDelay: + * Wait for some number of milliseconds + ********************************************************************************* + */ +void msDelay (unsigned int time_ms) { + struct timespec sleeper, t_remained ; + int interup_cnt = 32 ; // maximum number of interruptions + + sleeper.tv_sec = (time_t)(time_ms / 1000) ; + // '1000 * 1000' is easier to read vs. '1000000' + sleeper.tv_nsec = (long)(time_ms % 1000) * 1000 * 1000 ; + + // 'nanosleep' can be interuped by a signal or error. + // If interrupt is due to signal then resume sleep. + // If it's due to error print it and exit a function. + // Let's set a limit for number of interuptions to + // detect if something strange happens in the system. + while (nanosleep (&sleeper, &t_remained) == -1) { + if (errno != 0) { + perror (strerror (errno)); + return; + } + + sleeper.tv_sec = t_remained.tv_sec; + sleeper.tv_nsec = t_remained.tv_nsec; + + if( (--interup_cnt) == 0 ) { + perror ("nanosleep(...) has been frequently interrupted") ; + break; + } + } + + return ; +} /* * delayMicroseconds: diff --git a/wiringPi/wiringPi.h b/wiringPi/wiringPi.h index 9a26b74..e1e61ff 100644 --- a/wiringPi/wiringPi.h +++ b/wiringPi/wiringPi.h @@ -304,6 +304,7 @@ extern int piHiPri (const int pri) ; // Extras from arduino land extern void delay (unsigned int howLong) ; +extern void msDelay (unsigned int time_ms) ; extern void delayMicroseconds (unsigned int howLong) ; extern unsigned int millis (void) ; extern unsigned int micros (void) ;