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