twi.c 16 KB

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