Adafruit_I2C.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. # -*- coding: utf-8-*-
  2. #
  3. # This file is part of stdd, the simple time display daemon,
  4. # written by Helmut Pozimski <helmut@pozimski.eu>,
  5. # licensed under the 3-clause BSD license
  6. # This file was originally written by Written by Limor Fried, Kevin Townsend
  7. # and Mikey Sklar for Adafruit Industries. BSD license,
  8. # all text above must be included in any redistribution
  9. import smbus
  10. # ===========================================================================
  11. # Adafruit_I2C Class
  12. # ===========================================================================
  13. class Adafruit_I2C:
  14. @staticmethod
  15. def getPiRevision():
  16. "Gets the version number of the Raspberry Pi board"
  17. # Courtesy quick2wire-python-api
  18. # https://github.com/quick2wire/quick2wire-python-api
  19. try:
  20. with open('/proc/cpuinfo', 'r') as f:
  21. for line in f:
  22. if line.startswith('Revision'):
  23. return 1 if line.rstrip()[-1] in ['1', '2'] else 2
  24. except:
  25. return 0
  26. @staticmethod
  27. def getPiI2CBusNumber():
  28. # Gets the I2C bus number /dev/i2c#
  29. return 1 if Adafruit_I2C.getPiRevision() > 1 else 0
  30. def __init__(self, address, busnum=-1, debug=False):
  31. self.address = address
  32. # By default, the correct I2C bus is auto-detected using /proc/cpuinfo
  33. # Alternatively, you can hard-code the bus version below:
  34. # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's)
  35. # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's)
  36. self.bus = smbus.SMBus(
  37. busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber())
  38. self.debug = debug
  39. def reverseByteOrder(self, data):
  40. "Reverses the byte order of an int (16-bit) or long (32-bit) value"
  41. # Courtesy Vishal Sapre
  42. byteCount = len(hex(data)[2:].replace('L', '')[::2])
  43. val = 0
  44. for i in range(byteCount):
  45. val = (val << 8) | (data & 0xff)
  46. data >>= 8
  47. return val
  48. def errMsg(self):
  49. raise Exception("cannot connect to device, check hardware address!")
  50. return -1
  51. def write8(self, reg, value):
  52. "Writes an 8-bit value to the specified register/address"
  53. try:
  54. self.bus.write_byte_data(self.address, reg, value)
  55. if self.debug:
  56. print "I2C: Wrote 0x%02X to register 0x%02X" % (value, reg)
  57. except IOError, err:
  58. return self.errMsg()
  59. def write16(self, reg, value):
  60. "Writes a 16-bit value to the specified register/address pair"
  61. try:
  62. self.bus.write_word_data(self.address, reg, value)
  63. if self.debug:
  64. print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" %
  65. (value, reg, reg+1))
  66. except IOError, err:
  67. return self.errMsg()
  68. def writeList(self, reg, list):
  69. "Writes an array of bytes using I2C format"
  70. try:
  71. if self.debug:
  72. print "I2C: Writing list to register 0x%02X:" % reg
  73. print list
  74. self.bus.write_i2c_block_data(self.address, reg, list)
  75. except IOError, err:
  76. return self.errMsg()
  77. def readList(self, reg, length):
  78. "Read a list of bytes from the I2C device"
  79. try:
  80. results = self.bus.read_i2c_block_data(self.address, reg, length)
  81. if self.debug:
  82. print ("I2C: Device 0x % 02X returned the following from \
  83. reg 0x % 02X" % (self.address, reg))
  84. print results
  85. return results
  86. except IOError, err:
  87. return self.errMsg()
  88. def readU8(self, reg):
  89. "Read an unsigned byte from the I2C device"
  90. try:
  91. result = self.bus.read_byte_data(self.address, reg)
  92. if self.debug:
  93. print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" %
  94. (self.address, result & 0xFF, reg))
  95. return result
  96. except IOError, err:
  97. return self.errMsg()
  98. def readS8(self, reg):
  99. "Reads a signed byte from the I2C device"
  100. try:
  101. result = self.bus.read_byte_data(self.address, reg)
  102. if result > 127: result -= 256
  103. if self.debug:
  104. print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" %
  105. (self.address, result & 0xFF, reg))
  106. return result
  107. except IOError, err:
  108. return self.errMsg()
  109. def readU16(self, reg):
  110. "Reads an unsigned 16-bit value from the I2C device"
  111. try:
  112. hibyte = self.readU8(reg)
  113. lobyte = self.readU8(reg+1)
  114. result = (hibyte << 8) + lobyte
  115. if (self.debug):
  116. print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (
  117. self.address, result & 0xFFFF, reg)
  118. return result
  119. except IOError, err:
  120. return self.errMsg()
  121. def readS16(self, reg):
  122. "Reads a signed 16-bit value from the I2C device"
  123. try:
  124. hibyte = self.readS8(reg)
  125. lobyte = self.readU8(reg+1)
  126. result = (hibyte << 8) + lobyte
  127. if (self.debug):
  128. print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (
  129. self.address, result & 0xFFFF, reg)
  130. return result
  131. except IOError, err:
  132. return self.errMsg()
  133. def readU16Rev(self, reg):
  134. "Reads an unsigned 16-bit value from the I2C device with rev byte ord"
  135. try:
  136. lobyte = self.readU8(reg)
  137. hibyte = self.readU8(reg+1)
  138. result = (hibyte << 8) + lobyte
  139. if (self.debug):
  140. print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (
  141. self.address, result & 0xFFFF, reg)
  142. return result
  143. except IOError, err:
  144. return self.errMsg()
  145. def readS16Rev(self, reg):
  146. "Reads a signed 16-bit value from the I2C device with rev byte order"
  147. try:
  148. lobyte = self.readS8(reg)
  149. hibyte = self.readU8(reg+1)
  150. result = (hibyte << 8) + lobyte
  151. if (self.debug):
  152. print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (
  153. self.address, result & 0xFFFF, reg)
  154. return result
  155. except IOError, err:
  156. return self.errMsg()
  157. if __name__ == '__main__':
  158. try:
  159. bus = Adafruit_I2C(address=0)
  160. print "Default I2C bus is accessible"
  161. except:
  162. print "Error accessing default I2C bus"