twi.c 17 KB

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