SHOW:
|
|
- or go back to the newest paste.
| 1 | #include <inttypes.h> | |
| 2 | #include <Wire.h> | |
| 3 | #define BUFFER_SIZE (192) | |
| 4 | - | unsigned char buf[BUFFER_SIZE]; |
| 4 | + | |
| 5 | uint8_t buf1[BUFFER_SIZE]; | |
| 6 | uint8_t buf2[BUFFER_SIZE]; | |
| 7 | ||
| 8 | uint8_t *readBuf = buf1; | |
| 9 | uint8_t *writeBuf = buf2; | |
| 10 | ||
| 11 | volatile bool needsSwap = false; | |
| 12 | volatile uint8_t pos = 0; | |
| 13 | ||
| 14 | void setup() | |
| 15 | - | /* you can access the bytes directly as an array, with the first 96 being buf[0] to buf[95] and second buf[96] to buf[191], or if you need to pass to a function whateverFunction(buf) or with the size whateverFunction(buf, 96); |
| 15 | + | |
| 16 | - | Then the second 96 bytes are passed like this whateverFunction(buf + 96, 96) */ |
| 16 | + | |
| 17 | Wire.onReceive(receiveEvent); // register event | |
| 18 | } | |
| 19 | ||
| 20 | void loop() | |
| 21 | {
| |
| 22 | //Do whatever you need to with buf in here. | |
| 23 | - | // this is blocking, so no other code will run while this is receiving, |
| 23 | + | /* you can access the bytes directly as an array, with the first 96 being readBuf[0] to readBuf[95] and second readBuf[96] to readBuf[191], |
| 24 | - | // this will only work if you send all 192 bytes at once. |
| 24 | + | or if you need to pass to a function whateverFunction(readBuf) or with the size whateverFunction(readBuf, 96); |
| 25 | Then the second 96 bytes are passed like this whateverFunction(readBuf + 96, 96) */ | |
| 26 | ||
| 27 | - | unsigned char i = 0; |
| 27 | + | |
| 28 | - | while(Wire.available() && (i < BUFFER_SIZE)) |
| 28 | + | |
| 29 | //Swap the buffers, | |
| 30 | - | buf[i++] = Wire.read(); // receive byte |
| 30 | + | if(needsSwap){
|
| 31 | //I assume this loop() is fast, so you'll get here before the master does another tranmission? | |
| 32 | uint8_t *temp = writeBuf; | |
| 33 | writeBuf = readBuf; | |
| 34 | readBuf = temp; | |
| 35 | needsSwap = false; | |
| 36 | } | |
| 37 | } | |
| 38 | ||
| 39 | // function that executes whenever data is received from master | |
| 40 | // this function is registered as an event, see setup() | |
| 41 | // this is blocking, so no other code will run while this is receiving | |
| 42 | void receiveEvent(int howMany) | |
| 43 | {
| |
| 44 | while(Wire.available() && (pos < BUFFER_SIZE)) | |
| 45 | {
| |
| 46 | writeBuf[pos++] = Wire.read(); // receive byte | |
| 47 | } | |
| 48 | if(pos == BUFFER_SIZE){
| |
| 49 | pos = 0; | |
| 50 | needsSwap = true; | |
| 51 | } | |
| 52 | } |