Void loop not executing when using timer interrupt

Hello, first time posting so I apologize if I am doing this incorrectly. I am playing around with interrupts to understand them better but I can't seem to get past this problem. I started off by just implementing a program where the variable "count" is incremented whenever I press a pushbutton that is connected to pin 3 so it goes into an ISR and increments, I was able to do this. Then to explore timer interrupts, I implemented a program that counts how many times it is pressed in 10 seconds. This also worked. But now I want to be able to keep an LED on the while simultaneously having the previous program working. I tried putting it in the void loop it and does not seem to work. Help is very much appreciated.

// This code increments a variable count whenever a push button is pressed using a hardware interrupt 
#include "TimerOne.h"
// Variable declarations
int count = 0; // This variable will hold the number of times the push button was pressed
int pushButton = 3;
float freq;
int ledPin=9;

void counter() {  // This is the interrupt service routine for the push button press
  count++;
 
}

void ISR_timerone()
{

Timer1.detachInterrupt();
Serial.print("Frequency= ");
freq=count/10. ; 
Serial.println(freq);
count=0;
Timer1.attachInterrupt( ISR_timerone );

}

void setup() {
   Timer1.initialize(10000000); 
  attachInterrupt(digitalPinToInterrupt(3), counter, FALLING);  // Changed to RISING edge trigger
  Serial.begin(9600);
  pinMode(pushButton, INPUT_PULLUP);
   Timer1.attachInterrupt( ISR_timerone ); 
}



void loop() {
analogWrite(ledPin,100);
}

Yeah. That's way too much stuff in your interrupt service routine.

A good rule of thumb is that making any function / method calls inside an interrupt service routine is a yellow flag. Serial and Timer1 method calls are a big red flag.

In a youtube tutorial I watched, It was mentioned that the Timer1.detachInterrupt() and Timer1.attachInterrupt(); functions allow to serial.print. I read from a similar post to this to abandon the timer interrupt and use the millis function but I feel like there should be a way to make this work.

Read the documentation for TimerOne library.
https://www.pjrc.com/teensy/td_libs_TimerOne.html

Running TimerOne library will prevent the usage of pwm pins 9 and 10 on the Uno.

There is no need to disconnect and reconnect the interrupt inside of the ISR.

2 Likes

You are a life saver ! thank you

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.