I've just been looking at IC2 (TWI) communications and the simple example sketches for the wire library. In their example "slave_sender" sketch, the function linked to the onRequest event only sends the constant string "HELLO ". So not much that can go wrong there.
When I thought about creating more realistic examples however, it soon struck me that things probably aren't so straight forward when the data to be sent is regularly getting updated in the main loop?
Given that updating even a simple integer (int) is usually not an atomic operation, it seems like there's lots of opportunity for sending corrupted data if no precautions are taken.
So what I'm wondering is, what's the best way to handle the situation when the data that you want to send is getting updated in the main loop asynchronous to the onRequest events?
Just to make it clear, in psuedo code, this is the type of situation I'm talking about.
requestEvent is called from an ISR, and interrupts are already disabled.
However, the interrupt could happen between one byte of a multi-byte variable being changed and the next. To prevent that, you would need to disable interrupts, change the multi-byte variable's value, and then enable interrupts. Google "critical section".
Yes Paul, that was exactly the type of thing of was worried about.
From the number of responses it looks like this is not something that a lot of people have really considerd. So now I'm wondering if I'm worrying about nothing, like is this really a critical code section after all, or is it implemented in some other way?
Like most Arduino functions, the official documentation doesn't tell us much detail. Wire - Arduino Reference
All I really know is that I put my handler code there and it gets called "by magic" each time the master device requests it. So I really just assumed that it must be interrupt driven. But honestly I know nothing about the nuts and bolts of its actual implementation.
The problem is that I'm a worrier, so when things happen by magic, and I don't know what is going on behind the scenes, then it worries me. So perhaps I'm just imagining unnecessary problems. Perhaps the arduino system receives an interrupt for the data request and just sets a flag to tell it to call my onRequest routine at the end of the next loop. I really don't know?
If someone does know the exact details of how this works it would be really good to know. For now however, I think I'll just play it safe and assume that it (the handler) can get called at absolutely any point from within my main loop.