mcp3008.py 729 B

12345678910111213141516171819202122232425262728
  1. from spidev import SpiDev
  2. import time
  3. class MCP3008:
  4. def __init__(self, bus = 0, device = 0):
  5. self.bus, self.device = bus, device
  6. self.spi = SpiDev()
  7. self.open()
  8. def open(self):
  9. self.spi.open(self.bus, self.device)
  10. def read(self, channel = 0):
  11. adc = self.spi.xfer2([1, (8 + channel) << 4, 0])
  12. data = ((adc[1] & 3) << 8) + adc[2]
  13. return data
  14. def getVoltage(self, channel):
  15. return self.read(channel) / 1023.0 * 5
  16. def close(self):
  17. self.spi.close()
  18. if __name__ == "__main__":
  19. adc = MCP3008(0,0)
  20. while True:
  21. print('\t'.join(["{}: {:8.3f} V".format(i, adc.getVoltage(i)) for i in range(4)]))
  22. time.sleep(.3)