Using a Photocell + MCP3008 + Raspberry Pi + Pi_piper gem

Enabling SPI on the Raspberry Pi

To enable SPI on the Raspberry Pi, at the command-line:

  1. type raspi-config
  2. select 9 Advanced Options, then select A6 SPI
  3. select Yes to enable, then Yes to load the SPI kernel module by default

Connections

rpi connects_to
3.3v MCP3008(VDD); MCP3008(VREF); resistor+photocell(leg2)+MCP3008(CH0)
GROUND MCP3008(AGND); MCP3008(DGND); photocell(leg1)
GPIO18 MCP3008(CLK)
GPIO23 MCP3008(DOUT)
GPIO24 MCP3008(DIN)
GPIO25 MCP3008(CS)

Example

require 'pi_piper'
#port of the Adafruit MCP3008 interface code found @ http://learn.adafruit.com/send-raspberry-pi-data-to-cosm/python-script

def read_adc(adc_pin, clockpin, adc_in, adc_out, cspin)
  cspin.on
  clockpin.off
  cspin.off
  
  command_out = adc_pin
  command_out |= 0x18
  command_out <<= 3

  (0..4).each do
    adc_in.update_value((command_out & 0x80) > 0)
    command_out <<= 1
    clockpin.on
    clockpin.off
  end
  result = 0

  (0..11).each do
    clockpin.on
    clockpin.off
    result <<= 1
    adc_out.read
    if adc_out.on?
      result |= 0x1
    end
  end 

  cspin.on

  result >> 1
end
  
clock = PiPiper::Pin.new :pin => 18, :direction => :out
adc_out = PiPiper::Pin.new :pin => 23
adc_in = PiPiper::Pin.new :pin => 24, :direction => :out
cs = PiPiper::Pin.new :pin => 25, :direction => :out

adc_pin = 0

value = read_adc(adc_pin, clock, adc_in, adc_out, cs)

# raw reading from value when the room light was on
#=> 614

# raw reading from value when the room light was off
#=> 918

The above example results in a raw value which can be used to help indicate the ambient lighting level.

Resources