LoginSignup
23
25

More than 5 years have passed since last update.

WiringPi-Python を使って SPI 通信

Last updated at Posted at 2015-09-27

Raspberry PiにA/DコンバータMCP3002をつなぐ」でRaspberry Pi2にMCP3002 ADCを接続し、SPI経由でアナログセンサー値を読みだせるようにした。pythonからSPI通信を行うために py-spidev を使ったが、WiringPi v2python wrapper を使ってもSPIの制御が可能なので、ここではWiringPi2 pythonを使ってSPI経由でアナログセンサーを読みだしてみる。

実験用回路

  • Raspberry Pi2の SPI0.0 に MCP3002 をつなぎ、MCP3002 の channel 0 に圧力センサー FSR400 を接続する。
  • GPIO 25 に LED をつなぐ。

FSR_prototype2_ブレッドボード.png

FSR_prototype2_回路図.png

WiringPi を使った SPI / GPIO 制御

MCP3002 から圧力センサーの値を読み出し、THRESHOLD 値を超える値が観測されたら LED を点滅させるプログラムを python で実装する。

SPI Library を使って読みだす

MCP3002のデータシートにしたがって、0x68,0x00の2バイトを送信すると、CH0に接続したセンサー値2バイト(有効なのは下位10ビット)が返ってくる。0x68の代わりに0x78とすれば CH1 に接続したセンサー値が得られる。

read_adc_wp2.py
#!/usr/bin/env python3

import wiringpi2 as wp
import time

# SPI channel (0 or 1)
SPI_CH = 0

# SPI speed (hz)
SPI_SPEED = 1000000

# GPIO number
LED_PIN = 25

# threshold
THRESHOLD = 200

# setup
wp.wiringPiSPISetup (SPI_CH, SPI_SPEED)
wp.wiringPiSetupGpio()
wp.pinMode(LED_PIN, wp.GPIO.OUTPUT)

while True:
    buffer = 0x6800
    buffer = buffer.to_bytes(2,byteorder='big')
    wp.wiringPiSPIDataRW(SPI_CH, buffer)
    value = (buffer[0]*256+buffer[1]) & 0x3ff
    print (value)

    if value > THRESHOLD:
      wp.digitalWrite(LED_PIN, wp.GPIO.HIGH)
      time.sleep(0.2)
      wp.digitalWrite(LED_PIN, wp.GPIO.LOW)
      time.sleep(0.2)

    time.sleep(1)

MCP3002 Extension を使う

WiringPi2 には MCP3002 の extension があるので、これを使えば、SPI通信を意識することなくアナログセンサーの値を読み出すことができる(PIN_BASE が CH0, PIN_BASE + 1 が CH1)。

read_mcp3002.py
#!/usr/bin/env python3
###
### read MCP3002 ADC analog value via RasPi SPI
###

import wiringpi2 as wp
import time

# SPI channle (0 or 1)
SPI_CH = 0

# pin base (above 64)
PIN_BASE=70

# GPIO number
LED_PIN = 25

# threshold
THRESHOLD = 200

# setup
wp.mcp3002Setup (PIN_BASE, SPI_CH)
wp.wiringPiSetupGpio()
wp.pinMode(LED_PIN, wp.GPIO.OUTPUT)

# if a sensor value is over THRESHOLD,
# flash led.
while True:
    value = wp.analogRead(PIN_BASE)
    print (value)

    if value > THRESHOLD:
      wp.digitalWrite(LED_PIN, wp.GPIO.HIGH)
      time.sleep(0.2)
      wp.digitalWrite(LED_PIN, wp.GPIO.LOW)
      time.sleep(0.2)

    time.sleep(1)

実行

実行の様子

References

23
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
25