dvanhaeke
Posts: 8
Joined: Wed Nov 21, 2012 6:57 pm

Temperature/Light controlled LED

Tue Dec 04, 2012 6:53 pm

Hello everybody !

Until now I've been quite successful following simple tutorials from Youtube and Adafruit, I even successfully have 2-factor authentication (http://www.howtogeek.com/121650/how-to- ... ntication/) on my Pi :-)

Currently I'm logging temperature (measured through the ADC) and illumination values (photocell) to Cosm.com. Now I wanted to combine two tutorials to activate a LED when a certain value is measured (egg. too hot or too dark). I thought this was something that other users might have tried, alas I could not find much information here or on the WWW.

I'm new to python, but I have some experience with Linux and other programming languages.
Here's my code, when ran the script doesn't produce an error. Where is my error, why doesn't the LED activate ?

Code: Select all

#!/usr/bin/env python
import time
import os
import RPi.GPIO as GPIO
import eeml

GPIO.setmode(GPIO.BCM)
DEBUG = 1
LOGGER = 1

# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
        if ((adcnum > 7) or (adcnum < 0)):
                return -1
        GPIO.output(cspin, True)

        GPIO.output(clockpin, False)  # start clock low
        GPIO.output(cspin, False)     # bring CS low

        commandout = adcnum
        commandout |= 0x18  # start bit + single-ended bit
        commandout <<= 3    # we only need to send 5 bits here
        for i in range(5):
                if (commandout & 0x80):
                        GPIO.output(mosipin, True)
                else:   
                        GPIO.output(mosipin, False)
                commandout <<= 1
                GPIO.output(clockpin, True)
                GPIO.output(clockpin, False)

        adcout = 0
        # read in one empty bit, one null bit and 10 ADC bits
        for i in range(12):
                GPIO.output(clockpin, True)
                GPIO.output(clockpin, False)
                adcout <<= 1
                if (GPIO.input(misopin)):
                        adcout |= 0x1

        GPIO.output(cspin, True)

        adcout /= 2       # first bit is 'null' so drop it
        return adcout

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
        
# change these as desired - they're the pins connected from the
# SPI port on the ADC to the Cobbler
SPICLK = 18
SPIMISO = 23
SPIMOSI = 24
SPICS = 25

# set up the SPI interface pins
GPIO.setup(SPIMOSI, GPIO.OUT)
GPIO.setup(SPIMISO, GPIO.IN)
GPIO.setup(SPICLK, GPIO.OUT)
GPIO.setup(SPICS, GPIO.OUT)
# set up the LED pin
GPIO.setup(22, GPIO.OUT)

# COSM variables. The API_KEY and FEED are specific to your COSM account and must be changed 
API_KEY = 'MY_API_KEY'
FEED = FEED_ID



API_URL = '/v2/feeds/{feednum}.xml' .format(feednum = FEED)

# temperature sensor connected channel 0 of mcp3008
adcnum = 0

try:  
	while True:
			# read the analog pin (temperature sensor LM35)
			read_adc0 = readadc(adcnum, SPICLK, SPIMOSI, SPIMISO, SPICS)

			# convert analog reading to millivolts = ADC * ( 3300 / 1024 )
			millivolts = read_adc0 * ( 3300.0 / 1024.0)

			# 10 mv per degree 
			temp_C = ((millivolts - 100.0) / 10.0) - 40.0

			# remove decimal point from millivolts
			millivolts = "%d" % millivolts

			# show only one decimal place for temprature and voltage readings
			temp_C = "%.1f" % temp_C

			if DEBUG:
					print "read_adc0:\t", read_adc0
					print "millivolts:\t", millivolts
					print "temperature:\t", temp_C
					print "illuminance:\t", RCtime(21)
					print

			if LOGGER:
				try:
					# open up your cosm feed
					pac = eeml.Pachube(API_URL, API_KEY)

					#send celsius data
					pac.update([eeml.Data(0, temp_C, unit=eeml.Celsius())])

					#send Lux data
					pac.update([eeml.Data(1, RCtime(21), unit=eeml.Unit('LuminousFlux', type='basicSI', symbol='lx'))])

					# send data to cosm
					pac.put()
				except:
					# continue with the next loop and see if the connection recovers next time (could log locally)
					print "internet connection lost"
					continue
			# hang out and do nothing for 30 seconds, avoid flooding cosm
			time.sleep(30)
	while True:
		#activate LED when temperature is more then 20C
		if temp_C > 20.0:
			GPIO.output(22, True)
		else:
			GPIO.output(22, False)
		time.sleep(30)

except KeyboardInterrupt:                  # trap a CTRL+C keyboard interrupt
    GPIO.cleanup()                         # resets all GPIO ports

GPIO.cleanup()                             # on finishing,reset all GPIO ports used by this program
Clearly the LED is connected to PIN #22 of the Cobler. I tried with different LED's, without a decimal value, I even tried setting an "offset" variable to compare with ... kind of stuck here, help ?

Regards,
David

techpaul
Posts: 1512
Joined: Sat Jul 14, 2012 6:40 pm
Location: Reading, UK
Contact: Website

Re: Temperature/Light controlled LED

Tue Dec 04, 2012 10:14 pm

Firstly I would llose the rather large coverage of

Code: Select all

try:
....
except KeyboardInterrupt:                  # trap a CTRL+C keyboard interrupt
    GPIO.cleanup()                         # resets all GPIO ports

GPIO.cleanup()                             # on finishing,reset all GPIO ports used by this program
For two reasons firstly you could be masking other run time errors (as they are not also trapped and reported). Secondly you end up doing two GPIO.cleanup() in a row as only way to exit is via CTRL-C anyway.

I would lose the following

The second "while true:" as it never gets there it loops first of all in the first loop and grabs results then gets stuck in first loop not reaching second loop. Leave the code it executes in the first loop.

Lose the try/except KeyboardInterrupt whilst debugging add it back later

Then see what happens
Just another techie on the net - For GPIO boards see http:///www.facebook.com/pcservicesreading
or http://www.pcserviceselectronics.co.uk/pi/

User avatar
alexeames
Forum Moderator
Forum Moderator
Posts: 2869
Joined: Sat Mar 03, 2012 11:57 am
Location: UK
Contact: Website

Re: Temperature/Light controlled LED

Wed Dec 05, 2012 12:26 pm

techpaul wrote: The second "while true:" as it never gets there it loops first of all in the first loop and grabs results then gets stuck in first loop not reaching second loop. Leave the code it executes in the first loop.
What he said. That second while true part is never executed because the first one loops round forever.

The first try: is there to ensure the GPIO gets cleaned up on CTRL-C exit. As far as I know it doesn't trap other errors as there is no other exception.

The second GPIO cleanup is not necessary I agree.
Alex Eames RasPi.TV, RasP.iO

dvanhaeke
Posts: 8
Joined: Wed Nov 21, 2012 6:57 pm

Re: Temperature/Light controlled LED

Thu Dec 06, 2012 8:30 am

Thanks for your input guys, it turned out I made a n00b error in wiring the LED on the breadboard :roll:

Next, I tried your changes as suggested but the LED was turned on continuously. Unfortunately my time was yesterday evening was limited, I'll have a second attempt tonight and keep you posted.

dvanhaeke
Posts: 8
Joined: Wed Nov 21, 2012 6:57 pm

Re: Temperature/Light controlled LED

Thu Dec 06, 2012 8:32 pm

Fixed it :D

Moved the part for triggering the LED within the while statement.

Thanks again,
David

User avatar
alexeames
Forum Moderator
Forum Moderator
Posts: 2869
Joined: Sat Mar 03, 2012 11:57 am
Location: UK
Contact: Website

Re: Temperature/Light controlled LED

Thu Dec 06, 2012 10:11 pm

Result. Now it feels like you achieved something :D If it had worked first time it would have been too easy. :D
Alex Eames RasPi.TV, RasP.iO

dvanhaeke
Posts: 8
Joined: Wed Nov 21, 2012 6:57 pm

Re: Temperature/Light controlled LED

Fri Dec 07, 2012 9:08 am

I'm actually amazed I got this far already :D

Compared to 6-8 years ago Linux has gotten a lot easier (IMO): no compiling errors, no missing kernel modules, no missing dependencies, etc.

Next, I'm going to try and hook up my 5V 8 Channel Relay board I got from Ebay (http://goo.gl/gjgiw) and see if I can switch on a light bulb or a fan (sounds familiar ?). Then when I got that working, in order to connect everything (CdS, TMP36, ADC, 8 relays) I suppose I'll need a GPIO expander like (egg.) Adafruit's MCP23017 (http://adafruit.com/products/732) ?

Can you confirm this hardware is suitable ?

Regards,
David

User avatar
alexeames
Forum Moderator
Forum Moderator
Posts: 2869
Joined: Sat Mar 03, 2012 11:57 am
Location: UK
Contact: Website

Re: Temperature/Light controlled LED

Fri Dec 07, 2012 11:58 am

dvanhaeke wrote:I'm actually amazed I got this far already :D

Compared to 6-8 years ago Linux has gotten a lot easier (IMO): no compiling errors, no missing kernel modules, no missing dependencies, etc.

Next, I'm going to try and hook up my 5V 8 Channel Relay board I got from Ebay (http://goo.gl/gjgiw) and see if I can switch on a light bulb or a fan (sounds familiar ?). Then when I got that working, in order to connect everything (CdS, TMP36, ADC, 8 relays) I suppose I'll need a GPIO expander like (egg.) Adafruit's MCP23017 (http://adafruit.com/products/732) ?

Can you confirm this hardware is suitable ?

Regards,
David
Be careful with mains. My experiments have been called "insanely dangerous" in the comments in the comments section of my site. Be safe.

How many ports do you need? You might not need the expander. The Pi (Rev 1) has 17 ports available.
Alex Eames RasPi.TV, RasP.iO

techpaul
Posts: 1512
Joined: Sat Jul 14, 2012 6:40 pm
Location: Reading, UK
Contact: Website

Re: Temperature/Light controlled LED

Fri Dec 07, 2012 12:07 pm

dvanhaeke wrote:Next, I'm going to try and hook up my 5V 8 Channel Relay board I got from Ebay (http://goo.gl/gjgiw) and see if I can switch on a light bulb or a fan (sounds familiar ?). Then when I got that working, in order to connect everything (CdS, TMP36, ADC, 8 relays) I suppose I'll need a GPIO expander like (egg.) Adafruit's MCP23017 (http://adafruit.com/products/732) ?

Can you confirm this hardware is suitable ?
Your problem with those relay board is which type you have as the input may draw a lot of current, more than GPIO or your expander (there are many of them PCF8574 PCF8575 74HC594 74HC595 first ones to mind) can provide in one pin and when all relays are on. The types are
  • Direct Relay input - needs a buffer like ULN2803A between expander and relay board
  • Opto input might work, need to check total current in expander for that one
  • Transistor input - Expander must be powered from 5V power, may get away with it
You really need to know exactly which type of relay board you have to be sure.

When dealing with mains electricity please be VERY careful
  • Keep any mains wiring away from non mains wiring,
  • keep all stripped ends of wires short,
  • make sure everything insulated,
  • make sure boards are mounted on insulated surface (no bits underneath)
  • make sure you use mains terminal strips with recessed screws and terminals
  • make sure Earth continuity is maintained for all mains powered devices
  • MAKE SURE MAINS SOURCE IS DISCONNECTED WHILE CHANGING WIRING (many people forget this one video for relays and Pis gives a wrong impression of this).
Just another techie on the net - For GPIO boards see http:///www.facebook.com/pcservicesreading
or http://www.pcserviceselectronics.co.uk/pi/

dvanhaeke
Posts: 8
Joined: Wed Nov 21, 2012 6:57 pm

Re: Temperature/Light controlled LED

Fri Dec 07, 2012 12:37 pm

Thanks for your input,

I honestly didn't know all these little details and it's as you insinuated: I saw a Youtube video without further technical details and immediately started dreaming about the possibilities.

This is the relay I bought: http://goo.gl/7rn1I, from the specs I'm pretty sure the Pi will be able to handle it:
  • The item is a 5V 8-Channel Relay interface board,It can be controlled directly by a wide range of microcontrollers such as Arduino, AVR, PIC, ARM and so on.
  • 8-Channel Relay interface board.
  • Each one needs 15-20mA Driver Current.
  • Equiped with high-current relay : DC30V 10A AC250V 10A.
  • Standard interface that can be controlled directly by microcontroller (Arduino , 8051, AVR, PIC, DSP, ARM.
  • Size:13.9cm x 5.2cm x 1.7cm (5.47inch x 2.04inch x 0.67inch).
That being said, it's Made in China, so it might as well blow up in my face :lol:

Regards,
David

techpaul
Posts: 1512
Joined: Sat Jul 14, 2012 6:40 pm
Location: Reading, UK
Contact: Website

Re: Temperature/Light controlled LED

Fri Dec 07, 2012 1:00 pm

That means it is an opto-coupler input type (input "Each one needs 15-20mA Driver Current") this usally means that the input must go to 0V and then be able to handle 15-20mA of current.

You can drive ONE relay just about from a GPIO pin, but this is NOT RECOMMENDED.

When all 8 relays are on, that means the inputs have a total of 160mA just for the inputs the relays will be drawing a LOT more current as well, so depending on you Pi configuration (USB etc) there might not be enough spare power to drive 8 at once without crashing the Pi.

I would take 8 GPIO from the Pi, to a ULN2803A device take the ouputs of that to the relay card. Consider a separate 5V power supply to drive the relay card (tie 0V to 0V/GND of Pi) add a 100uF (micro farad) capacitor to the 5V on relay card and on Pi to reduce switching surges dropping the 5V rail on the Pi

Note when driving via a ULN2803A chip the GPIO now has to be '1' to turn relay on.

Be aware these ralays being on does NOT mean the output is on, as they have three connections a common, Normally Open (NO) and Normally Closed (NC) when wiring for mains on./off control
  • Wire Live in to Normally Open contact
  • Live out to device on Common contact
This way when the relay is OFF the Normally Closed contact has no power on it, mains is totally isolated.

Only wire Live in (from mains source) to common when switching between two different loads

.
Just another techie on the net - For GPIO boards see http:///www.facebook.com/pcservicesreading
or http://www.pcserviceselectronics.co.uk/pi/

User avatar
richiepp
Posts: 140
Joined: Wed Dec 19, 2012 4:56 pm

Re: Temperature/Light controlled LED

Fri Dec 21, 2012 11:01 pm

Please post the corrected, working code.

Thx
Rich

msloan
Posts: 24
Joined: Fri Feb 24, 2012 5:36 pm

Re: Temperature/Light controlled LED

Tue Jan 29, 2013 7:01 pm

I would also be interested in this as it is similar to what I am going to do.

Return to “Python”