TimerOne and Serial Library

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 one way to block arduino in some block, I try use atomic and didn’t work.

I’m using arduino UNO (ATmega328)

It's possible?

It's entirely possible; you should never use Serial in an interrupted context.

But when I remove:

Serial.println(millis()); from loop

Work well in ISR Routine, I think that the problem is: when ISR Routine try use Serial at the same time of loop()

I think you should never use Serial in an ISR.
YMMV.

I spent a lot of time to discovery.

Just one
Serial.flush();
:confused:

Thanks :smiley:

I don't understand your reply.

Nothing, only the solution, for others

Ah! Playing with us, you are. “Serial.flush” a double-edged light sabre, it is.

FWIW, there is no (one) solution.

When I said

I think you should never use Serial in an ISR.

I chose my words carefully. I didn’t say “One should never use Serial in an ISR”, and I didn’t say “I never use Serial in an ISR”.

I liked of yoda voice

kkkkkkkkkkkkkkkk XD