Sensors usually need an analog input port to read their value. To process the values from analog input, Raspberry Pi would need an external Analog to Digital Converter (ADC) chip or interface with Gertboard or Arduino. However, a simple method making use of the capacitor can be used to get the values of a sensor. This is because some sensors such as a photocell, thermistor, and force sensitive resistor, behave like a resistor. If a capacitor is connected to power (3.3V) through “resistor”, it will charge up slowly and we could count how long it takes. This method is not as accurate as an ADC but it is good enough to give 2 distinct state – sensor triggered as on or off. The diagram here gives a better illustration.
So i used a 1uF capacitor and a photocell to test it out. The photocell cell has no polarity so one of its side is connected to 3.3V (Pin1) and the other side is connected to GPIO pin 18 (physical pin 12). However the capacitor has polarity and the side with negative sign (shorter leg) is connected to the ground (pin 6) while the other is connected to GPIO pin 18 too. See diagram below:
This sample code could give some readings from the photocell:
#!/usr/bin/env python import RPi.GPIO as GPIO, time, os DEBUG = 1 GPIO.setmode(GPIO.BCM) def RCtime (RCpin): reading = 0 GPIO.setup(RCpin, GPIO.OUT) GPIO.output(RCpin, GPIO.LOW) time.sleep(0.1) GPIO.setup(RCpin, GPIO.IN) # This takes about 1 millisecond per loop cycle while (GPIO.input(RCpin) == GPIO.LOW): reading += 1 return reading while True: print RCtime(18) # Read RC timing using pin #18
I was able to get some readings from the photocell where the values get larger when i cover my hand over it.
To use this to control a LED, connect a LED to GPIO pin 17 (see diagram above). The code will include the following:
if sensorvalue > 1000: print "switch on light" GPIO.output(11, True) #switch on lightstate ="On" time.sleep(1) else: print "switch off light" GPIO.output(11, False) #switch off lightstate ="Off" time.sleep(1)
Full script here: http://pastebin.com/Asp7Gixa
The following video demonstrate the control.
I have also tried force sensitive resistor (FSR). The connection is as followed:
The reading that it gave:
However it is a bit different because it does not give reading when the sensor is not pressed.
Full script here: http://pastebin.com/RSEJ3Y7y
Unable to terminate the function properly, see forum here. -probably has to do with terminating the while loop.
Unable to display the sensor value on the web, see forum here. – probably can be solved using setInterval but from my past experience it has been causing much problem and increase work load for Raspberry Pi.
The GPIO.BOARD option specifies that you are referring to the pins by the number of the pin the the plug – i.e the numbers printed on the board (e.g. P1).
The GPIO.BCM option means that you are referring to the pins by the “Broadcom SOC channel” number.