Also, if you just check frequency, skipping duty cycle, and completely forgo using interrupts, you can measure up to 60-ish KHz. With a regularly timed event, the interrupt code that runs behind the scenes interferes, and actually slows things down near the physical limits of the machine.
const byte inputPin = 2; // INT.0
boolean inputState = false;
boolean lastInputState = false;
long count = 0UL;
unsigned long previousDisplayMillis = millis();
const long displayMillis = 500L;
void setup() {
pinMode(inputPin, INPUT_PULLUP);
Serial.begin(115200);
}
void loop() {
inputState = PIND & 4; // faster than: inputState = digitalRead(inputPin);
if (inputState != lastInputState) {
count++;
lastInputState = inputState;
}
// --------- Run this code every *half* second ------------------
if (millis() - previousDisplayMillis >= displayMillis) {
previousDisplayMillis += displayMillis;
Serial.print(count); // *** SERIAL PRINT ***
Serial.print(" Hz"); // *** SERIAL PRINT ***
Serial.print('\n'); // *** SERIAL PRINT ***
count = 0UL;
}
}