/* Test counting cpu cycles
Teensy 3.1, Arduino 1.61 and Teensyduino 1.21
*/
const int gpsPin = 2;
unsigned long gpsPeriod = 0;
volatile int gpsFlag; // set by gps interrupt
unsigned long longCount = 0;
long test;
void setup() {
ARM_DEMCR |= ARM_DEMCR_TRCENA; // info from teensy forum, access cycle counter
ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;
pinMode(gpsPin, INPUT);
Serial.begin(9600);
attachInterrupt(gpsPin, gpsISR, RISING); // set flag high on rising edge
}
void loop() {
gpsPeriod = gpsTest();
longCount++;
test = gpsPeriod - 480000; // 10 msec input, 48 MHz clock
if (test < -50 || test > 50) { // test typically = -8 for this test setup
Serial.print(longCount);
Serial.print(" ");
Serial.print(test);
Serial.print(" ");
Serial.println(gpsPeriod);
}
delay(100);
}
//-------------------------------------
unsigned long gpsTest() {
unsigned long period = 0;
unsigned long firstEdge = 0;
unsigned long secondEdge = 0;
gpsFlag = 0;
while (!gpsFlag) { // wait for line to go high, start of timing interval
}
firstEdge = ARM_DWT_CYCCNT; // free running time in cycle counts
gpsFlag = 0;
while (!gpsFlag) { // wait for next edge
}
secondEdge = ARM_DWT_CYCCNT;
// subtract to get period
period = secondEdge - firstEdge;
return period;
}
//-------------------------------------
void gpsISR() {
gpsFlag = 1;
}