Good Day All,
I’m seeking some guidance on how setup dual frequency counters on my Mega 2560. By using standard library examples, the hardware and code functions flawlessly. At the moment, I’m using a single counter via Frequency.h on pin 47.
There is very little out there with respect to code examples for the ATMega2560, so my studies switched to the internals of the Atmel processor to help me understand what I’m coding, and how certain commands work. Downloading the datasheet from the Atmel website was a good start, as well as the pin to header legend which I’ve linked. I’ve also mapped out the port layouts for a visual if anyone is interested.
By using the datasheet, and studying the examples of cpp files, I have successfully setup inputs on pins D47 and D38 to count two separate frequencies. The problem is, the code examples use a delay of 1000 msecs which produce a slow update in data flow.
After messing around with variables, and removing the delay, etc. I’m not able to increase the data update rate (in Serial Monitor) without effecting the frequency output.
IE: With 1000 msec delay, the output is fine (The Serial Monitor output = frequency generator). With a reduced delay of 10 msec, the output reads 1/10th the frequency generator.
I realize the one second delay is required for the timer to count “cycles per second”, and hence return the proper frequency, but that’s not suitable for my application. It appears that editing the code to remove the delay is not going to work based on how the Atmel circuitry is designed (at least with my limited knowledge). Am I stuck, or do I need to look at modifying the .h/.cpp files to allow an additional input pin to count pulses?
Thanks for any advice!
Datasheet Link:
Sample Code:
#include "FreqCounter.h"
#include <FreqMeasure.h>
#include <util/delay.h>
//#include <util/millis.h>
int timeCounter = 100, timePassed;
unsigned long tachometer=0;
unsigned int tovf0=0;
unsigned long temp0=0;
unsigned long speedometer=0;
unsigned int tovf5=0;
unsigned long temp5=0;
//timer 0, 8 bit counter
ISR(TIMER0_COMPA_vect) { tovf0++; }
//timer 5, 16 bit counter
ISR(TIMER5_OVF_vect) { tovf5++; }
void setup(){
Serial.begin(57600);
PORTD = (1 << 7); //PD7 Pullup, Input D38
PORTL = (1 << 2); //PL2 Pullup, Input D47
TCCR0A = 0;
TCCR0B = (1 << CS02) | (1 << CS01) | (1 << CS00); // Setting external clock, rising edge
TIMSK0 = (1 << OCIE0A); // Interrupt enable
TCCR5A = 0;
TCCR5B = (1 << CS52) | (1 << CS51) | (1 << CS50); // Setting external clock, rising edge
TIMSK5 = (1 << TOIE5); // Interrupt enable
_delay_ms(1000); // One second delay?
reset_Counters();
}
void loop(){
_delay_ms(1000);
tachometer = TCNT0;
speedometer = (TCNT5H << 8)|TCNT5L;
temp0 = 256*(unsigned long)tovf0;
temp5 = 65536*(unsigned long)tovf5;
tachometer += temp0;
speedometer += temp5;
Serial.print(tachometer);
Serial.print(',');
Serial.println(speedometer);
}
void reset_Counters(){
TCNT0 = 0;
tovf0 = 0;
TCNT5H = 0;
TCNT5L = 0;
tovf5 = 0;
}