1

I do not know much electronics.

I have Nano v3 as I2C master, it reads 5-byte packets (of delimtted data) from PC's USB port, processes it and forwards it.

I now need to implement a way to signal PC if something went wrong down the line. I don't want to clutter I2C channel and its just a flag so I think interrupt is best for my purpose.

While writing the ISR function I am not sure if its advisable to write data using Serial, because loop might have read 2-3 bytes of the 5-byte message packet. And I don't know if it will overwrite data coming from PC or what...

What will happen if I Serial.write(0x1) (suddenly, in an ISR function) while loop() was reading data from same Serial?

I don't know how to test this myself.

2

Reading and writing of serial data are separate functions. When you .write() you just append the data to the TX buffer. When you .read() you just take the next character from the RX buffer.

All actual sending and receiving, and filling/emptying of the buffers is done inside the ISRs for the UART module.

That said, you really shouldn't use Serial inside an ISR. This is because the sending and receiving is done by an ISR, and if you are in your ISR then the sending can never happen until you leave your ISR. For the odd occasional byte it's not really a problem, but if the TX buffer fills up Serial.write() will block until the TX ISR has sent some data - which won't happen since your ISR is blocking the TX ISR.

So it's best to avoid any Serial operations inside an ISR. Instead you would normally set flags and values in an ISR then check for those flags in loop() to report anything.

1
  • Roger that. Yeah I am writing just 1 byte and then error handling will take over. I'll mark as answer soon, thanks. – chocolate Apr 12 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.