Simple IOT Sunlight Sensing Raspberry Pi Project – SunIOT – Part 2

Simple IOT Sunlight Sensing Raspberry Pi Project- SunIOT – Part 2

We just have added a new product, a Grove Sunlight Sensor to our lineup and wanted to build a project using it.   We are intending to add drivers for this sensing device to three of our product lines:  OurWeather, the GroveWeatherPi and the WXLink wireless data transmission products.  Since we are going to be using the Grove Sunlight Sensor so extensively, we thought we should build a quick example project.

SunIOT was thus born.   We will be building this project in four postings.  FIrst the description of the project (Part 1).  Secondly, we get the hardware up and connected , Python connected to both of the Grove devices (Part 2), Part 3 will have us connect up to initialstate.com and then in Part 4, we will use MQTT to connect to a dashboard, freeboard.io (and pubnub.com).

[include-page id=”SunIOTLinks”]

What is SunIOT?

The overall design of the project is simple.   We use the Raspberry Pi to read  a sensor that measures sunlight and breaks the sunlight down into three components (UV, IR and Visible). We also use an LED to provide visual feedback that a sample is being taken (two blinks) and that the process is still running (one blink).

The general idea of SunIOT is to build a software platform to build more complex IOT sensors.   In this column and the next, we will be going through a complete, albeit simple, IOT design.   As well as providing a test bed for the new Grove Sunlight Sensor.

Building the SunIOT

[callout size=”col-12″ last_column=”true” title=”SwitchDoc Note” description=”Warning: Always turn off the power before you remove or replace any Grove devices on your Raspberry Pi. You may damage your devices or your Raspberry Pi!”  flip_left_edge=”false” flip_right_edge=”true”]

 

SunIOT

Using Grove connectors, this is a very easy project to put together.  Step by step instructions follow:

  1. (1)Remove power from the Raspberry Pi (be sure to shut it down before you remove power!).
  2. (2)Take the Pi2Grover and align the pins on the Raspberry Pi 3 GPIO header accurately and the carefully push down the Pi2Grover board on to the Raspberry Pi 3 board.   Note that the end of the Pi2Grover board that hangs over the USB and Network plugs on the Raspberry Pi 3 has no pins on the bottom of the Pi2Grover board so it can’t short out.
  3. (3)Take your Grove Sunlight Sensor, plug in a Grove Cable into the device and then plug the other end of the cable into any of the I2C plugs on the Pi2Grover board.   Any of the plugs work as the I2C is a bus and not an individually addressed plug like the Digital Grove connectors.
  4. (4)Now take you Grove LED and plug one end of a Grove cable into the Grove LED device and the other end into the Pi2Grover Digital Grove connector marked D4/5.

That’s it!   Now power up your Raspberry Pi and if all is well you will see a blue LED on the Pi2Grover board and most of the time, you will see the Grove LED turn on (the GPIOs on the Raspberry Pi wake up as Inputs, so the pull-ups in the voltage translation circuitry will either resolve the input as a one or as a zero, usually a one.

Below is the SunIOT device out in the sun running on a USB Power pack.

img_3442

The Software

Before we are ready to run the SunIOT.py program, we have a bit of setup to do on your Raspberry Pi 3.

Set Up the I2C Bus

The Raspberry Pi operating system by default does not enable the I2C bus.

Use this tutorial for setting up and testing the I2C bus [ref:  https://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup/configuring-i2c ].

When you have done the tutorial type the following into your Raspberry Pi:

sudo i2cdetect -y 1

If everything is good, then you will see this:

pi@RPi3-62:~/SunIOT $ i2cdetect -y 1

     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: 60 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- --

0x60 is the Sunlight Sensor.

APscheduler

The Advanced Python Scheduler (APScheduler) is a light but powerful in-process task scheduler that lets you schedule functions (or any other python callables) to be executed at times of your choosing.

We have used the APScheduler software for a number of projects in the past, such as Project Curacao [ref:  Raspberry Pi Geek article on Project Curacao], SunRover [ref: Raspberry Pi Geek Article on SunRover software], the upcoming Project Curacao 2 project (we revisit wind power and the Caribbean with a 2nd generation Project Curacao) as well as other SwitchDoc Labs projects for customers.   It’s a great package.

You can install it by doing the following two commands on your Raspberry Pi.

sudo pip install setuptools --upgrade
sudo pip install apscheduler

Look through the SunIOT software and the examples on the APScheduler site to see how it is used.

Installing the SunIOT Software

We have put the source code for this column up on github.com.  Download your own copy by running the command:

git clone https://github.com/switchdoclabs/SunIOT.git


If you get the error:

"ImportError: No module named Adafruit_PureIO.smbus"

Try the following:

git clone https://github.com/adafruit/Adafruit_Python_PureIO.git
cd Adafruit_Python_PureIO
sudo python setup.py install

Description of the SunIOT Software

The SunIOT software for this posting is pretty straight forward.   Section one is shown below:

 

#
#
# SunIOT - SwitchDoc Labs
#
# October 2016
#
import sys
import os

sys.path.append('./SDL_Pi_SI1145');
import time

import RPi.GPIO as GPIO


#set up GPIO using BCM numbering
GPIO.setmode(GPIO.BCM)

LED = 4

GPIO.setup(LED, GPIO.OUT, initial=0)

from datetime import datetime

from apscheduler.schedulers.background import BackgroundScheduler


import SDL_Pi_SI1145

sensor = SDL_Pi_SI1145.SDL_Pi_SI1145()

<\pre>
In the section of the code above, all the necessary libraries are imported, the LED mapped to D4 (GPIO 4) on the Pi2Grover board and we start the SI1145 I2C sensor.

The next section of code shows the setup for all three of our tasks that we will be scheduling.
# setup apscheduler

def tick():
    print('Tick! The time is: %s' % datetime.now())


def killLogger():
    scheduler.shutdown()
    print "Scheduler Shutdown...."
    exit()

def blinkLED(times,length):

	for i in range(0, times):
		GPIO.output(LED, 1)
		time.sleep(length)
		GPIO.output(LED, 0)
		time.sleep(length)



def readSunLight():
	
        vis = sensor.readVisible()
        IR = sensor.readIR()
        UV = sensor.readUV()
        uvIndex = UV / 100.0
        print('SunLight Sensor read at time: %s' % datetime.now())
        print '		Vis:             ' + str(vis)
        print '		IR:              ' + str(IR)
        print '		UV Index:        ' + str(uvIndex)

	blinkLED(2,0.200)

	returnValue = []
	returnValue.append(vis)
	returnValue.append(IR)
	returnValue.append(uvIndex)
	return returnValue

The first task just prints out the time to the console, the second task will blink the LED to show certain events are happening (by changing the timing on blinks and the number of blinks we can show a number of different events are happening).

The third task is the real guts of our IOT device.   Here is where we read the SI1145 light sensors and return the values to our mainline program.   We also convert the UV readings into the UV Index values here.

The third section shows the main program, how we are setting up tasks for APScheduler to execute, and the main loop.

print "-----------------"
print "SunIOT"
print ""
print "SwitchDoc Labs" 
print "-----------------"
print ""


if __name__ == '__main__':

    	scheduler = BackgroundScheduler()


	# DEBUG Mode - because the functions run in a separate thread, debugging can be difficult inside the functions.
	# we run the functions here to test them.
	#tick()
	#print readSunLight()
	


	# prints out the date and time to console
    	scheduler.add_job(tick, 'interval', seconds=60)
    	# blink life light
	scheduler.add_job(blinkLED, 'interval', seconds=5, args=[1,0.250])

	# IOT Jobs are scheduled here (more coming next issue) 
	scheduler.add_job(readSunLight, 'interval', seconds=10)
	
    	# start scheduler
	scheduler.start()
	print "-----------------"
	print "Scheduled Jobs" 
	print "-----------------"
    	scheduler.print_jobs()
	print "-----------------"

    	print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    	try:
        	# This is here to simulate application activity (which keeps the main thread alive).
        	while True:
            		time.sleep(2)
    	except (KeyboardInterrupt, SystemExit):
        	# Not strictly necessary if daemonic mode is enabled but should be done if possible
        	scheduler.shutdown


As you can see, we have three tasks.  The “tick” process printing out the time to console, running every 60 seconds, the “blinkLED” process giving a heartbeat every 5 seconds and the IOT process “readSunLight” every 10 seconds.

Now, note that we really aren’t doing anything IOT in this example yet.    We have built a data gathering device and in our next column we will be hooking it up to the IOT and the world.

Running our IOT Device

Start the software by typing this (when you are in the SunIOT directory!) into your command window on the Raspberry Pi:

sudo python SunIOT.py

And the results look like this:

 

-----------------
SunIOT

SwitchDoc Labs
-----------------

-----------------
Scheduled Jobs
-----------------
Jobstore default:
    blinkLED (trigger: interval[0:00:05], next run at: 2016-10-17 20:50:45 UTC)
    readSunLight (trigger: interval[0:00:10], next run at: 2016-10-17 20:50:50 UTC)
    tick (trigger: interval[0:01:00], next run at: 2016-10-17 20:51:40 UTC)
-----------------
Press Ctrl+C to exit
SunLight Sensor read at time: 2016-10-17 20:50:50.742733
		Vis:             261
		IR:              257
		UV Index:        0.02
SunLight Sensor read at time: 2016-10-17 20:51:00.741888
		Vis:             269
		IR:              279
		UV Index:        0.05
SunLight Sensor read at time: 2016-10-17 20:51:10.743216
		Vis:             262
		IR:              258
		UV Index:        0.03
SunLight Sensor read at time: 2016-10-17 20:51:20.740935
		Vis:             261
		IR:              257
		UV Index:        0.02

We turned a light on the sensor between the first and the second readings to make sure the sensor is reading correctly. Not much UV inside SwitchDoc Labs! No way to get a sun tan here. It would be interesting to put the sensor inside a tanning bed. We wonder what level we would read!

Coming Next in Part 3

Now we have built an IOT sensing device. Next time we are going to add another sensor (not quite sure which one yet, there are so many choices!) and then we are going to hook up the SunIOT device to a Internet Dashboard using MQTT. This will complete our simple SunIOT Raspberry Pi based device.