
Originally Posted by
luni
setPeriod changes the period immediately. I.e., it will end the current period and restart the timer with the new period. setNextPeriod is supposed to set a new period after the current one is done to prevent partial periods. There should be no delay (other than the time needed for executing ) in both functions.
I kind of remember having issues with setNextPeriod some time ago but didn't look into it deeper. So, let me know if setNextPeriod is not working as expected.
setNextPeriod doesn't seem to work at all in my code, but setPeriod seems ok. Ok in the sense that at least there are 4 pulses of the same period, then 4 more at a different period. The last long pulse is sort of strange, but I think it is still "forward". setNextPeriod does not change the waveform, at least not in my code.
Code:
#include "TeensyTimerTool.h"
using namespace TeensyTimerTool;
// for Teensy 4.1 only
PeriodicTimer t1(GPT1);
PeriodicTimer t2(GPT2);
float maxperiod, periodincrement;
int maxcount, gpt2period;
volatile bool forward;
volatile float period;
float initperiod;
#define A 1
#define B 2
// Callbacks
void a_ns( )
{
static int state=0;
switch (state & 3) {
case 0:
{
if (forward) { digitalWriteFast(A, HIGH); digitalWriteFast(B, LOW); }
else { digitalWriteFast(A, LOW); digitalWriteFast(B, HIGH); }
break;
}
case 1:
{
if (forward) { digitalWriteFast(A, HIGH); digitalWriteFast(B, HIGH); }
else { digitalWriteFast(A, HIGH); digitalWriteFast(B, HIGH); }
break;
}
case 2:
{
if(forward) { digitalWriteFast(A, LOW); digitalWriteFast(B, HIGH); }
else { digitalWriteFast(A, HIGH); digitalWriteFast(B, LOW); }
break;
}
case 3:
{
digitalWriteFast(A, LOW); digitalWriteFast(B, LOW);
// same for both fwd and reverse
break;
}
}
state++;
}
void slowtime()
{
bool test1;
test1 = false;
period += periodincrement;
if (period > maxperiod)
{
period = initperiod;
digitalWriteFast(3, HIGH); // add timing mark to detect beginning
delayNanoseconds(20);
digitalWriteFast(3, LOW);
}
if (test1)
{
t1.setNextPeriod(period);
t2.setNextPeriod(period*16);
}
else
{
t1.setPeriod(period);
t2.setPeriod(period*16);
}
}
void setup() {
// put your setup code here, to run once:
for(unsigned pin=1; pin<=3; pin++) pinMode(pin, OUTPUT);
Serial.begin(9600);
//while(!Serial) delay(10);
initperiod = 1.0;
gpt2period = 16*initperiod; // interrupt every 4 full pulses
period = initperiod; // initial start interrupt period us. Real period is 4x.
periodincrement = 1.0;
maxperiod = 100*periodincrement; //
Serial.print("max period = "); Serial.print(maxperiod);
forward = true;
t1.begin( a_ns, period); // default time is in us. Min value is 0.25.
t2.begin( slowtime, gpt2period);
}
void loop() {
// put your main code here, to run repeatedly:
}
if test1 is true, (using setNextPeriod) the code fails to create the varying waveform. If false, (using setPeriod) the waveform looks ok.
