Solving Approach,
Arduino UNO (Pulse Generator)
Arduino UNO (Pulse Counter)
The pulse generator produces pulses on digital pin 7, which is connected to digital pin 5 of the pulse counter. Digital pin 5 serves as the input for the external clock source to
#define SWITCH_PIN 12
#define DEBOUNCE_DELAY 50 // debounce delay
bool last_button_state = 1; // Previous button state (1: not pressed, 0: pressed)
bool current_button_state = 1; // Current button state
unsigned long last_debounce_time = 0; // Timestamp of the last button state change
uint8_t overflowFlag = 0;
void setup() {
Serial.begin(115200);
pinMode(SWITCH_PIN, INPUT_PULLUP);
// Configure Timer1 as a counter
TCCR1A = 0x00; // Normal mode
TCCR1B = 0x07; // External clock source on T1 pin, rising edge
TIMSK1 |= B00000001; // Enable Timer Overflow Interrupt
TCNT1 = 0; // Initialize counter to 0
}
void loop() {
if (is_debounced_press(SWITCH_PIN)) {
uint32_t pulseCount = (overflowFlag*65536) + TCNT1;
Serial.println("Number of Pulses: ");
Serial.println(pulseCount);
TCNT1 = 0;
overflowFlag = 0;
}
}
bool is_debounced_press(int button_pin) {
int reading = digitalRead(button_pin);
// If the button state has changed, reset the debounce timer
if (reading != last_button_state) {
last_debounce_time = millis();
}
last_button_state = reading;
// If the button state is stable for more than 50 msec the debounce delay, update the state.
if ((millis() - last_debounce_time) > DEBOUNCE_DELAY) {
if (reading != current_button_state) {
current_button_state = reading;
if (current_button_state == 0) {
return true; // valid press detected
}
}
}
return false; // No valid press detected
}
ISR(TIMER1_OVF_vect)
{
overflowFlag++;
}
is_debounced_press()
the function checks for a debounced button press.overflowFlag * 65536) + TCNT1.
TCNT1
) and overflow flag (overflowFlag
) are reset to 0.ISR(TIMER1_OVF_vect)
function increments overflowFlag
each time Timer1 overflows.Timer Configuration and Calculations
TCCR1A
= 0x00: Timer1 is set to normal mode (no PWM or waveform generation).TCCR1B
= 0x07: Timer1 is configured to use an external clock source (T1 pin) and increment on the rising edge of the input signal.TIMSK1 |= B00000001
: The Timer1 overflow interrupt is enabled. This interrupt triggers when the counter overflows (i.e., exceeds 65,536).TCNT1
= 0: The Timer1 counter is initialized to 0.ISR(TIMER1_OVF_vect)
interrupt service routine is triggered, and the overflow flag is incremented.= 131072 + 1234.
= 132306.
Button Debouncing Logic
digitalRead(SWITCH_PIN)
.DEBOUNCE_DELAY
).Hardware Setup
Serial Monitor Output
Video