twi2c.c 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /* Copyright 2018 Jack Humbert
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "twi2c.h"
  17. #include <string.h>
  18. #include <hal.h>
  19. #include "hal_i2cslave.h"
  20. #include "chprintf.h"
  21. #include "memstreams.h"
  22. #include "printf.h"
  23. #include "matrix.h"
  24. #ifndef I2C_DRIVER
  25. #define I2C_DRIVER I2CD1
  26. #endif
  27. /**
  28. * I2C slave test routine.
  29. *
  30. * To use: Add file to a project, call startComms() with the address of a serial stream
  31. *
  32. * There are two different responses:
  33. * a) A read-only transaction - returns the "Initial Reply" message
  34. * b) A write then read transaction - calls a message processor and returns the generated reply.
  35. * Stretches clock until reply available.
  36. */
  37. static const I2CConfig uniI2CConfig = {
  38. STM32_TIMINGR_PRESC(15U) |
  39. STM32_TIMINGR_SCLDEL(4U) | STM32_TIMINGR_SDADEL(2U) |
  40. STM32_TIMINGR_SCLH(15U) | STM32_TIMINGR_SCLL(21U),
  41. 0,
  42. 0,
  43. NULL
  44. };
  45. char initialReplyBody[50] = "Initial reply"; // 'Status' response if read without preceding write
  46. uint32_t messageCounter = 0; /* Counts number of messages received to return as part of response */
  47. uint8_t rxBody[240]; /* stores last message master sent us (intentionally a few bytes smaller than txBody) */
  48. uint8_t txBody[256]; /* Return message buffer for computed replies */
  49. BaseSequentialStream *chp = NULL; // Used for serial logging
  50. // Handler when something sent to us
  51. const I2CSlaveMsg echoRx =
  52. {
  53. sizeof(rxBody), /* max sizeof received msg body */
  54. rxBody, /* body of received msg */
  55. NULL, /* do nothing on address match */
  56. twi2c_slave_message_process, /* Routine to process received messages */
  57. catchError /* Error hook */
  58. };
  59. // 'Empty' reply when nothing to say, and no message received. In RAM, to allow update
  60. I2CSlaveMsg initialReply =
  61. {
  62. sizeof(initialReplyBody), /* trailing zero byte will be repeated as needed */
  63. (uint8_t *)initialReplyBody,
  64. NULL, /* do nothing on address match */
  65. NULL, /* do nothing after reply sent */
  66. catchError /* Error hook */
  67. };
  68. // Response to received messages
  69. I2CSlaveMsg echoReply = { /* this is in RAM so size may be updated */
  70. 0, /* filled in with the length of the message to send */
  71. txBody, /* Response message */
  72. NULL, /* do nothing special on address match */
  73. clearAfterSend, /* Clear receive buffer once replied */
  74. catchError /* Error hook */
  75. };
  76. /**
  77. * Track I2C errors
  78. */
  79. uint8_t gotI2cError = 0;
  80. uint32_t lastI2cErrorFlags = 0;
  81. // Called from ISR to log error
  82. void noteI2cError(uint32_t flags)
  83. {
  84. lastI2cErrorFlags = flags;
  85. gotI2cError = 1;
  86. }
  87. /**
  88. * Generic error handler
  89. *
  90. * Called in interrupt context, so need to watch what we do
  91. */
  92. void catchError(I2CDriver *i2cp)
  93. {
  94. noteI2cError(i2cp->errors);
  95. }
  96. extern void matrix_copy(matrix_row_t * copy);
  97. const char hexString[16] = "0123456789abcdef";
  98. /**
  99. * Message processor - looks at received message, determines reply as quickly as possible
  100. *
  101. * Responds with the value of the messageCounter (in hex), followed by the received message in [..]
  102. *
  103. * Note: Called in interrupt context, so need to be quick!
  104. */
  105. void twi2c_slave_message_process(I2CDriver *i2cp) {
  106. uint8_t *txPtr = txBody;
  107. uint8_t txLen;
  108. size_t len = i2cSlaveBytes(i2cp); // Number of bytes received
  109. if (len >= 2 && rxBody[0] == 0x01 && rxBody[1] == 0x00) {
  110. matrix_row_t matrix[MATRIX_ROWS / 2];
  111. matrix_copy(matrix);
  112. memcpy(txPtr, matrix, MATRIX_ROWS / 2);
  113. txLen = MATRIX_ROWS / 2;
  114. }
  115. echoReply.size = txLen;
  116. i2cSlaveReplyI(i2cp, &echoReply);
  117. }
  118. /**
  119. * Callback after sending of response complete - restores default reply in case polled
  120. */
  121. void clearAfterSend(I2CDriver *i2cp)
  122. {
  123. echoReply.size = 0; // Clear receive message
  124. i2cSlaveReplyI(i2cp, &initialReply);
  125. }
  126. /**
  127. * Start the I2C Slave port to accept comms from master CPU
  128. *
  129. * We then go into a loop checking for errors, and never return
  130. */
  131. void twi2c_slave_init(void) {
  132. palSetGroupMode(GPIOB,8,9, PAL_MODE_INPUT); // Try releasing special pins for a short time
  133. chThdSleepMilliseconds(10);
  134. /* I2C1 SCL on PF1, SDA on PF0 */
  135. palSetPadMode(GPIOB, 9, PAL_MODE_ALTERNATE(4) | PAL_STM32_OTYPE_OPENDRAIN | PAL_STM32_PUPDR_PULLUP);
  136. palSetPadMode(GPIOB, 8, PAL_MODE_ALTERNATE(4) | PAL_STM32_OTYPE_OPENDRAIN | PAL_STM32_PUPDR_PULLUP);
  137. i2cStart(&I2C_DRIVER, &uniI2CConfig);
  138. #if HAL_USE_I2C_SLAVE
  139. I2C_DRIVER.slaveTimeout = MS2ST(100); // Time for complete message
  140. #endif
  141. i2cSlaveConfigure(&I2C_DRIVER, &echoRx, &initialReply);
  142. // Enable match address after everything else set up
  143. i2cMatchAddress(&I2C_DRIVER, slaveI2Caddress/2);
  144. // i2cMatchAddress(&I2C_DRIVER, myOtherI2Caddress/2);
  145. // i2cMatchAddress(&I2C_DRIVER, 0); /* "all call" */
  146. printf("Slave I2C started\n\r");
  147. }
  148. void twi2c_slave_task(void) {
  149. if (gotI2cError) {
  150. gotI2cError = 0;
  151. printf("I2cError: %04x\r\n", lastI2cErrorFlags);
  152. }
  153. }
  154. void twi2c_master_init(void) {
  155. i2cStart(&I2C_DRIVER, &uniI2CConfig);
  156. }
  157. msg_t twi2c_master_send(i2caddr_t address, const uint8_t * txbuf, uint8_t * rxbuf, systime_t timeout) {
  158. return i2cMasterTransmitTimeout(&I2C_DRIVER, address, txbuf, sizeof(txbuf), rxbuf, sizeof(rxbuf), timeout);
  159. }