für meine Hausautomatisierung benötige ich jede Menge analoge Eingänge.
Daher habe ich mich mit Analog Digital Wandlern beschäftigt.
Mittels GPIO möchte AD Wandler ansprechen und die 8 Eingänge auslesen.
Nach einigem recherchieren bin ich nun so weit:
Den AD Wandler habe ich wie folgt angeschlossen:
Code: Select all
RaspberryPi MCP3008
Pin 1 (3.3V) Pin 16 (VDD)
Pin 1 (3.3V) Pin 15 (VREF)
Pin 6 (GND) Pin 14 (AGND)
Pin 23 (SCLK) Pin 13 (CLK)
Pin 21 (MISO) Pin 12 (DOUT)
Pin 19 (MOSI) Pin 11 (DIN)
Pin 24 (CE0) Pin 10 (CS/SHDN)
Pin 6 (GND) Pin 9 (DGND)
Code: Select all
sudo raspi-config
Code: Select all
from spidev import SpiDev
class MCP3008:
def __init__(self, bus = 0, device = 0):
self.bus, self.device = bus, device
self.spi = SpiDev()
self.open()
def open(self):
self.spi.open(self.bus, self.device)
def read(self, channel = 0):
adc = self.spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
return data
def close(self):
self.spi.close()
Code: Select all
from MCP3008 import MCP3008
adc = MCP3008()
value = adc.read( channel = 0 ) # Den auszulesenden Channel kannst du natürlich anpassen
print("Anliegende Spannung: %.2f" % (value / 1023.0 * 3.3) )
Code: Select all
Anliegende Spannung: 0.00
Anliegende Spannung: 0.00
Anliegende Spannung: 0.00
Anliegende Spannung: 0.00
Anliegende Spannung: 0.00
Anliegende Spannung: 0.00
Anliegende Spannung: 0.00
Anliegende Spannung: 0.00
Anliegende Spannung: 0.00
Code: Select all
import spidev
import time
import os
import RPi.GPIO as GPIO, time, os
#Setup GPIO
GPIO.setmode(GPIO.BCM)
cs1 = 17
GPIO.setup(cs1, GPIO.OUT)
# Open SPI bus
spi = spidev.SpiDev()
spi.open(0,0)
# Function to read SPI data from MCP3008 chip 1
# Channel must be an integer 0-7
def ReadChip1(channel):
GPIO.output(cs1, False)
adc = spi.xfer([1,(8+channel)<<4,0])
data = ((adc[1]&3) << 8) + adc[2]
return data
# Define sensor channels - ReadChip1
input1 = 0
input2 = 1
input3 = 2
input4 = 3
input5 = 4
input6 = 5
input7 = 6
input8 = 7
while True:
# Read input data each Channel
input1_level = ReadChip1(input1)
input2_level = ReadChip1(input2)
input3_level = ReadChip1(input3)
input4_level = ReadChip1(input4)
input5_level = ReadChip1(input5)
input6_level = ReadChip1(input6)
input7_level = ReadChip1(input7)
input8_level = ReadChip1(input8)
# Print out results
print "--------------------------------------------"
print("input_channel_1: {}".format(input1_level))
print("input_channel_2: {}".format(input2_level))
print("input_channel_3: {}".format(input3_level))
print("input_channel_4: {}".format(input4_level))
print("input_channel_5: {}".format(input5_level))
print("input_channel_6: {}".format(input6_level))
print("input_channel_7: {}".format(input7_level))
print("input_channel_8: {}".format(input8_level))
# print "-----"
time.sleep(0.1)
close()
GPIO.cleanup()
Code: Select all
input_channel_1: 0
input_channel_2: 0
input_channel_3: 0
input_channel_4: 0
input_channel_5: 0
input_channel_6: 0
input_channel_7: 0
input_channel_8: 0