A knock sensor example using a piezo element + MCP3008 + Raspberry Pi
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 loop do value = read_adc(adc_pin, clock, adc_in, adc_out, cs) puts 'val : ' + value.inspect if value > 5 sleep 0.01 end
Output:
val : 6 val : 38 val : 22 val : 19 val : 32 val : 28 val : 12 val : 36 val : 26 val : 10 val : 6 val : 183 val : 35 val : 67 val : 38 val : 85 val : 29
The above output was created when I tapped my finger close to the piezo element. The harder I tap, the larger the value.
Note: The threshold was set to 5 because the value when idling floated between 0 and 3.