#define mTimeBufferSize 64 // MUST only be 2^x value, such as 2, 4, 8, 16, 32, 64, 128
volatile unsigned long mTimesBuffer[mTimeBufferSize]; // Buffer to store values before they are sent over serial
volatile unsigned long mTimesBufferStorePtr=0; // Pointer into the buffer showing where we are currently storing values to. Note this pointer does not loop over, it counts up continually
volatile unsigned long mTimesBufferSendPtr=0; // Pointer into the buffer showing where we are currently sending values over serial from. Note this pointer does not loop over, it counts up continually
unsigned long lastSent = 0; // Used to hold the previous micros() value sent to the PC so the difference from current micros can be calculated
void setup()
{
Serial.begin(115200); // Enable serial port communication at 115200 baud
pinMode(2, INPUT); // Set digital pin 2 to an input pin
digitalWrite(2, HIGH);
attachInterrupt(0, onChangeX, FALLING); // Setup interrupt 0 (which is on digital pin 2), triggered on a rising edge input, calling the onChangeX function
}
void loop()
{
if(mTimesBufferSendPtr < mTimesBufferStorePtr)
{
// The send pointer is behind the store pointer so there must have been a value written that we can send
//Serial.print(mTimesBufferStorePtr - mTimesBufferSendPtr); // Send how far the send pointer is behind the store pointer, if this gets higher then mTimeBufferSize a buffer overflow has occured and the data will not be accurate
//Serial.print(",");
//Serial.print(mTimesBuffer[mTimesBufferSendPtr & (unsigned long)(mTimeBufferSize-1)]); // Send the next micros value in the buffer, buffer is incremented later.
//Serial.print(",");
Serial.println(mTimesBuffer[mTimesBufferSendPtr & (unsigned long)(mTimeBufferSize-1)] - lastSent); // Subtract the previous micros from this micros to get the pulse time and send across serial port
lastSent = mTimesBuffer[mTimesBufferSendPtr++ & (unsigned long)(mTimeBufferSize-1)];
}
}
// Function called on every interrupt
void onChangeX()
{
mTimesBuffer[mTimesBufferStorePtr & (unsigned long)(mTimeBufferSize-1)] = micros(); // Put the current micros() value into the next space in the buffer
mTimesBufferStorePtr++; // Increment the buffer store pointer to the next location
}