//////////////////////////////////////////////////////
//ATtiny85 Period Time & Frequency counting via ISR;
// Time counting more than 255
// Mokhtar Zerdali 2022.
#include<avr/io.h>
#include<util/delay.h>
#include <TinyDebug.h>
#define F_CPU 8000000UL
#define INT_PIN PB2 // INT0 -> PB2 external interrupt pin
volatile unsigned long Overflow ; // value >256, and volatile between void programs
volatile unsigned long Count;
volatile unsigned long Time;
volatile unsigned long Start_Time;
volatile unsigned long Finish_Time;
volatile unsigned long Elapsed_Time;
volatile float Frequency;
volatile int PRB;// pulse rate beat
volatile byte i;
void counter_setup()
{
//Debug.begin( 9600 ); // for tiny_debug_serial
Debug.begin();
//Debug.println(F("Hello, clock is running"));
DDRB = (1 << PB1) | (1 << PB0) | (1 << PB3) | (1 << PB4);
TCCR0A = 0X00; //TCCR0A to low for normal port operation and mode 0.
TCCR0B = 0X00; //WGM02=0
TCCR0B |= (1 << CS00); //No prescaling clk
TCNT0 = 0; //initializing the counter to 0
// Overflow >255 interrupts
TIMSK = bit (TOIE0); //|= (1 << TOIE0); //enabling overflow interrupts of timer0
Overflow = 0;
//Externall interrupts
GIMSK |= (1 << INT0); // enable external interrupt
// Mode sense of MCUCR Register to choose the adequate sense
/////////////////////////////////////
// MCUCR &= ~(bit(ISC01) | bit(ISC00)); //1/ INT0 on low level
// The low level of INT0 generates an interrupt request
//MCUCR = //(1 << ISC00); //2/ Any Logical mode sense
MCUCR = (1 << ISC01); //3/ FALLING mode sense
//MCUCR = bit(ISC01) | bit(ISC00); //4// RISING mode sense
sei(); //global interruption
}
///////////////////////////////
ISR (TIMER0_OVF_vect) //Interrupt vector for Timer0 >>>> Counter0
{
Overflow++; // count number of overflow
} // End of TIMER0_OVF_vect
//////////////////////////////
ISR(INT0_vect) // Interrupter vector for external inerruption
{
i = digitalRead(PB2);
digitalWrite(PB1, i);
Count = TCNT0 + (Overflow << 8); //n° overflow*256
Time = 0.000125 * Count; // 8MHz ; clk : 125 ns.
Start_Time = Time;
//Debug.println("Start_Time:");
//Debug.print(Start_Time);
//Debug.println("ms");
//Debug.println("###:");
//Debug.println("Elapsed_Time:");
//Debug.print(Elapsed_Time);
//Debug.println("ms");
//Debug.println("###:");
Debug.println("Frequency:");
Debug.print(Frequency);
Debug.println("Hz");
Debug.println("###:");
Debug.println("Pulse rate beat:");
Debug.print(PRB);// heart
Debug.println("/min");
Debug.println("###:");
}
///////////////////////////////////
int main()
{
counter_setup();
while (1)
{
Count = TCNT0 + (Overflow << 8); //n° overflow*256
Time = 0.000125 * Count; // 8MHz ; clk : 125 ns.
Finish_Time = Time;
Elapsed_Time = Finish_Time - Start_Time;
Frequency = 1000 / float(Elapsed_Time); // on Hz
PRB = 60* Frequency; //pulse rate beat
//if (Start_Time > 1500)
{
PORTB = bit(PB0);
}
}
}