(micros() is a function generating the time since system start, in micro seconds, periodTime is the desired period time of the carrier, and periodOnTime the desired onTime (thus duty cycle = perioOnTime/periodTime))
Code: Select all
unsigned long start = micros();
unsigned long stop = start + time;
unsigned int count = 0U;
while (micros() < stop) {
count++;
unsigned long now = micros();
int onTime = min(periodOnTime, (int) (stop - now));
if (onTime > 0) {
TURN_ON;
delayMicroseconds((unsigned) onTime);
}
TURN_OFF;
unsigned long targetTime = min(start + count * periodTime, stop);
int timeOff = (int) (targetTime - micros());
if (timeOff > 0)
delayMicroseconds((unsigned) timeOff);
}