jacksonliam

Untitled

Dec 21st, 2013
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <inttypes.h>
  2. #include <Wire.h>
  3. #define BUFFER_SIZE (192)
  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. {
  16.   Wire.begin(4);                // join i2c bus with address #4
  17.   Wire.onReceive(receiveEvent); // register event
  18. }
  19.  
  20. void loop()
  21. {
  22.   //Do whatever you need to with buf in here.
  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.  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.   delay(100); //remove this when you have code in this loop
  28.  
  29.   //Swap the buffers,
  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. }
Advertisement
Add Comment
Please, Sign In to add comment