Variable for Arduino Timer

Hi, I have been trying to set the timer constant of OCR1A to the variable TImer_count so that when I change Sfreq it automatically updates Timer_count and hence OCR1A. Does anyone know how to and what kind of variable I set Timer_count to? Many thanks!

int Sfreq = 100;
unsigned long Timer_count = ceil(((16*10^6) / (Sfreq*1024) - 1));

voidSetup(){
// Previous timer code
OCR1A = 156; //-----> I want to set this number to Timer_count such that OCR1A = Timer_count
//After timer code
}

Hi,

You can place those instructions in the draw() function :

int Sfreq = 100;
unsigned long Timer_count;

void draw() {
  Timer_count = ceil(((16*10^6) / (Sfreq*1024) - 1));

  OCR1A = Timer_count;
}

Because the draw() function is going to be executed roughly 60 times per second, the OCR1A variable is going to be assigned to the Timer_count value that is related to the Sfreq value.

If you used setup() to assign your variables, then the function would only be executed once at startup and it’s not updating in real time.

(note that it’s void setup() not void Setup() :wink: )

1 Like

Hi there Joseph. Thank you so much. I am trying to implement this but it isn’t working for some reason?

Here is my full setup code:

#include <SoftwareSerial.h> 
#include <avr/io.h>

int i;
int r_pin = A0;
int sample_output;
int Sfreq = 1000;
unsigned long Timer_count;

void setup (){
  noInterrupts();
  Timer_count = (16*10^6) / (Sfreq*1024) - 1;
  Serial.begin (9600);
  ADCSRA |= (1 << ADPS0) |  (1 << ADPS1) | (1 << ADPS2);  // ADC Prescaler of 128

  //set timer1 interrupt at Sfreq Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = Timer_count;// = (16*10^6) / (Sfreq*Timer Prescaler) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and and CS11 and CS10 bits for prescaler <----
  TCCR1B |= (1 << CS12) | (1 << CS10); //-- 1024
//  TCCR1B |= (1 << CS12);               //-- 256
//  TCCR1B |= (1 << CS11) | (1 << CS10); //-- 64
//  TCCR1B |= (1 << CS11);               //-- 8
//  TCCR1B |= (1 << CS10);               //-- 1

  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  interrupts();
}  // end of setup

Could you take a look please?

Hi @saaqib.m,

Your code is from arduino IDE, not Processing IDE.
Try the arduino Forum instead, since your problem is related to arduino code.
Here is the link to it:
https://forum.arduino.cc/

Best regards

2 Likes

Hello,

The code you provided looks like this example:
Arduino Timer Interrupts : 6 Steps (with Pictures) - Instructables

This is NOT correct for 1Hz:
Timer_count = (16*10^6) / (Sfreq*1024) - 1; // ^ is a Bitwise exclusive OR

This is correct for 1Hz:
Timer_count = (16*1000000) / (Sfreq*1024) - 1;

Reference:
Summary of Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)

3 Likes