Connect the MCP3002 ADC to the Raspberry Pi2 with "Connect the A / D converter MCP3002 to the Raspberry Pi" so that the analog sensor value can be read via SPI. did. I used py-spidev to perform SPI communication from python, but python wrapper of WiringPi v2 You can also control the SPI using, so here I will use WiringPi2 python to read the analog sensor via SPI.
--Connect the MCP3002 to SPI0.0 on the Raspberry Pi2 and connect the pressure sensor FSR400 to channel 0 on the MCP3002. --Connect the LED to GPIO 25.
Implement a program in python that reads the value of the pressure sensor from the MCP3002 and blinks the LED when a value exceeding the THRESHOLD value is observed.
If you send 2 bytes of 0x68,0x00 according to the MCP3002 data sheet, the sensor value of 2 bytes connected to CH0 (valid is the lower 10 bits) will be returned. If 0x78 is used instead of 0x68, the sensor value connected to CH1 can be obtained.
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)
Since WiringPi2 has an extension of MCP3002, it can be used to read the value of the analog sensor without being aware of SPI communication (PIN_BASE is CH0, PIN_BASE + 1 is 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
Recommended Posts