Advertisement
TolentinoCotesta

ATMega328 Frequency Measure

Aug 4th, 2020
1,242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1.  
  2. #define SIG_A 2
  3. #define SIG_B 3
  4.  
  5. uint16_t signalA_T0 = 0;
  6. uint16_t signalB_T0 = 0;
  7.  
  8. uint16_t tick_counterA = 0;
  9. uint16_t tick_counterB = 0;
  10.  
  11. // Instruction in ISR functions need some time to be executed
  12. int16_t offsetA = 2;
  13. int16_t offsetB = 2;
  14.  
  15. float frequencyA = 0.0;
  16. float frequencyB = 0.0;
  17.  
  18. void setup() {
  19.   Serial.begin(115200);
  20.   pinMode(SIG_A, INPUT_PULLUP);
  21.   pinMode(SIG_B, INPUT_PULLUP);
  22.   setupTimer1();
  23.   attachInterrupt(digitalPinToInterrupt(SIG_A), getSignal_A, RISING);
  24.   attachInterrupt(digitalPinToInterrupt(SIG_B), getSignal_B, RISING);
  25.   delay(1000);
  26. }
  27.  
  28. void loop() {
  29.  
  30.   /*
  31.    *  F_CPU = 16Mhz    Timer1 prescaler = 8
  32.    *  Timer1 will be incremented every 1/(16.000.000 / 8) = 0.5uS
  33.   */
  34.   frequencyA = (1 / (0.0000005F * (tick_counterA + offsetA))) ;
  35.   frequencyB = (1 / (0.0000005F * (tick_counterB + offsetB))) ;
  36.  
  37.   static uint32_t printTime = 0;
  38.   if(millis() - printTime > 1000){
  39.     printTime = millis();
  40.     Serial.print("\nTick counter A: ");
  41.     Serial.print(tick_counterA);
  42.     Serial.print(";\tFrequenza A: ");
  43.     Serial.println(frequencyA);  
  44.     Serial.print("Tick counter B: ");
  45.     Serial.print(tick_counterB);
  46.     Serial.print(";\tFrequenza B: ");
  47.     Serial.println(frequencyB);      
  48.   }
  49. }
  50.  
  51. void getSignal_A(){
  52.   tick_counterA = TCNT1 - signalA_T0;  
  53.   signalA_T0 = TCNT1;  
  54. }
  55.  
  56. void getSignal_B(){
  57.   tick_counterB = TCNT1 - signalB_T0;  
  58.   signalB_T0 = TCNT1;
  59. }
  60.  
  61. void setupTimer1() {
  62.   // Clear registers
  63.   TCCR1A = 0;
  64.   TCCR1B = 0;
  65.   TCNT1 = 0;
  66.   // Prescaler 8
  67.   TCCR1B |= (1 << CS11);  
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement