PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 line
1.9KB

  1. // -------------------------------------------------------------------------------------------
  2. // Basic Slave
  3. // -------------------------------------------------------------------------------------------
  4. //
  5. // This creates a simple I2C Slave device which will print whatever text string is sent to it.
  6. // It will retain the text string in memory and will send it back to a Master device if
  7. // requested. It is intended to pair with a Master device running the basic_master sketch.
  8. //
  9. // This example code is in the public domain.
  10. //
  11. // -------------------------------------------------------------------------------------------
  12. #include <i2c_t3.h>
  13. // Function prototypes
  14. void receiveEvent(size_t count);
  15. void requestEvent(void);
  16. // Memory
  17. #define MEM_LEN 256
  18. char databuf[MEM_LEN];
  19. volatile uint8_t received;
  20. //
  21. // Setup
  22. //
  23. void setup()
  24. {
  25. pinMode(LED_BUILTIN,OUTPUT); // LED
  26. // Setup for Slave mode, address 0x66, pins 18/19, external pullups, 400kHz
  27. Wire.begin(I2C_SLAVE, 0x66, I2C_PINS_18_19, I2C_PULLUP_EXT, 400000);
  28. // Data init
  29. received = 0;
  30. memset(databuf, 0, sizeof(databuf));
  31. // register events
  32. Wire.onReceive(receiveEvent);
  33. Wire.onRequest(requestEvent);
  34. Serial.begin(115200);
  35. }
  36. void loop()
  37. {
  38. // print received data - this is done in main loop to keep time spent in I2C ISR to minimum
  39. if(received)
  40. {
  41. digitalWrite(LED_BUILTIN,HIGH);
  42. Serial.printf("Slave received: '%s'\n", databuf);
  43. received = 0;
  44. digitalWrite(LED_BUILTIN,LOW);
  45. }
  46. }
  47. //
  48. // handle Rx Event (incoming I2C data)
  49. //
  50. void receiveEvent(size_t count)
  51. {
  52. Wire.read(databuf, count); // copy Rx data to databuf
  53. received = count; // set received flag to count, this triggers print in main loop
  54. }
  55. //
  56. // handle Tx Event (outgoing I2C data)
  57. //
  58. void requestEvent(void)
  59. {
  60. Wire.write(databuf, MEM_LEN); // fill Tx buffer (send full mem)
  61. }