0

I am very new to Arduino programming and I am just trying to count with a frequency of 4000Hz and send the count over serial. Here's the code:

int counter = 0;

void setup() {
  Serial.begin(115200);
  Serial.println('UP IN HERE');
  // put your setup code here, to run once:
  noInterrupts();
  //set timer1 interrupt at 4000Hz
  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 4000hz increments
  OCR1A = 3999;
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS10 bit for no prescaling
  TCCR1B |= (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  interrupts();
}


ISR(Timer1_COMPA_vect){
  counter = counter + 1;
  Serial.println(counter);
}


void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(counter);
}

The main loop never executes so I don't receive anything over the serial port. However, if I comment out the line:

TIMSK1 |= (1 << OCIE1A);

The main loop starts and I receive 0's over serial.

user3446746
  • 141
  • 1
  • 12
  • I tried to fix it, but did not succeed. Just a couple of thoughts. 1) `'UP IN HERE'` is wrong; it should be `"UP IN HERE"`. 2) DON'T perform tasks that are potentially slow (i.e. `Serial.println(counter);`) in an ISR; it can hang your code. 3) 3999 for OCR1A sounds a bit odd to me: how did you calculate it? 4) try looking at [this answer](http://stackoverflow.com/questions/28880226/timer1-arduino-makes-serial-not-work/28887781#28887781) and check if you did everything correctly – frarugi87 May 09 '16 at 09:02
  • Thank you very much. I figured out what I did wrong. I am accessing counter from the main loop and the interrupt which causes a runtime error. I by the way calculated 3999 by dividing 16000000 by 4000 and subtracting 1. – user3446746 May 09 '16 at 18:22
  • Ok ;) than that was a unique case ;) Anyway, as for your problem, if that is the main problem try declaring the variable as `int volatile counter = 0` and check if it fixes it.. – frarugi87 May 10 '16 at 08:57

0 Answers0