Skip to content

Instantly share code, notes, and snippets.

@yasamoka
Created July 26, 2018 04:03
Show Gist options
  • Save yasamoka/8fe0c81fe65c0404789624a6bd7799c9 to your computer and use it in GitHub Desktop.
Save yasamoka/8fe0c81fe65c0404789624a6bd7799c9 to your computer and use it in GitHub Desktop.
import spidev
# credits to http://raspberry.io/projects/view/reading-from-a-mcp3002-analog-to-digital-converter/
# modified by Ramzi Sabra
class MCP3002:
def __init__(self, device=0):
self.conn = spidev.SpiDev(0, device)
self.conn.max_speed_hz = 1200000 # 1.2 MHz
@staticmethod
def bitstring(n):
s = bin(n)[2:]
return '0'*(8-len(s)) + s
def read(self, channel=0):
cmd = 128
if channel:
cmd += 32
reply_bytes = self.conn.xfer2([cmd, 0])
reply_bitstring = ''.join(MCP3002.bitstring(n) for n in reply_bytes)
reply = reply_bitstring[5:15]
return int(reply, 2) / 2**10
import time
import mcp3002
adc = mcp3002.MCP3002(device=0)
while True:
read_value = adc.read(channel=0)
real_value = 1 - read_value
percentage_value = real_value * 100
print("{:3f}%".format(percentage_value))
time.sleep(0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment