Question re: Serial comm & Interrupts

Hello, everyone. I'm new here, working on my first real Arduino project. While I was thinking the details through, I can up with a question...

Part of what I want the Arduino to do is measure some values from a couple sensors and send it up to a computer using serial IO. I also want to attach an interrupt or two to "listen" for changes from say an IR remote control or something.

Lets say that the code starts executing a serial.println("Test data") call to send back some data, but in the middle of doing so, I hit a button on the remote. Will the serial data finish printing, or will it print "Test", execute the interrupt code, and then finish up with " data"? Basically, I want to know if println is "atomic," if that makes any sense at all... I looked in the reference section but did not see anything specific there.

FYI, I'm planning on just sending back very short strings of data to the computer, something like "T78.12" for temperature, etc.

Hi Matt--

println is not atomic by any mean. If you are sending lots of data across the serial port, it is very likely that your sends will be interrupted by incoming data. However, given that the serial port buffers the received data, this is not likely to cause any inconvenience to you. You probably won't even notice.

Mikal

Hi Mikal, thanks for the reply.

What if I wanted to write data to serial from the interrupt as well? I'm guessing I could get collisions. I'm not actually sure I really need to do that, but its sortof a thought-experiment at this point...

I think everything should be okay for my project though. I'll be sure to update if I run into any snags. Thanks again.

Matt, if you did any serial writing directly from within an interrupt handler, then yes, you would risk losing incoming data. A better strategy would be to do all the lengthy work in the loop (i.e. non-interrupt code), something like this:

byte process_data = 0;
void interrupt_handler()
{
  process_data++;
}

void loop()
{
  if (process_data > 0)
  {
    --process_data;
    read_incoming_data();
    send_outgoing_data();
  }
}

Mikal

Genius!!!

That's really simple - awesome! i should have thought of that. I normally program in higher level languages on PCs, so I guess i just need to get used to using simple solutions here.

Thanks again. That really helped.