본문 바로가기
임베디드/RaspberryPi

cds

by sj0020 2020. 10. 30.

# readadc.py
import spidev, time


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


if __name__ == "__main__":
    spi = spidev.SpiDev()
    spi.open(0, 0)
    spi.max_speed_hz = 1000000

    try:
        while True:
            reading = analog_read(0)
            voltage = reading * 3.3 / 1024
            print("읽은 값은 %s(%d) 전압은 %.3fV" % (hex(reading), reading, voltage))
            time.sleep(1)
    except KeyboardInterrupt:
        print("spi close")
        spi.close()