コンテンツにスキップ

AD コンバータ MCP3002

ピン配置

ピン名 説明
\(\overline{CS}\) Raspberry Pi なら CE0 もしくは CE1 に接続する。
\(CH0\) 1ch 目の入力ピン。
\(CH1\) 2ch 目の入力ピン。
\(V_{SS}\) GND を接続する。
\(V_{DD}\) 3.3V もしくは 5V を接続する。
\(CLK\) Raspberry Pi なら SCLK に接続する。
\(D_{OUT}\) Raspberry Pi なら MISO に接続する。
\(D_{IN}\) Raspberry Pi なら MOSI に接続する。

参考情報

ラズパイでアナログ電圧を扱う (5) MCP3208 のプログラム ① | 電子工作の環境向上

サンプルコード(Raspberry Pi)

1
pip install spidev
 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import time

import spidev


class MCP3002:
    def __init__(self, bus: int, cs: int, max_voltage: int) -> None:
        """コンストラクタ

        Args:
            bus (int): 0を指定する
            cs (int): CE0に接続する場合は0、CE1に接続する場合は1を指定する
            max_voltage (int): MCP3002のVDDに供給する電圧[V]
        """
        self.__spi = spidev.SpiDev()
        self.__bus = bus
        self.__cs = cs
        self.__max_voltage = max_voltage

    def open(self) -> None:
        """SPI通信を開始する
        """
        # busとcsを指定する。csはCE0の場合は0, CE1の場合は1
        self.__spi.open(self.__bus, self.__cs)
        self.__spi.max_speed_hz = 1000000  # 1MHz (指定必須)

    def close(self) -> None:
        """SPI通信を終了する
        """
        self.__spi.close()

    def get_value(self, channel: int) -> int:
        """チャンネルを指定して値を取得する

        Args:
            channel (int): チャンネル

        Raises:
            Exception: _description_

        Returns:
            int: 値
        """
        if channel <= -1 or channel >= 2:
            raise Exception("The channel must be 0 or 1.")
        data = [0x68 | channel << 4, 0]
        response = self.__spi.xfer2(data)
        # ADコンバータは10bit出力だから10bit目まででANDを取っている
        return ((response[0] << 8) + response[1]) & 0x3ff

    def get_voltage(self, channel: int) -> float:
        """チャンネルを指定して電圧値を取得する

        Args:
            channel (int): チャンネル

        Returns:
            float: 電圧値[V]
        """
        return self.get_value(channel) / 0x3ff * self.__max_voltage

    def get_values(self) -> list[int]:
        """値を取得する

        Returns:
            list[int]: チャンネルごとの値
        """
        return [self.get_value(i) for i in range(2)]

    def get_voltages(self) -> list[float]:
        """電圧値を取得する

        Returns:
            list[float]: チャンネルごとの電圧値[V]
        """
        return [self.get_voltage(i) for i in range(2)]


def main() -> None:
    mcp3002 = MCP3002(0, 0, 3.3)
    mcp3002.open()
    try:
        while True:
            voltages = mcp3002.get_voltages()
            print(voltages)
            time.sleep(1)
    except KeyboardInterrupt:
        mcp3002.close()


if __name__ == "__main__":
    main()