Picadae hardware and control code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

twi.c 17KB

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