2
votes

I'm working using TimerOne library, the code is shown below:

#include <TimerOne.h>

void setup() {
    Serial.begin(9600);
    pinMode(13, OUTPUT);    
    Serial.println();
    Timer1.initialize(1000000); // set a timer of length 1000000 microseconds
    Timer1.attachInterrupt(timerIsr); // attach the service routine here
}

void loop() {
    Serial.println(millis());
}

void timerIsr() {
    Serial.print("FROM Time1: ");
    Serial.println(millis());
}

The problem is, after some loops (when millis of loop() returns 930), the arduino stop

I think that the problem is, when the arduino is running the loop, and write in Serial port, the ISR Routine is writing too. How can I solve this problem?

I try change:

Serial.print("FROM Time1: ");
Serial.println(millis());

by:

digitalWrite(13, !digitalRead(13));

And work fine, I think that the Serial library of arduino has some problem when use interrupts, It's possible?

There's any way to block arduino in some block of code, I try use atomic and didn't work.

I'm using Arduino UNO (ATmega328)

2

2 Answers

3
votes

First problem is that your ISR (Interrupt Service Routine), MUST NOT perform any IO. Instead write something, like:

int timedone;

setup() {
   // etc.
   timedone = 0;
}

loop() {
   if (timedone == 1)
   {
    Serial.print("FROM Time1: ");
    Serial.println(millis());
   }
}

void timerISR() {timedone = 1;}

Instead of what you have:

void timerIsr() {
    Serial.print("FROM Time1: ");
    Serial.println(millis());
}

Hope this helps.

0
votes

I spent a lot of time to discovery.

Just

Serial.flush();

:/