Advertisement
grist

Arduino I2C library test

Feb 11th, 2013
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.80 KB | None | 0 0
  1. /*
  2.  
  3.  
  4. Test harness for playing with I2C.
  5.  
  6.  
  7.  
  8. */
  9.  
  10. #include <I2C.h>
  11.  
  12. #define SLAVE_ADDR         0x01  // This has to match the address assigned to the slave in its code
  13. #define MAX_PACKET_SIZE    16    // max bytes to test sending at a time
  14. #define TEST_TRIES         10    // how many tests to perform for each number of bytes
  15. #define END_MARKER         255
  16.  
  17.  
  18. // Holds the outgoing data
  19. byte data[MAX_PACKET_SIZE];
  20.  
  21. // function prototypes
  22. int fillData(int bytes);
  23.  
  24.  
  25. void setup()
  26. {
  27.     I2c.begin();
  28.     I2c.setSpeed(1); // 0 = 100MHz, 1 = 400MHz
  29.     Serial.begin(9600);
  30. }
  31.  
  32. void loop()
  33. {
  34.     int total;
  35.     int retries = 10;
  36.     unsigned long start_time, trans_time;
  37.     for(int i=0;i<retries;i++) {
  38.         Serial.println("-----------------");
  39.         Serial.println(retries++);
  40.         Serial.println("-----------------");
  41.         for (int bytes=1;bytes<MAX_PACKET_SIZE-1;bytes++) {
  42.  
  43.             total = fillData(bytes);
  44.             start_time = micros();
  45.             sendData(bytes);
  46.             trans_time = micros() - start_time;
  47.             Serial.print("Total: ");
  48.             Serial.println(total);
  49.             Serial.print("Time: ");
  50.             Serial.println(trans_time);
  51.             delay(7000);
  52.         }
  53.     }
  54. }
  55.  
  56.  
  57. int fillData(int bytes)
  58. { // generate some random bytes.
  59.     int total = 0;
  60.     for (int i=0;i<bytes;i++) {
  61.         data[i] = random(256);
  62.         total += data[i];
  63.     }
  64.     return total;
  65. }
  66.  
  67. void sendData(int bytes)
  68. { // send the bytes. Hacking a 0 as the first byte and forcing the
  69.   // END_MARKER in. No error checking seeing we're interested in speed.
  70.  
  71.    data[bytes] = END_MARKER;
  72.    I2c.write((int)SLAVE_ADDR, 0, data, bytes +1);
  73.    Serial.print("Bytes: ");
  74.    Serial.println(bytes + 2); // Includes the start byte and end marker
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement