twi2c.c 6.6 KB

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