/** * Tachymétre minimaliste avec une carte Arduino */ /* constantes pour la broche de mesure */ const byte PIN_SIGNAL = 2; /** Fonction setup() */ void setup() { /* Initialise le port série */ Serial.begin(115200); /* Met la broche en entrée */ pinMode(PIN_SIGNAL, INPUT_PULLUP); } /** Fonction loop() */ void loop() { /* Mesure la durée de la (demi) période */ unsigned long periode = pulseInCycle(PIN_SIGNAL, HIGH, 1000000); /* Affiche le résultat de la mesure en RPM */ Serial.println(1000000 / periode * 60); delay(1000); } unsigned long pulseInCycle(byte pin, byte startState, unsigned long timeout) { /* Compute low-level bitmask and port for direct I/O reading */ byte bitmask = digitalPinToBitMask(pin); volatile byte* port = portInputRegister(digitalPinToPort(pin)); byte mask = startState ? bitmask : 0; /* Get the starting time (for the timeout handling) */ unsigned long startMicros = micros(); /* Wait the end of the current starting state (avoid partial measure) */ while ((*port & bitmask) == mask) { if (micros() - startMicros > timeout) return 0; } /* Wait for the next starting state */ while ((*port & bitmask) != mask) { if (micros() - startMicros > timeout) return 0; } /* Start the counter */ unsigned long start = micros(); /* Measure the starting state duration */ while ((*port & bitmask) == mask) { if (micros() - startMicros > timeout) return 0; } /* Measure the ending state duration */ while ((*port & bitmask) != mask) { if (micros() - startMicros > timeout) return 0; } /* Compute the total duration */ return micros() - sta