Skip to content

Instantly share code, notes, and snippets.

@fnishio
Last active September 27, 2015 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fnishio/56401c57dd90d3597536 to your computer and use it in GitHub Desktop.
Save fnishio/56401c57dd90d3597536 to your computer and use it in GitHub Desktop.
read MCP3002 SPI data by python/spidev ref: http://qiita.com/f_nishio/items/4b9723c4e622a51aaeb5
#!/usr/bin/env python
# Read the analog sensor value via MCP3002.
import spidev
import time
import subprocess
# open SPI device 0.0
spi = spidev.SpiDev()
spi.open(0, 0)
try:
while True:
resp = spi.xfer2([0x68, 0x00])
value = (resp[0] * 256 + resp[1]) & 0x3ff
print value
time.sleep(1)
except KeyboardInterrupt:
spi.close()
#!/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)
#!/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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment