Skip to content

Instantly share code, notes, and snippets.

@sovcik
Created November 4, 2020 13:45
Show Gist options
  • Select an option

  • Save sovcik/56fe06963ea46d6f2cf04582b719dc04 to your computer and use it in GitHub Desktop.

Select an option

Save sovcik/56fe06963ea46d6f2cf04582b719dc04 to your computer and use it in GitHub Desktop.
Arduino ATmega328 as Asynchronous Pulse Counter
// ARDUINO as ASYNCHRONOUS PULSE COUNTER
//
// Pulses are counted asynchronously using Timer1 circuit as counter. Interrupt is
// triggered once counter reaches the set level.
//
// Pulse source should be connected to pin D5 (alternative function T1 - Timer1)
// Make sure to install pull-down resitor on pulse input pin to avoid ghost inputs.
// Also make sure to debounce pulse source, e.g. in case of using mechanical button
//
// For more information see ATmega328P DataSheet section 15. 16-bit Timer1/Counter with PWM
#include <Arduino.h>
#include <avr/io.h>
#include <avr/interrupt.h>
volatile uint16_t counterTriggered = 0;
void setup() {
Serial.begin(9600);
DDRD &= ~(1 << DDD5); // Clear the PD5 pin
// PD5 is now an input
//TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt
TIMSK1 |= (1 << OCIE1A); // enable timer interrupt if TCNT1 == OCR1A
TCCR1A = 0; // clear register
TCCR1B = 0; // clear register
TCCR1B |= (1 << WGM12); // CTC mode, clear on reaching OCR1A
TCCR1B |= (1 << CS12) | (1 << CS11) | (1 << CS10); // clock on T1 rising edge
// Setting ClockSelect CSn bits in TCCRnB register will start counter/timer
OCR1A = 10; // set Timer1 comparator A - number of pulses to trigger an interrupt
sei(); // enable interupts
Serial.print("Registers: ");
Serial.print(TCCR1A, BIN);
Serial.print(" ");
Serial.print(TCCR1B, BIN);
Serial.print(" ");
Serial.print(OCR1A, BIN);
Serial.println();
TCNT1 = 0;
delay(5000);
}
void loop(){
// here can be any code
Serial.print("Counter=");
Serial.print(TCNT1);
Serial.print(" ");
Serial.println(digitalRead(5));
delay(1000);
if (counterTriggered){
uint16_t c = counterTriggered;
counterTriggered = 0;
Serial.print("Counter triggered ");
Serial.print(c);
Serial.println(" x");
}
}
// Interrupt handler - avoid extensive/blocking code here
ISR (TIMER1_COMPA_vect){
counterTriggered++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment