twi2c.c 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 "chprintf.h"
  20. #include "memstreams.h"
  21. #include "printf.h"
  22. #include "matrix.h"
  23. #ifdef I2C_SLAVE_ENABLE
  24. #include "hal_i2cslave.h"
  25. /**
  26. * I2C slave test routine.
  27. *
  28. * To use: Add file to a project, call startComms() with the address of a serial stream
  29. *
  30. * There are two different responses:
  31. * a) A read-only transaction - returns the "Initial Reply" message
  32. * b) A write then read transaction - calls a message processor and returns the generated reply.
  33. * Stretches clock until reply available.
  34. */
  35. // static const I2CConfig masterI2CConfig = {
  36. // 400000
  37. // };
  38. I2CSlaveMsgCB twi2c_slave_message_process, catchError, clearAfterSend;
  39. #endif
  40. static uint8_t twi2c_address;
  41. static const I2CConfig i2cconfig = {
  42. STM32_TIMINGR_PRESC(15U) |
  43. STM32_TIMINGR_SCLDEL(4U) | STM32_TIMINGR_SDADEL(2U) |
  44. STM32_TIMINGR_SCLH(15U) | STM32_TIMINGR_SCLL(21U),
  45. 0,
  46. 0
  47. };
  48. char initialReplyBody[50] = "Initial reply"; // 'Status' response if read without preceding write
  49. uint32_t messageCounter = 0; /* Counts number of messages received to return as part of response */
  50. uint8_t rxBody[2]; /* stores last message master sent us (intentionally a few bytes smaller than txBody) */
  51. uint8_t txBody[MATRIX_ROWS/2]; /* Return message buffer for computed replies */
  52. BaseSequentialStream *chp = NULL; // Used for serial logging
  53. #ifdef I2C_SLAVE_ENABLE
  54. // Handler when something sent to us
  55. const I2CSlaveMsg echoRx =
  56. {
  57. sizeof(rxBody), /* max sizeof received msg body */
  58. rxBody, /* body of received msg */
  59. NULL, /* do nothing on address match */
  60. twi2c_slave_message_process, /* Routine to process received messages */
  61. catchError /* Error hook */
  62. };
  63. // // 'Empty' reply when nothing to say, and no message received. In RAM, to allow update
  64. I2CSlaveMsg initialReply =
  65. {
  66. sizeof(initialReplyBody), /* trailing zero byte will be repeated as needed */
  67. (uint8_t *)initialReplyBody,
  68. NULL, /* do nothing on address match */
  69. NULL, /* do nothing after reply sent */
  70. catchError /* Error hook */
  71. };
  72. // // 'Empty' reply when nothing to say, and no message received. In RAM, to allow update
  73. // I2CSlaveMsg initialReply =
  74. // {
  75. // 0, /* trailing zero byte will be repeated as needed */
  76. // NULL,
  77. // NULL, /* do nothing on address match */
  78. // NULL, /* do nothing after reply sent */
  79. // catchError /* Error hook */
  80. // };
  81. // Response to received messages
  82. I2CSlaveMsg echoReply = { /* this is in RAM so size may be updated */
  83. MATRIX_ROWS / 2, /* filled in with the length of the message to send */
  84. txBody, /* Response message */
  85. NULL, /* do nothing special on address match */
  86. clearAfterSend, /* Clear receive buffer once replied */
  87. catchError /* Error hook */
  88. };
  89. /**
  90. * Track I2C errors
  91. */
  92. uint8_t gotI2cError = 0;
  93. uint32_t lastI2cErrorFlags = 0;
  94. // Called from ISR to log error
  95. void noteI2cError(uint32_t flags)
  96. {
  97. lastI2cErrorFlags = flags;
  98. gotI2cError = 1;
  99. }
  100. /**
  101. * Generic error handler
  102. *
  103. * Called in interrupt context, so need to watch what we do
  104. */
  105. void catchError(I2CDriver *i2cp)
  106. {
  107. noteI2cError(i2cp->errors);
  108. }
  109. extern void matrix_copy(matrix_row_t * copy);
  110. const char hexString[16] = "0123456789abcdef";
  111. /**
  112. * Message processor - looks at received message, determines reply as quickly as possible
  113. *
  114. * Responds with the value of the messageCounter (in hex), followed by the received message in [..]
  115. *
  116. * Note: Called in interrupt context, so need to be quick!
  117. */
  118. void twi2c_slave_message_process(I2CDriver *i2cp) {
  119. // size_t len = i2cSlaveBytes(i2cp); // Number of bytes received
  120. // memset(txBody, 0, MATRIX_ROWS / 2 * sizeof(matrix_row_t));
  121. matrix_copy(txBody);
  122. echoReply.size = MATRIX_ROWS / 2;
  123. i2cSlaveReplyI(i2cp, &echoReply);
  124. }
  125. /**
  126. * Callback after sending of response complete - restores default reply in case polled
  127. */
  128. void clearAfterSend(I2CDriver *i2cp)
  129. {
  130. // echoReply.size = 0; // Clear receive message
  131. // i2cSlaveReplyI(i2cp, &initialReply);
  132. }
  133. /**
  134. * Start the I2C Slave port to accept comms from master CPU
  135. *
  136. * We then go into a loop checking for errors, and never return
  137. */
  138. void twi2c_slave_init(void) {
  139. twi2c_init();
  140. i2cStart(&I2C_DRIVER, &i2cconfig);
  141. #if HAL_USE_I2C_SLAVE
  142. I2C_DRIVER.slaveTimeout = MS2ST(100); // Time for complete message
  143. #endif
  144. // i2cSlaveConfigure(&I2C_DRIVER, &echoRx, &initialReply);
  145. memset(txBody, 0, MATRIX_ROWS / 2 * sizeof(matrix_row_t));
  146. i2cSlaveConfigure(&I2C_DRIVER, &echoRx, &echoReply);
  147. // Enable match address after everything else set up
  148. i2cMatchAddress(&I2C_DRIVER, slaveI2Caddress/2);
  149. // i2cMatchAddress(&I2C_DRIVER, myOtherI2Caddress/2);
  150. // i2cMatchAddress(&I2C_DRIVER, 0); /* "all call" */
  151. printf("Slave I2C started\n\r");
  152. }
  153. void twi2c_slave_task(void) {
  154. if (gotI2cError) {
  155. gotI2cError = 0;
  156. printf("I2cError: %04x\r\n", lastI2cErrorFlags);
  157. }
  158. }
  159. #endif
  160. uint8_t twi2c_start(uint8_t address) {
  161. twi2c_address = address;
  162. i2cStart(&I2C_DRIVER, &i2cconfig);
  163. return 0;
  164. }
  165. void twi2c_init(void) {
  166. palSetGroupMode(GPIOB,6,7, PAL_MODE_INPUT); // Try releasing special pins for a short time
  167. chThdSleepMilliseconds(10);
  168. palSetPadMode(GPIOB, 6, PAL_MODE_ALTERNATE(4) | PAL_STM32_OTYPE_OPENDRAIN | PAL_STM32_PUPDR_PULLUP);
  169. palSetPadMode(GPIOB, 7, PAL_MODE_ALTERNATE(4) | PAL_STM32_OTYPE_OPENDRAIN | PAL_STM32_PUPDR_PULLUP);
  170. // try high drive (from kiibohd)
  171. // I2C_DRIVER.i2c->C2 |= I2Cx_C2_HDRS;
  172. // try glitch fixing (from kiibohd)
  173. // I2C_DRIVER.i2c->FLT = 4;
  174. }
  175. uint8_t twi2c_write(uint8_t data) {
  176. return i2cMasterTransmitTimeout(&I2C_DRIVER, twi2c_address/2, &data, 1, 0, 0, MS2ST(100));
  177. }
  178. uint8_t twi2c_transmit(uint8_t address, uint8_t* data, uint16_t length) {
  179. twi2c_address = address;
  180. i2cStart(&I2C_DRIVER, &i2cconfig);
  181. return i2cMasterTransmitTimeout(&I2C_DRIVER, twi2c_address/2, data, length, 0, 0, MS2ST(100));
  182. }