-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathmcp3008.py
More file actions
72 lines (61 loc) · 1.94 KB
/
Copy pathmcp3008.py
File metadata and controls
72 lines (61 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Object interface for MCP3008 A/D converter using bit-banged SPI
"""
import time
import atexit
import RPi.GPIO as GPIO
# make sure GPIO.cleanup will be called when script exits
atexit.register(GPIO.cleanup)
class Mcp3008(object):
def __init__(self, spi_clock, spi_miso, spi_mosi, spi_cs):
self.clock = spi_clock
self.miso = spi_miso
self.mosi = spi_mosi
self.cs = spi_cs
GPIO.setmode(GPIO.BCM)
for port in [self.clock, self.mosi, self.cs]:
GPIO.setup(port, GPIO.OUT)
GPIO.setup(self.miso, GPIO.IN)
def read(self, channel):
assert 0 <= channel <= 7, 'channel must be 0...7'
GPIO.output(self.cs, True)
GPIO.output(self.clock, False)
GPIO.output(self.cs, False)
cmd = channel
cmd |= 0x18 # start bit + "single-ended" config bit
cmd <<= 3 # discard 3 bits; we need just 5
for i in range(5):
GPIO.output(self.mosi, cmd & 0x80)
cmd <<= 1
GPIO.output(self.clock, True)
GPIO.output(self.clock, False)
res = 0
# read null bit plus 10 bits for ADC value
for i in range(11):
GPIO.output(self.clock, True)
GPIO.output(self.clock, False)
res <<= 1
if (GPIO.input(self.miso)):
res |= 0x1
GPIO.output(self.cs, True)
return res
def test():
# select pins for SPI
SPI_CLK = 18
SPI_MISO = 23
SPI_MOSI = 24
SPI_CS = 25
ad_chip = Mcp3008(SPI_CLK, SPI_MISO, SPI_MOSI, SPI_CS)
count = 0
display = '{0:6d} {1:010b} {1:4} {2:3.2f} V {3}'
while True:
res = ad_chip.read(1)
volts = float(res) / 1023 * 3.3
ticks = int(round(float(res) / 1023 * 40)) * '='
print(display.format(count, res, volts, ticks))
time.sleep(.2)
count += 1
if __name__ == '__main__':
test()