forked from valtsu23/DIY-Emu-Black-Dash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmcp3002.py
32 lines (26 loc) · 759 Bytes
/
mcp3002.py
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
import spidev
# Enable SPI0.1 for adc
spi = spidev.SpiDev(0, 0)
spi.max_speed_hz = 1200000
# Adc_ch 0/1
def read_adc(adc_ch):
# Construct SPI message
# First bit (Start): Logic high (1)
# Second bit (SGL/DIFF): 1 to select single mode
# Third bit (ODD/SIGN): Select channel (0 or 1)
# Fourth bit (MSFB): 0 for LSB first
# Next 12 bits: 0 (don't care)
msg = 0b11
msg = ((msg << 1) + adc_ch) << 5
msg = [msg, 0b00000000]
reply = spi.xfer2(msg)
# Construct single integer out of the reply (2 bytes)
adc = 0
for n in reply:
adc = (adc << 8) + n
# Last bit (0) is not part of ADC value, shift to remove it
adc = adc >> 1
# Return 0-1023
return adc
def close():
spi.close()