Thursday, 12 February 2015

Pi-based Domestic Electricity Monitor - Part 2 - Programming the Light Sensor


It works! Here's the program (see below) running on the Pi:






















This is a very useful link:

http://www.raspberrypi-spy.co.uk/2012/08/reading-analogue-sensors-with-one-gpio-pin/

as is this:

https://learn.adafruit.com/basic-resistor-sensor-reading-on-raspberry-pi/basic-photocell-reading

If you just want the code:

  1. #!/usr/bin/env python
  2.  
  3. # Example for RC timing reading for Raspberry Pi
  4. # Must be used with GPIO 0.3.1a or later - earlier verions
  5. # are not fast enough!
  6.  
  7. import RPi.GPIO as GPIO, time, os
  8.  
  9. DEBUG = 1
  10. GPIO.setmode(GPIO.BCM)
  11.  
  12. def RCtime (RCpin):
  13. reading = 0
  14. GPIO.setup(RCpin, GPIO.OUT)
  15. GPIO.output(RCpin, GPIO.LOW)
  16. time.sleep(0.1)
  17.  
  18. GPIO.setup(RCpin, GPIO.IN)
  19. # This takes about 1 millisecond per loop cycle
  20. while (GPIO.input(RCpin) == GPIO.LOW):
  21. reading += 1
  22. return reading
  23.  
  24. while True:
  25. print RCtime(18) # Read RC timing using pin #1
or

#!/usr/local/bin/python

# Reading an analogue sensor with
# a single GPIO pin

# Author : Matt Hawkins
# Distribution : Raspbian
# Python : 2.7
# GPIO   : RPi.GPIO v3.1.0a

import RPi.GPIO as GPIO, time

# Tell the GPIO library to use
# Broadcom GPIO references
GPIO.setmode(GPIO.BCM)

# Define function to measure charge time
def RCtime (PiPin):
  measurement = 0
  # Discharge capacitor
  GPIO.setup(PiPin, GPIO.OUT)
  GPIO.output(PiPin, GPIO.LOW)
  time.sleep(0.1)

  GPIO.setup(PiPin, GPIO.IN)
  # Count loops until voltage across
  # capacitor reads high on GPIO
  while (GPIO.input(PiPin) == GPIO.LOW):
    measurement += 1

  return measurement

# Main program loop
while True:
  print RCtime(4) # Measure timing using GPIO4

No comments:

Post a Comment