twi.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. twi.c - Stripped-down TWI/I2C library
  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 "Arduino.h" // for digitalWrite
  19. #include "twi.h"
  20. void twi_init(void)
  21. {
  22. // activate internal pullups for twi.
  23. digitalWrite(SDA, 1);
  24. digitalWrite(SCL, 1);
  25. // initialize twi prescaler and bit rate
  26. TWSR &= ~(_BV(TWPS0) | _BV(TWPS1));
  27. TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;
  28. /* twi bit rate formula from atmega128 manual pg 204
  29. SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
  30. note: TWBR should be 10 or higher for master mode
  31. It is 72 for a 16mhz Wiring board with 100kHz TWI */
  32. }
  33. void twi_disable(void)
  34. {
  35. // deactivate internal pullups for twi.
  36. digitalWrite(SDA, 0);
  37. digitalWrite(SCL, 0);
  38. }
  39. static void twi_wait()
  40. {
  41. while(!(TWCR & _BV(TWINT)));
  42. }
  43. uint8_t twi_rw8(uint8_t address, uint8_t mode, uint8_t* data)
  44. {
  45. // send start condition
  46. TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWSTA);
  47. twi_wait();
  48. if(TW_STATUS != TW_START)
  49. return 1;
  50. // send address
  51. TWDR = mode;
  52. TWDR |= (address << 1);
  53. TWCR = _BV(TWEN) | _BV(TWINT);
  54. twi_wait();
  55. if(mode == TW_WRITE)
  56. {
  57. if(TW_STATUS != TW_MT_SLA_ACK)
  58. return 2;
  59. // send data
  60. TWDR = *data;
  61. TWCR = _BV(TWEN) | _BV(TWINT);
  62. twi_wait();
  63. if(TW_STATUS != TW_MT_DATA_ACK)
  64. return 3;
  65. }
  66. else
  67. {
  68. if(TW_STATUS != TW_MR_SLA_ACK)
  69. return 2;
  70. // receive data
  71. TWCR = _BV(TWEN) | _BV(TWINT);
  72. twi_wait();
  73. // accept ACK or NACK (since only 1 byte is read)
  74. if(!(TW_STATUS & TW_MR_DATA_ACK))
  75. return 3;
  76. *data = TWDR;
  77. }
  78. // send stop
  79. TWCR = _BV(TWEN) | _BV(TWINT) | _BV(TWSTO);
  80. return 0;
  81. }