PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

3 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /*
  2. twi.c - TWI/I2C library for Wiring & Arduino
  3. Copyright (c) 2006 Nicholas Zambetti. All right reserved.
  4. This library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. This library 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 GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with this library; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  15. Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts
  16. */
  17. #if defined(__AVR__)
  18. #include <math.h>
  19. #include <stdlib.h>
  20. #include <inttypes.h>
  21. #include <avr/io.h>
  22. #include <avr/interrupt.h>
  23. #include <compat/twi.h>
  24. #include "Arduino.h" // for digitalWrite
  25. #ifndef cbi
  26. #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
  27. #endif
  28. #ifndef sbi
  29. #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
  30. #endif
  31. #include "pins_arduino.h"
  32. #include "twi.h"
  33. static volatile uint8_t twi_state;
  34. static volatile uint8_t twi_slarw;
  35. static volatile uint8_t twi_sendStop; // should the transaction end with a stop
  36. static volatile uint8_t twi_inRepStart; // in the middle of a repeated start
  37. static void (*twi_onSlaveTransmit)(void);
  38. static void (*twi_onSlaveReceive)(uint8_t*, int);
  39. static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
  40. static volatile uint8_t twi_masterBufferIndex;
  41. static volatile uint8_t twi_masterBufferLength;
  42. static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
  43. static volatile uint8_t twi_txBufferIndex;
  44. static volatile uint8_t twi_txBufferLength;
  45. static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
  46. static volatile uint8_t twi_rxBufferIndex;
  47. static volatile uint8_t twi_error;
  48. /*
  49. * Function twi_init
  50. * Desc readys twi pins and sets twi bitrate
  51. * Input none
  52. * Output none
  53. */
  54. void twi_init(void)
  55. {
  56. // initialize state
  57. twi_state = TWI_READY;
  58. twi_sendStop = true; // default value
  59. twi_inRepStart = false;
  60. // activate internal pullups for twi.
  61. digitalWrite(SDA, 1);
  62. digitalWrite(SCL, 1);
  63. // initialize twi prescaler and bit rate
  64. cbi(TWSR, TWPS0);
  65. cbi(TWSR, TWPS1);
  66. TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;
  67. /* twi bit rate formula from atmega128 manual pg 204
  68. SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
  69. note: TWBR should be 10 or higher for master mode
  70. It is 72 for a 16mhz Wiring board with 100kHz TWI */
  71. // enable twi module, acks, and twi interrupt
  72. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
  73. }
  74. /*
  75. * Function twi_slaveInit
  76. * Desc sets slave address and enables interrupt
  77. * Input none
  78. * Output none
  79. */
  80. void twi_setAddress(uint8_t address)
  81. {
  82. // set twi slave address (skip over TWGCE bit)
  83. TWAR = address << 1;
  84. }
  85. /*
  86. * Function twi_readFrom
  87. * Desc attempts to become twi bus master and read a
  88. * series of bytes from a device on the bus
  89. * Input address: 7bit i2c device address
  90. * data: pointer to byte array
  91. * length: number of bytes to read into array
  92. * sendStop: Boolean indicating whether to send a stop at the end
  93. * Output number of bytes read
  94. */
  95. uint8_t twi_readFrom(uint8_t address, uint8_t* data, uint8_t length, uint8_t sendStop)
  96. {
  97. uint8_t i;
  98. // ensure data will fit into buffer
  99. if(TWI_BUFFER_LENGTH < length){
  100. return 0;
  101. }
  102. // wait until twi is ready, become master receiver
  103. while(TWI_READY != twi_state){
  104. continue;
  105. }
  106. twi_state = TWI_MRX;
  107. twi_sendStop = sendStop;
  108. // reset error state (0xFF.. no error occured)
  109. twi_error = 0xFF;
  110. // initialize buffer iteration vars
  111. twi_masterBufferIndex = 0;
  112. twi_masterBufferLength = length-1; // This is not intuitive, read on...
  113. // On receive, the previously configured ACK/NACK setting is transmitted in
  114. // response to the received byte before the interrupt is signalled.
  115. // Therefor we must actually set NACK when the _next_ to last byte is
  116. // received, causing that NACK to be sent in response to receiving the last
  117. // expected byte of data.
  118. // build sla+w, slave device address + w bit
  119. twi_slarw = TW_READ;
  120. twi_slarw |= address << 1;
  121. if (true == twi_inRepStart) {
  122. // if we're in the repeated start state, then we've already sent the start,
  123. // (@@@ we hope), and the TWI statemachine is just waiting for the address byte.
  124. // We need to remove ourselves from the repeated start state before we enable interrupts,
  125. // since the ISR is ASYNC, and we could get confused if we hit the ISR before cleaning
  126. // up. Also, don't enable the START interrupt. There may be one pending from the
  127. // repeated start that we sent outselves, and that would really confuse things.
  128. twi_inRepStart = false; // remember, we're dealing with an ASYNC ISR
  129. TWDR = twi_slarw;
  130. TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE); // enable INTs, but not START
  131. }
  132. else
  133. // send start condition
  134. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
  135. // wait for read operation to complete
  136. while(TWI_MRX == twi_state){
  137. continue;
  138. }
  139. if (twi_masterBufferIndex < length)
  140. length = twi_masterBufferIndex;
  141. // copy twi buffer to data
  142. for(i = 0; i < length; ++i){
  143. data[i] = twi_masterBuffer[i];
  144. }
  145. return length;
  146. }
  147. /*
  148. * Function twi_writeTo
  149. * Desc attempts to become twi bus master and write a
  150. * series of bytes to a device on the bus
  151. * Input address: 7bit i2c device address
  152. * data: pointer to byte array
  153. * length: number of bytes in array
  154. * wait: boolean indicating to wait for write or not
  155. * sendStop: boolean indicating whether or not to send a stop at the end
  156. * Output 0 .. success
  157. * 1 .. length to long for buffer
  158. * 2 .. address send, NACK received
  159. * 3 .. data send, NACK received
  160. * 4 .. other twi error (lost bus arbitration, bus error, ..)
  161. */
  162. uint8_t twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait, uint8_t sendStop)
  163. {
  164. uint8_t i;
  165. // ensure data will fit into buffer
  166. if(TWI_BUFFER_LENGTH < length){
  167. return 1;
  168. }
  169. // wait until twi is ready, become master transmitter
  170. while(TWI_READY != twi_state){
  171. continue;
  172. }
  173. twi_state = TWI_MTX;
  174. twi_sendStop = sendStop;
  175. // reset error state (0xFF.. no error occured)
  176. twi_error = 0xFF;
  177. // initialize buffer iteration vars
  178. twi_masterBufferIndex = 0;
  179. twi_masterBufferLength = length;
  180. // copy data to twi buffer
  181. for(i = 0; i < length; ++i){
  182. twi_masterBuffer[i] = data[i];
  183. }
  184. // build sla+w, slave device address + w bit
  185. twi_slarw = TW_WRITE;
  186. twi_slarw |= address << 1;
  187. // if we're in a repeated start, then we've already sent the START
  188. // in the ISR. Don't do it again.
  189. //
  190. if (true == twi_inRepStart) {
  191. // if we're in the repeated start state, then we've already sent the start,
  192. // (@@@ we hope), and the TWI statemachine is just waiting for the address byte.
  193. // We need to remove ourselves from the repeated start state before we enable interrupts,
  194. // since the ISR is ASYNC, and we could get confused if we hit the ISR before cleaning
  195. // up. Also, don't enable the START interrupt. There may be one pending from the
  196. // repeated start that we sent outselves, and that would really confuse things.
  197. twi_inRepStart = false; // remember, we're dealing with an ASYNC ISR
  198. TWDR = twi_slarw;
  199. TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE); // enable INTs, but not START
  200. }
  201. else
  202. // send start condition
  203. TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE) | _BV(TWSTA); // enable INTs
  204. // wait for write operation to complete
  205. while(wait && (TWI_MTX == twi_state)){
  206. continue;
  207. }
  208. if (twi_error == 0xFF)
  209. return 0; // success
  210. else if (twi_error == TW_MT_SLA_NACK)
  211. return 2; // error: address send, nack received
  212. else if (twi_error == TW_MT_DATA_NACK)
  213. return 3; // error: data send, nack received
  214. else
  215. return 4; // other twi error
  216. }
  217. /*
  218. * Function twi_transmit
  219. * Desc fills slave tx buffer with data
  220. * must be called in slave tx event callback
  221. * Input data: pointer to byte array
  222. * length: number of bytes in array
  223. * Output 1 length too long for buffer
  224. * 2 not slave transmitter
  225. * 0 ok
  226. */
  227. uint8_t twi_transmit(const uint8_t* data, uint8_t length)
  228. {
  229. uint8_t i;
  230. // ensure data will fit into buffer
  231. if(TWI_BUFFER_LENGTH < length){
  232. return 1;
  233. }
  234. // ensure we are currently a slave transmitter
  235. if(TWI_STX != twi_state){
  236. return 2;
  237. }
  238. // set length and copy data into tx buffer
  239. twi_txBufferLength = length;
  240. for(i = 0; i < length; ++i){
  241. twi_txBuffer[i] = data[i];
  242. }
  243. return 0;
  244. }
  245. /*
  246. * Function twi_attachSlaveRxEvent
  247. * Desc sets function called before a slave read operation
  248. * Input function: callback function to use
  249. * Output none
  250. */
  251. void twi_attachSlaveRxEvent( void (*function)(uint8_t*, int) )
  252. {
  253. twi_onSlaveReceive = function;
  254. }
  255. /*
  256. * Function twi_attachSlaveTxEvent
  257. * Desc sets function called before a slave write operation
  258. * Input function: callback function to use
  259. * Output none
  260. */
  261. void twi_attachSlaveTxEvent( void (*function)(void) )
  262. {
  263. twi_onSlaveTransmit = function;
  264. }
  265. /*
  266. * Function twi_reply
  267. * Desc sends byte or readys receive line
  268. * Input ack: byte indicating to ack or to nack
  269. * Output none
  270. */
  271. void twi_reply(uint8_t ack)
  272. {
  273. // transmit master read ready signal, with or without ack
  274. if(ack){
  275. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
  276. }else{
  277. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
  278. }
  279. }
  280. /*
  281. * Function twi_stop
  282. * Desc relinquishes bus master status
  283. * Input none
  284. * Output none
  285. */
  286. void twi_stop(void)
  287. {
  288. // send stop condition
  289. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);
  290. // wait for stop condition to be exectued on bus
  291. // TWINT is not set after a stop condition!
  292. while(TWCR & _BV(TWSTO)){
  293. continue;
  294. }
  295. // update twi state
  296. twi_state = TWI_READY;
  297. }
  298. /*
  299. * Function twi_releaseBus
  300. * Desc releases bus control
  301. * Input none
  302. * Output none
  303. */
  304. void twi_releaseBus(void)
  305. {
  306. // release bus
  307. TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);
  308. // update twi state
  309. twi_state = TWI_READY;
  310. }
  311. SIGNAL(TWI_vect)
  312. {
  313. switch(TW_STATUS){
  314. // All Master
  315. case TW_START: // sent start condition
  316. case TW_REP_START: // sent repeated start condition
  317. // copy device address and r/w bit to output register and ack
  318. TWDR = twi_slarw;
  319. twi_reply(1);
  320. break;
  321. // Master Transmitter
  322. case TW_MT_SLA_ACK: // slave receiver acked address
  323. case TW_MT_DATA_ACK: // slave receiver acked data
  324. // if there is data to send, send it, otherwise stop
  325. if(twi_masterBufferIndex < twi_masterBufferLength){
  326. // copy data to output register and ack
  327. TWDR = twi_masterBuffer[twi_masterBufferIndex++];
  328. twi_reply(1);
  329. }else{
  330. if (twi_sendStop)
  331. twi_stop();
  332. else {
  333. twi_inRepStart = true; // we're gonna send the START
  334. // don't enable the interrupt. We'll generate the start, but we
  335. // avoid handling the interrupt until we're in the next transaction,
  336. // at the point where we would normally issue the start.
  337. TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;
  338. twi_state = TWI_READY;
  339. }
  340. }
  341. break;
  342. case TW_MT_SLA_NACK: // address sent, nack received
  343. twi_error = TW_MT_SLA_NACK;
  344. twi_stop();
  345. break;
  346. case TW_MT_DATA_NACK: // data sent, nack received
  347. twi_error = TW_MT_DATA_NACK;
  348. twi_stop();
  349. break;
  350. case TW_MT_ARB_LOST: // lost bus arbitration
  351. twi_error = TW_MT_ARB_LOST;
  352. twi_releaseBus();
  353. break;
  354. // Master Receiver
  355. case TW_MR_DATA_ACK: // data received, ack sent
  356. // put byte into buffer
  357. twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
  358. case TW_MR_SLA_ACK: // address sent, ack received
  359. // ack if more bytes are expected, otherwise nack
  360. if(twi_masterBufferIndex < twi_masterBufferLength){
  361. twi_reply(1);
  362. }else{
  363. twi_reply(0);
  364. }
  365. break;
  366. case TW_MR_DATA_NACK: // data received, nack sent
  367. // put final byte into buffer
  368. twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
  369. if (twi_sendStop)
  370. twi_stop();
  371. else {
  372. twi_inRepStart = true; // we're gonna send the START
  373. // don't enable the interrupt. We'll generate the start, but we
  374. // avoid handling the interrupt until we're in the next transaction,
  375. // at the point where we would normally issue the start.
  376. TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;
  377. twi_state = TWI_READY;
  378. }
  379. break;
  380. case TW_MR_SLA_NACK: // address sent, nack received
  381. twi_stop();
  382. break;
  383. // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case
  384. // Slave Receiver
  385. case TW_SR_SLA_ACK: // addressed, returned ack
  386. case TW_SR_GCALL_ACK: // addressed generally, returned ack
  387. case TW_SR_ARB_LOST_SLA_ACK: // lost arbitration, returned ack
  388. case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack
  389. // enter slave receiver mode
  390. twi_state = TWI_SRX;
  391. // indicate that rx buffer can be overwritten and ack
  392. twi_rxBufferIndex = 0;
  393. twi_reply(1);
  394. break;
  395. case TW_SR_DATA_ACK: // data received, returned ack
  396. case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack
  397. // if there is still room in the rx buffer
  398. if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){
  399. // put byte in buffer and ack
  400. twi_rxBuffer[twi_rxBufferIndex++] = TWDR;
  401. twi_reply(1);
  402. }else{
  403. // otherwise nack
  404. twi_reply(0);
  405. }
  406. break;
  407. case TW_SR_STOP: // stop or repeated start condition received
  408. // put a null char after data if there's room
  409. if(twi_rxBufferIndex < TWI_BUFFER_LENGTH){
  410. twi_rxBuffer[twi_rxBufferIndex] = '\0';
  411. }
  412. // sends ack and stops interface for clock stretching
  413. //twi_stop(); // Arduino issue #66
  414. // callback to user defined callback
  415. twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex);
  416. // since we submit rx buffer to "wire" library, we can reset it
  417. twi_rxBufferIndex = 0;
  418. // ack future responses and leave slave receiver state
  419. twi_releaseBus();
  420. break;
  421. case TW_SR_DATA_NACK: // data received, returned nack
  422. case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack
  423. // nack back at master
  424. twi_reply(0);
  425. break;
  426. // Slave Transmitter
  427. case TW_ST_SLA_ACK: // addressed, returned ack
  428. case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
  429. // enter slave transmitter mode
  430. twi_state = TWI_STX;
  431. // ready the tx buffer index for iteration
  432. twi_txBufferIndex = 0;
  433. // set tx buffer length to be zero, to verify if user changes it
  434. twi_txBufferLength = 0;
  435. // request for txBuffer to be filled and length to be set
  436. // note: user must call twi_transmit(bytes, length) to do this
  437. twi_onSlaveTransmit();
  438. // if they didn't change buffer & length, initialize it
  439. if(0 == twi_txBufferLength){
  440. twi_txBufferLength = 1;
  441. twi_txBuffer[0] = 0x00;
  442. }
  443. // transmit first byte from buffer, fall
  444. case TW_ST_DATA_ACK: // byte sent, ack returned
  445. // copy data to output register
  446. TWDR = twi_txBuffer[twi_txBufferIndex++];
  447. // if there is more to send, ack, otherwise nack
  448. if(twi_txBufferIndex < twi_txBufferLength){
  449. twi_reply(1);
  450. }else{
  451. twi_reply(0);
  452. }
  453. break;
  454. case TW_ST_DATA_NACK: // received nack, we are done
  455. case TW_ST_LAST_DATA: // received ack, but we are done already!
  456. // ack future responses
  457. twi_reply(1);
  458. // leave slave receiver state
  459. twi_state = TWI_READY;
  460. break;
  461. // All
  462. case TW_NO_INFO: // no state information
  463. break;
  464. case TW_BUS_ERROR: // bus error, illegal stop/start
  465. twi_error = TW_BUS_ERROR;
  466. twi_stop();
  467. break;
  468. }
  469. }
  470. #endif // __AVR__