RaspPi アナログ入力

RasPiにMCP3008とボリューム繋いでアナログ入力テスト。

MCP3008

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#
# MCP3008 にボリュームを繋いでアナログ入力テスト
#
# 参考
# https://www.denshi.club/pc/raspi/5-mcp3208.html

import spidev, time

spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz = 1000000  #転送速度 1MHz

def analog_read(channel):
    adc = spi.xfer2([1,(8+channel)<<4,0])
    data = ((adc[1]& 3) << 8) + adc[2]
    return data

while True:
    for i in range(2):
        reading = analog_read(i)
        voltage = reading * 5 / 1024
        print("ch:", i, "Reading=%d  tViltage=%f" % (reading,  voltage))
        time.sleep(1)