// Arduino 2 - Counter with Frequency Calculation
int pulsePin = 2; // Input pin connected to pulse generator
int pulsePin2 = 9; // Output pin for pulse
volatile int pulseCount = 0; // Volatile variable for counting pulses
unsigned long lastPulseTime = 0; // Time of the last pulse
unsigned long pulseInterval = 0; // Time interval between pulses
float frequency = 0; // Frequency calculation (Hz)
void setup() {
pinMode(pulsePin, INPUT); // Set pulse pin as input
pinMode(pulsePin2, OUTPUT); // Set pulse pin as output
attachInterrupt(digitalPinToInterrupt(pulsePin), countPulse, RISING); // Interrupt on rising edge
Serial.begin(9600); // Initialize Serial Monitor
}
void loop() {
// Generate a pulse
digitalWrite(pulsePin2, HIGH); // Send a pulse
delayMicroseconds(50); // Pulse width of 1 microsecond
digitalWrite(pulsePin2, LOW); // End the pulse
delayMicroseconds(50); // Wait for 1 microsecond before next pulse
// Print pulse count and frequency every second
static unsigned long lastMillis = 0;
if (millis() - lastMillis >= 1000) {
lastMillis = millis();
Serial.print("Pulse Count: ");
Serial.println(pulseCount); // Print the number of pulses detected in the last second
// Calculate the frequency
if (pulseCount > 1) { // Ensure at least two pulses have been counted
// To avoid issues with millis() overflow, we use the difference directly
pulseInterval = millis() - lastPulseTime; // Time between the last two pulses
if (pulseInterval > 0) { // Ensure the pulse interval is positive
frequency = 1000.0 / pulseInterval; // Calculate frequency in Hz
Serial.print("Frequency: ");
Serial.print(frequency); // Print the frequency in Hz
Serial.println(" Hz");
} else {
Serial.println("Frequency: Invalid interval");
}
} else {
Serial.println("Frequency: Not enough pulses");
}
pulseCount = 0; // Reset pulse count for the next second
}
}
void countPulse() {
pulseCount++; // Increment pulse count on each pulse detected
lastPulseTime = millis(); // Update last pulse time
}