first commit

This commit is contained in:
pandacraft 2025-03-21 16:04:17 +01:00
commit a5a0434432
1126 changed files with 439481 additions and 0 deletions

View file

@ -0,0 +1,113 @@
# grovepi_lcd_dht.py
#
# This is an project for using the Grove RGB_LED Display and the Grove DHT Sensor from the GrovePi starter kit
#
# In this project, the Temperature and humidity from the DHT sensor is printed on the RGB_LCD Display
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import decimal
from grovepi import *
from grove_rgb_lcd import *
dht_sensor_port = 7 # Connect the DHt sensor to port 7
lastTemp = 0.1 # initialize a floating point temp variable
lastHum = 0.1 # initialize a floating Point humidity variable
tooLow = 62.0 # Lower limit in fahrenheit
justRight = 68.0 # Perfect Temp in fahrenheit
tooHigh = 74.0 # Temp Too high
# Function Definitions
def CtoF( tempc ):
"This converts celcius to fahrenheit"
tempf = round((tempc * 1.8) + 32, 2);
return tempf;
def FtoC( tempf ):
"This converts fahrenheit to celcius"
tempc = round((tempf - 32) / 1.8, 2)
return tempc;
def calcColorAdj(variance): # Calc the adjustment value of the background color
"Because there is 6 degrees mapping to 255 values, 42.5 is the factor for 12 degree spread"
factor = 42.5;
adj = abs(int(factor * variance));
if adj > 255:
adj = 255;
return adj;
def calcBG(ftemp):
"This calculates the color value for the background"
variance = ftemp - justRight; # Calculate the variance
adj = calcColorAdj(variance); # Scale it to 8 bit int
bgList = [0,0,0] # initialize the color array
if(variance < 0):
bgR = 0; # too cold, no red
bgB = adj; # green and blue slide equally with adj
bgG = 255 - adj;
elif(variance == 0): # perfect, all on green
bgR = 0;
bgB = 0;
bgG = 255;
elif(variance > 0): #too hot - no blue
bgB = 0;
bgR = adj; # Red and Green slide equally with Adj
bgG = 255 - adj;
bgList = [bgR,bgG,bgB] #build list of color values to return
return bgList;
while True:
try:
temp = 0.01
hum = 0.01
[ temp,hum ] = dht(dht_sensor_port,1) #Get the temperature and Humidity from the DHT sensor
#Change the second parameter to 0 when using DHT (instead of DHT Pro)
#You will get very large number values if you don't!
if (CtoF(temp) != lastTemp) and (hum != lastHum) and not math.isnan(temp) and not math.isnan(hum):
print("lowC : ",FtoC(tooLow),"C\t\t","rightC : ", FtoC(justRight),"C\t\t","highC : ",FtoC(tooHigh),"C") # comment these three lines
print("lowF : ",tooLow,"F\t\tjustRight : ",justRight,"F\t\ttoHigh : ",tooHigh,"F") # if no monitor display
print("tempC : ", temp, "C\t\ttempF : ",CtoF(temp),"F\t\tHumidity =", hum,"%\r\n")
lastHum = hum # save temp & humidity values so that there is no update to the RGB LCD
ftemp = CtoF(temp) # unless the value changes
lastTemp = ftemp # this reduces the flashing of the display
# print "ftemp = ",ftemp," temp = ",temp # this was just for test and debug
bgList = calcBG(ftemp) # Calculate background colors
t = str(ftemp) # "stringify" the display values
h = str(hum)
# print "(",bgList[0],",",bgList[1],",",bgList[2],")" # this was to test and debug color value list
setRGB(bgList[0],bgList[1],bgList[2]) # parse our list into the color settings
setText("Temp:" + t + "F " + "Humidity :" + h + "%") # update the RGB LCD display
except (IOError,TypeError) as e:
print("Error" + str(e))

View file

@ -0,0 +1,54 @@
# button_buzzer.py
#
# This is an project using the Grove Button, Buzzer from the GrovePi starter kit
#
# In this project, the buzzer starts making a sound when the the button is hold
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import time
from grovepi import *
import math
buzzer_pin = 2 #Port for buzzer
button = 4 #Port for Button
pinMode(buzzer_pin,"OUTPUT") # Assign mode for buzzer as output
pinMode(button,"INPUT") # Assign mode for Button as input
while True:
try:
button_status= digitalRead(button) #Read the Button status
if button_status: #If the Button is in HIGH position, run the program
digitalWrite(buzzer_pin,1)
# print "\tBuzzing"
else: #If Button is in Off position, print "Off" on the screen
digitalWrite(buzzer_pin,0)
# print "Off"
except KeyboardInterrupt: # Stop the buzzer before stopping
digitalWrite(buzzer_pin,0)
break
except (IOError,TypeError) as e:
print("Error")

134
Projects/CO2_sensor.py Normal file
View file

@ -0,0 +1,134 @@
#!/usr/bin/env python
########################################################################
# Calibration and read of the CO2 sensor MH-Z16
# according to the datasheet : http://www.seeedstudio.com/wiki/images/c/ca/MH-Z16_CO2_datasheet_EN.pdf
# output value directly in ppm
# Doms made
# History
# ------------------------------------------------
# Author Date Comments
# Doms 13 04 15 Initial Authoring
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
'''
#
########################################################################
import os
import serial, time
import smbus
import math
import RPi.GPIO as GPIO
import struct
import sys
import datetime
import grovepi
import struct
from grovepi import *
#
__author__ = 'Doms Genoud'
#co2 sensor
#use an external usb to serial adapter
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout = 1) #Open the serial port at 9600 baud
#To open the raspberry serial port
#ser = serial.Serial('/dev/ttyAMA0', 9600, timeout = 1) #Open the serial port at 9600 baud
#init serial
ser.flush()
############# carbon dioxid CO2 #####################
class CO2:
#inspired from c code of http://www.seeedstudio.com/wiki/Grove_-_CO2_Sensor
#Gas concentration= high level *256+low level
inp =[]
cmd_zero_sensor = "\xff\x87\x87\x00\x00\x00\x00\x00\xf2"
cmd_span_sensor = "\xff\x87\x87\x00\x00\x00\x00\x00\xf2"
cmd_get_sensor = "\xff\x01\x86\x00\x00\x00\x00\x00\x79"
def read(self):
try:
while True:
ser.write(CO2.cmd_get_sensor)
CO2.inp = ser.read(9)
high_level = struct.unpack('B',CO2.inp[2])[0]
low_level = struct.unpack('B',CO2.inp[3])[0]
temp_co2 = struct.unpack('B',CO2.inp[4])[0] - 40
#output in ppm
conc = high_level*256+low_level
return [conc,temp_co2]
except IOError:
return [-1,-1]
def calibrateZero(self):
try:
ser.write(CO2.cmd_zero_sensor)
print("CO2 sensor zero calibrated")
except IOError:
print("CO2 sensor calibration error")
def calibrateSpan(self):
try:
while True:
#ser.write(CO2.cmd_zero_sensor)
print("CO2 sensor span calibrated")
break
except IOError:
print("CO2 sensor calibration error")
########################################################################################################
############# MAIN
########################################################################################################
# following the specs of the sensor :
# read the sensor, wait 3 minutes, set the zero, read the sensor
c = CO2()
while True:
try:
#CO2 sensor calib
print("wait 3 minutes to warm up CO2 sensor")
time.sleep(180)
print("Read before calibration-->",c.read())
print("calibrating...")
co2 = c.calibrateZero()
time.sleep(5)
print("Read after calibration-->",c.read())
print("DONE")
break
except IndexError:
print("Unable to read")
except KeyboardInterrupt:
print("Exiting")
sys.exit(0)

View file

@ -0,0 +1,32 @@
## **Candy Counting Raspberry Pi Robot Costume**
In this project, we took the tried-and-true robot costume and gave it some life with the Raspberry Pi, GrovePi, and a handful of sensors. The costume is a standard robot costume, but with a candy-counting machine attached that talks!
When a piece of candy is placed in the robot, it flashes it's LEDs, thanks the candy donor for the piece of candy, and announces the candy count. We use the Raspberry Pi for brains, the GrovePi and assorted sensors to detect candy, and a battery powered speaker to do the talking. The whole project takes about 2 hours to build.
### How to use
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2016 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN

View file

@ -0,0 +1,491 @@
#!/usr/bin/env python
#
# Raspberry Pi Robot Costume
'''
In this project, we're making a Raspberry Pi Robot Costume. The costume will count candy placed in a bin, and speak out loud to the giver.
Well use the GrovePi, with an Ultrasonic Sensor, an LED Bar graph, 4 Chainable LED's, and the RGB LCD Display. We'll also use a small
portable speaker to give the robot a voice.
Each time a piece of candy is placed in the robot, it says "Thank you for the candy" and reads aloud the count of candy.
'''
#
import os
import random
import time
import grovepi
import sys
import random
from subprocess import call
from grove_rgb_lcd import *
candy_count = 10
bar_level = 0
led1 = 14
led2 = 15
led3 = 16
grovepi.pinMode(led1,"OUTPUT")
grovepi.pinMode(led2,"OUTPUT")
grovepi.pinMode(led3,"OUTPUT")
# Connect the Grove LED Bar to digital port D5
# DI,DCKI,VCC,GND
ledbar = 5
grovepi.pinMode(ledbar,"OUTPUT")
time.sleep(1)
i = 0
# Connect the Grove Ultrasonic Ranger to digital port D4
# SIG,NC,VCC,GND
ultrasonic_ranger = 4
# Connect first LED in Chainable RGB LED chain to digital port D7
# In: CI,DI,VCC,GND
# Out: CO,DO,VCC,GND
ledpin = 7 # RGB LED's are on D7
# First LED input socket connected to GrovePi, output socket connected to second LED input and so on
numleds = 4 #If you only plug 1 LED, change to 1
grovepi.pinMode(ledpin,"OUTPUT")
time.sleep(1)
# Connect the Grove 4 Digit Display to digital port D2
# CLK,DIO,VCC,GND
display = 2
grovepi.pinMode(display,"OUTPUT")
# test colors used in grovepi.chainableRgbLed_test()
testColorBlack = 0 # 0b000 #000000
testColorBlue = 1 # 0b001 #0000FF
testColorGreen = 2 # 0b010 #00FF00
testColorCyan = 3 # 0b011 #00FFFF
testColorRed = 4 # 0b100 #FF0000
testColorMagenta = 5 # 0b101 #FF00FF
testColorYellow = 6 # 0b110 #FFFF00
testColorWhite = 7 # 0b111 #FFFFFF
# patterns used in grovepi.chainableRgbLed_pattern()
thisLedOnly = 0
allLedsExceptThis = 1
thisLedAndInwards = 2
thisLedAndOutwards = 3
def initalize_chained_led():
print("Test 1) Initialise")
# init chain of leds
grovepi.chainableRgbLed_init(ledpin, numleds)
time.sleep(.5)
grovepi.chainableRgbLed_test(ledpin, numleds, random.randint(0,7))
time.sleep(.5)
def chained_led():
try:
# set led 1 to green
grovepi.chainableRgbLed_pattern(pin, thisLedOnly, 0)
time.sleep(.5)
# change color to red
grovepi.storeColor(255,0,0)
time.sleep(.5)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 2b) Test Patterns - blue")
# test pattern 1 blue
grovepi.chainableRgbLed_test(pin, numleds, testColorBlue)
time.sleep(1)
print ("Test 2c) Test Patterns - green")
# test pattern 2 green
grovepi.chainableRgbLed_test(pin, numleds, testColorGreen)
time.sleep(1)
print ("Test 2d) Test Patterns - cyan")
# test pattern 3 cyan
grovepi.chainableRgbLed_test(pin, numleds, testColorCyan)
time.sleep(1)
print ("Test 2e) Test Patterns - red")
# test pattern 4 red
grovepi.chainableRgbLed_test(pin, numleds, testColorRed)
time.sleep(1)
print ("Test 2f) Test Patterns - magenta")
# test pattern 5 magenta
grovepi.chainableRgbLed_test(pin, numleds, testColorMagenta)
time.sleep(1)
print ("Test 2g) Test Patterns - yellow")
# test pattern 6 yellow
grovepi.chainableRgbLed_test(pin, numleds, testColorYellow)
time.sleep(1)
print ("Test 2h) Test Patterns - white")
# test pattern 7 white
grovepi.chainableRgbLed_test(pin, numleds, testColorWhite)
time.sleep(1)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 3a) Set using pattern - this led only")
# change color to red
grovepi.storeColor(255,0,0)
time.sleep(.5)
# set led 3 to red
grovepi.chainableRgbLed_pattern(pin, thisLedOnly, 2)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 3b) Set using pattern - all leds except this")
# change color to blue
grovepi.storeColor(0,0,255)
time.sleep(.5)
# set all leds except for 3 to blue
grovepi.chainableRgbLed_pattern(pin, allLedsExceptThis, 3)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 3c) Set using pattern - this led and inwards")
# change color to green
grovepi.storeColor(0,255,0)
time.sleep(.5)
# set leds 1-3 to green
grovepi.chainableRgbLed_pattern(pin, thisLedAndInwards, 2)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 3d) Set using pattern - this led and outwards")
# change color to green
grovepi.storeColor(0,255,0)
time.sleep(.5)
# set leds 7-10 to green
grovepi.chainableRgbLed_pattern(pin, thisLedAndOutwards, 6)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 4a) Set using modulo - all leds")
# change color to black (fully off)
grovepi.storeColor(0,0,0)
time.sleep(.5)
# set all leds black
# offset 0 means start at first led
# divisor 1 means every led
grovepi.chainableRgbLed_modulo(pin, 0, 1)
time.sleep(.5)
# change color to white (fully on)
grovepi.storeColor(255,255,255)
time.sleep(.5)
# set all leds white
grovepi.chainableRgbLed_modulo(pin, 0, 1)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 4b) Set using modulo - every 2")
# change color to red
grovepi.storeColor(255,0,0)
time.sleep(.5)
# set every 2nd led to red
grovepi.chainableRgbLed_modulo(pin, 0, 2)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
print ("Test 4c) Set using modulo - every 2, offset 1")
# change color to green
grovepi.storeColor(0,255,0)
time.sleep(.5)
# set every 2nd led to green, offset 1
grovepi.chainableRgbLed_modulo(pin, 1, 2)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 4d) Set using modulo - every 3, offset 0")
# change color to red
grovepi.storeColor(255,0,0)
time.sleep(.5)
# set every 3nd led to red
grovepi.chainableRgbLed_modulo(pin, 0, 3)
time.sleep(.5)
# change color to green
grovepi.storeColor(0,255,0)
time.sleep(.5)
# set every 3nd led to green, offset 1
grovepi.chainableRgbLed_modulo(pin, 1, 3)
time.sleep(.5)
# change color to blue
grovepi.storeColor(0,0,255)
time.sleep(.5)
# set every 3nd led to blue, offset 2
grovepi.chainableRgbLed_modulo(pin, 2, 3)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 4e) Set using modulo - every 3, offset 1")
# change color to yellow
grovepi.storeColor(255,255,0)
time.sleep(.5)
# set every 4nd led to yellow
grovepi.chainableRgbLed_modulo(pin, 1, 3)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
print ("Test 4f) Set using modulo - every 3, offset 2")
# change color to magenta
grovepi.storeColor(255,0,255)
time.sleep(.5)
# set every 4nd led to magenta
grovepi.chainableRgbLed_modulo(pin, 2, 3)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 5a) Set level 6")
# change color to green
grovepi.storeColor(0,255,0)
time.sleep(.5)
# set leds 1-6 to green
grovepi.write_i2c_block(0x04,[95,pin,6,0])
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 5b) Set level 7 - reverse")
# change color to red
grovepi.storeColor(255,0,0)
time.sleep(.5)
# set leds 4-10 to red
grovepi.write_i2c_block(0x04,[95,pin,7,1])
time.sleep(.5)
except KeyboardInterrupt:
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
except IOError:
print ("Error")
def led_random():
#print "Change LED Color"
# test pattern 1 blue
try:
grovepi.chainableRgbLed_test(ledpin, numleds, random.randint(0,7))
# time.sleep(1)
except:
print "led_random failure"
def lcd_rgb(text):
c = random.randint(0,255)
setRGB(c,255-c,0)
setText(text)
def lcd_rgb_blue_blank():
setRGB(0,0,255)
#Calls the Espeak TTS Engine to read aloud a sentence
def sound(spk):
# -ven+m7: Male voice
# -s180: set reading to 180 Words per minute
# -k20: Emphasis on Capital letters
cmd_beg=" espeak -ven+m7 -a 200 -s180 -k20 --stdout '"
cmd_end="' | aplay"
print cmd_beg+spk+cmd_end
call ([cmd_beg+spk+cmd_end], shell=True)
def LEDBarGraph(level):
grovepi.ledBar_setLevel(ledbar,level)
time.sleep(0.1)
def random_bar():
global bar_level
# print "Random bar! " + str(bar_level)
try:
ran_bar_sign = random.randint(0,1)
if ran_bar_sign > 0:
bar_level = bar_level + 1
else:
bar_level = bar_level - 1
if bar_level < 0:
bar_level = 0
if bar_level > 10:
bar_level = 10
LEDBarGraph(bar_level)
except:
print "Random Bar Failure"
def random_led():
try:
grovepi.digitalWrite(led1,random.randint(0,1))
grovepi.digitalWrite(led2,random.randint(0,1))
grovepi.digitalWrite(led3,random.randint(0,1))
except:
print "LED Failure!"
def candy_detection():
global candy_count
dist = 100
try:
while dist > 8:
# Read distance value from Ultrasonic
# print(grovepi.ultrasonicRead(ultrasonic_ranger))
dist = grovepi.ultrasonicRead(ultrasonic_ranger)
random_bar()
led_random()
print("Distance Detected: " + str(dist))
candy_count = candy_count + 1
thanks = "Thank you for the candy! " + "I now have " + str(candy_count) + " pieces of candy!"
lcd_rgb(str(thanks))
led_random()
sound(thanks)
except TypeError:
print ("Ultrasonic Error! Error!")
except IOError:
print ("Ultrasonic Error! Error!")
initalize_chained_led() #Starts LED's sets to green.
grovepi.ledBar_init(ledbar, 0)
time.sleep(.5)
while True:
led_random()
random_bar()
try:
led_random()
candy_detection()
except:
print "Error."
lcd_rgb_blue_blank()
random_bar()
random_led()
led_random()
led_random()

View file

@ -0,0 +1,30 @@
## **Catch a Lunch Thief**
Have you ever had your lunch stolen? This project will help you find the culprit! Using the GrovePi, a Raspberry Pi, and a Raspberry Pi camera this project will e-mail you when your lunch is moved, taking a picture of the offender and helping you nab the lunch thief.
See more at the [GrovePi Site](http://dexterindustries.com/GrovePi/)
## License
.
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,58 @@
#! /usr/local/bin/python
# This project by Dexter Industries will help you figure out who's stealing your lunch! In
# this project, we will use the GrovePi to take a picture of the culprit when the light in
# your fridge turns on. We will use the light detector for Grove to detect when the fridge
# door has been opened.
#
# Hardware Setup:
# - Use the Raspberry Pi and GrovePi. (http://www.dexterindustries.com/shop/grovepi-starter-kit-2/)
# - Use the Raspberry Pi camera. (http://www.dexterindustries.com/shop/raspberry-pi-camera/)
# - Connect the light sensor to A0. (http://www.dexterindustries.com/shop/grove-light-sensor/)
# You can adjust the threshold value if you have a bright environment.
# Change the email_destination to change the destination you send an e-mail to.
import time
import datetime
import grovepi
import picamera
import send_email_pic
email_destination = 'examples@dexterindustries.com' # Change this to the destination e-mail.
destination = [email_destination] # We put it into an array.
# Connect the Grove Light Sensor to analog port A0
# SIG,NC,VCC,GND
light_sensor = 0 # Connect the light sensor to A0 Port.
grovepi.pinMode(light_sensor,"INPUT") # Set the A0 port to input.
# Send a picture once sensor exceeds threshold resistance
threshold = 600 # Adjust this threshold higher or lower
# Depending on how bright your fridge is.
camera = picamera.PiCamera() # Setup the Pi Camera
# Simple function to get the date as a string.
def get_time_string():
dateString = '%Y-%m-%d_%H-%M-%S'
return_string = datetime.datetime.now().strftime(dateString)
return return_string
while True:
try:
# Get sensor value. Read the light sensor.
sensor_value = grovepi.analogRead(light_sensor)
# Sense the light coming on, within the target range
if sensor_value > threshold:
print ('The fridget light is on!') # Print a note to let us know how it goes.
file_name = "lunch_status-"+str(get_time_string())+".jpg"
camera.capture(file_name) # Take a picture and save it to file_name
# Now send an e-mail
send_email_pic.send_email("The fridge has been opened!", destination, "The fridge has been opened!", file_name)
else:
print ('.') # Do nothing! It's still dark.
time.sleep(.5) # If your hold time is less than this, you might not see as many detections
except IOError:
print ("Error")

View file

@ -0,0 +1,59 @@
#! /usr/local/bin/python
# This example will show you how to send an email in python, with a picture
# attachment. This example uses outlook.com to send an e-mail.
SMTPserver = 'smtp.live.com'
sender = 'dexterexamples@outlook.com'
USERNAME = "dexterexamples@outlook.com"
PASSWORD = "password"
text_subtype = 'plain' # typical values for text_subtype are plain, html, xml
content="""\ Test message """
import sys
import os
import re
# from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP
# protocol (port 465, uses SSL)
from smtplib import *
from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
from email.MIMEText import MIMEText
# Here are the email package modules we'll need for images.
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
def send_email(content, destination, subject, file):
try:
msg = MIMEMultipart()
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
fp = open(file, 'rb') # Open File name "file"
img = MIMEImage(fp.read()) # Read the file.
fp.close() # Good housekeeping: close the file.
msg.attach(img) # Attach the file to the message.
conn = SMTP(SMTPserver, port = 587, timeout = 60) # timeout is critical here for long term health.
conn.ehlo()
conn.starttls()
conn.ehlo()
conn.login(USERNAME, PASSWORD)
conn.set_debuglevel(1)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.close()
except Exception as exc:
# Print a message error!
print("Mail failed; %s" % str(exc))
print("Moving on!")
# Example function call! This is what calling the function would look like!
# send_email(content, destination, subject, file) where "content" is the content of the email, destination is the destination
# of the e-mail (who you're emailing to) and subject is the subject of the e-mail. file is the filename of the image file
# you want to attach. It's usually best to include the full path of the file!
file = "/home/pi/test.jpg"
destination = ['examples@dexterindustries.com'] # Enter the destination e-mail address here, between the ''
send_email("Hello from my Raspberry Pi!", destination, "Hello from Dex!", file)

View file

@ -0,0 +1,11 @@
This folder contains the code to create a smart Holidays wreath, using a string of holiday lights from yesteryear.
The wreath lights will turn on when it's dark and wait for sunrise to turn off.
The lights will blink whenever a movement is detected, whether it's day or not.
Use:
- the PIR sensor on port D8,
- the light sensor on port A0
- and the relay on port D2
Write-up with explanations can be found here:
http://www.dexterindustries.com/projects/holiday-wreath/

View file

@ -0,0 +1,146 @@
#!/usr/bin/env python
#
# GrovePi Example for using the Grove Relay (http://www.seeedstudio.com/wiki/Grove_-_Relay)
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
# NOTE: Relay is normally open. LED will illuminate when closed and you will hear a definitive click sound
import time
import grovepi
# Connect the Grove Relay to digital port D2
# SIG,NC,VCC,GND
relay = 2
# connect the PIR sensor to digital port D8
pir_sensor = 8
# connect the light sensor to analog port A0
light_sensor = 0
# how dark must it be before the lights turn on
# you may want to adjust this if you have a street lamp or a porch light nearby
light_threshold = 500
# delay when blinking lights. Currently on for 1 second, off for 1 second
blink_delay = 1
# how long should the wreath be on after sunset (in hours)
hours_after_sunset = 5
# how long should the wreath sleep till sunrise (in hours)
hours_of_sleep = 6
# initial status
lights_on = False
start_sleeptime = time.time()
def sleeptime():
"""
Calculates if it's time for the wreath to turn off for the night, and go to sleep
Contains a rather long sleep time (technically the whole night)
"""
global lights_on
now = time.time()
go_to_sleep_time = start_sleeptime + (hours_after_sunset*60*60)
# print now, start_sleeptime, "(", now-start_sleeptime,")", go_to_sleep_time, "(",go_to_sleep_time-now,")"
if now >= go_to_sleep_time:
print("Sleep time!!!")
print("Will wake up in ", hours_of_sleep, " hours")
grovepi.digitalWrite(relay,0)
lights_on = False
for i in range(60):
time.sleep(hours_of_sleep * 60 ) # long sleep time!!!
print("Wake up!")
def blink(in_time):
"""
blinks the wreath lights a certain number of times
variable blink_delay determines how quick or slow the blink is
in_time determines how many times the lights will blink
"""
for i in range(in_time):
grovepi.digitalWrite(relay,1)
time.sleep(blink_delay)
grovepi.digitalWrite(relay,0)
time.sleep(blink_delay)
if lights_on == True:
grovepi.digitalWrite(relay,1)
grovepi.pinMode(relay,"OUTPUT")
grovepi.pinMode(pir_sensor,"INPUT")
grovepi.pinMode(light_sensor,"INPUT")
##########################
# main loop
##########################
while True:
try:
# if the lights are on, test whether it's time for a long nappy
if lights_on==True:
sleeptime() # test included in this function call.
if grovepi.digitalRead(pir_sensor):
# switch on for 5 seconds
print ("blink on")
blink(5)
print ("blink off")
light_sensor_value = grovepi.analogRead(light_sensor)
# is it getting dark?
if light_sensor_value < light_threshold:
# turn lights on
if lights_on == False:
lights_on = True
start_sleeptime = time.time()
print("turning lights on ")
grovepi.digitalWrite(relay,1)
# is it getting light?
else:
# turn lights off
if lights_on == True:
lights_on = False
print("turning lights off", light_sensor_value)
grovepi.digitalWrite(relay,0)
except KeyboardInterrupt:
grovepi.digitalWrite(relay,0)
break
except IOError as e:
pass
# print ("I/O error({0}): {1}".format(e.errno, e.strerror))
time.sleep(2)

View file

@ -0,0 +1,85 @@
# Home_Weather_Display.py
#
# This is an project for using the Grove RGB LCD Display and the Grove DHT Sensor from the GrovePi starter kit
#
# In this project, the Temperature and humidity from the DHT sensor is printed on the RGB-LCD Display
#
#
# Note the dht_sensor_type below may need to be changed depending on which DHT sensor you have:
# 0 - DHT11 - blue one - comes with the GrovePi+ Starter Kit
# 1 - DHT22 - white one, aka DHT Pro or AM2302
# 2 - DHT21 - black one, aka AM2301
#
# For more info please see: http://www.dexterindustries.com/topic/537-6c-displayed-in-home-weather-project/
#
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
from grovepi import *
from grove_rgb_lcd import *
from time import sleep
from math import isnan
dht_sensor_port = 7 # connect the DHt sensor to port 7
dht_sensor_type = 0 # use 0 for the blue-colored sensor and 1 for the white-colored sensor
# set green as backlight color
# we need to do it just once
# setting the backlight color once reduces the amount of data transfer over the I2C line
setRGB(0,255,0)
while True:
try:
# get the temperature and Humidity from the DHT sensor
[ temp,hum ] = dht(dht_sensor_port,dht_sensor_type)
print("temp =", temp, "C\thumidity =", hum,"%")
# check if we have nans
# if so, then raise a type error exception
if isnan(temp) is True or isnan(hum) is True:
raise TypeError('nan error')
t = str(temp)
h = str(hum)
# instead of inserting a bunch of whitespace, we can just insert a \n
# we're ensuring that if we get some strange strings on one line, the 2nd one won't be affected
setText_norefresh("Temp:" + t + "C\n" + "Humidity :" + h + "%")
except (IOError, TypeError) as e:
print(str(e))
# and since we got a type error
# then reset the LCD's text
setText("")
except KeyboardInterrupt as e:
print(str(e))
# since we're exiting the program
# it's better to leave the LCD with a blank text
setText("")
break
# wait some time before re-updating the LCD
sleep(0.05)

59
Projects/IOT/grove_IOT.py Normal file
View file

@ -0,0 +1,59 @@
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import xively
import datetime
import sys
import time
import grovepi
sensor = 4
XIVELY_API_KEY = "xmvAR7Y2KxAd00B8AFS1smKCsMigYheWFCybsx58sc2DmFOJ"
XIVELY_FEED_ID = "631205699"
api = xively.XivelyAPIClient(XIVELY_API_KEY)
feed = api.feeds.get(XIVELY_FEED_ID)
while True:
try:
now = datetime.datetime.utcnow()
[temp,humidity] = grovepi.dht(sensor,1)
light=int(grovepi.analogRead(0)/10.24)
sound=int(grovepi.analogRead(1)/10.24)
print(temp,humidity,light,sound)
feed.datastreams = [
xively.Datastream(id='temp', current_value=temp, at=now),
xively.Datastream(id='humidity', current_value=humidity, at=now),
xively.Datastream(id='light', current_value=light, at=now),
xively.Datastream(id='sound', current_value=sound, at=now),
]
feed.update()
time.sleep(10)
except:
print("Error")

View file

@ -0,0 +1,55 @@
# Adjust LED brightness by rotating Potentiometer
# GrovePi + Rotary Angle Sensor (Potentiometer) + LED
# http://www.seeedstudio.com/wiki/Grove_-_Rotary_Angle_Sensor
# http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import time
import grovepi
# Connect the Rotary Angle Sensor to analog port A2
potentiometer = 2
# Connect the LED to digital port D5
led = 5
grovepi.pinMode(led,"OUTPUT")
time.sleep(1)
i = 0
while True:
try:
# Read resistance from Potentiometer
i = grovepi.analogRead(potentiometer)
print(i)
# Send PWM signal to LED
grovepi.analogWrite(led,i//4)
except IOError:
print("Error")

View file

@ -0,0 +1,150 @@
# GrovePi Minecraft Controller
# This is a custom controller for Minecraft, made using the GrovePi.
# In this example, we show you how to build your own custom Minecraft controller
# with the GrovePi.
# See more about the GrovePi at http://dexterindustries.com/grovepi
# A great reference we used is the MagPi's Essentials Minecraft Guide: https://www.raspberrypi.org/magpi-issues/Essentials_Minecraft_v1.pdf
'''
Software Setup:
Before we begin, run the following commands to setup:
sudo apt-get install minecraft-pi
sudo pip3 install python3-xlib
sudo pip3 install pyautogui
Hardware Setup:
Setup the GrovePi on the Raspberry Pi.
Connect a touch Sensor to port A0.
Connect a Joystick to port A2.
Connect a touch sensor to Port D3.
Connect a touch sensor to Port D4.
To run:
1. Start Minecraft on the Pi.
2. Start a world.
3. Start Python3 (IDLE).
4. Open this file (GrovePi-Controller.py)
5. Click "Run" --> "Run Module"
6. Click back into Minecraft.
'''
import mcpi.minecraft as minecraft
import grovepi
import time
import mcpi.block as block
import pyautogui as pag
# Setup the four sensors.
touch_sensor1 = 4 # This will be the Build Key
touch_sensor2 = 3 # This will be the Destroy Key
touch_sensor3 = 14 # This will be the Fly Key.
# This will be the joystick.
xPin = 16 # Port A2
yPin = 17 # Port A2
grovepi.pinMode(xPin, "INPUT")
grovepi.pinMode(yPin, "INPUT")
grovepi.pinMode(touch_sensor1, "INPUT")
grovepi.pinMode(touch_sensor2, "INPUT")
grovepi.pinMode(touch_sensor3, "INPUT")
flying = 0;
# Creat a minecraft entity. We'll reference this through the entire program.
mc = minecraft.Minecraft.create()
# unpress() - This function unpresses all keys.
def unpress():
for key in ['s','w','a','d',' ']:
pag.keyUp(key)
# move() - This function presses the key "direction"
def move(direction):
unpress()
pag.keyDown(direction)
#build - This function builds a square block of "size" size.
def build(p):
size = 5
mc.setBlocks(p.x+1, p.y+1, p.z+1, (p.x + size), (p.y + size), (p.z + size), block.STONE.id)
print("Build!")
#destroy - This function destroys a square block of "size" size.
def destroy(p):
size = 5
mc.setBlocks(p.x+1, p.y+1, p.z+1, (p.x + size), (p.y + size), (p.z + size), block.AIR.id)
print("Destroy!")
# fly - This starts and stops the flying mode.
def fly():
pag.keyDown(' ')
pag.keyUp(' ')
pag.keyDown(' ')
pag.keyUp(' ')
print("Flying!")
# We do the following loop over and over.
while True:
p = mc.player.getTilePos() # Get the position of our person in Minecraft.
try:
# Read the three keys.
# Touch Sensor 1: Build something if it's touched.
if(grovepi.digitalRead(touch_sensor1)):
build(p)
# Touch Sensor 2: Destroy something if it's touched.
if(grovepi.digitalRead(touch_sensor2)):
destroy(p)
# Touch Sensor 3: Start or stop flying if it's been touched.
if(grovepi.digitalRead(touch_sensor3)):
#The variable flying is whether we're flying or not.
if(flying == 0):
flying = 1
fly()
else:
flying = 0
# Read the joystick. We do that with the two pins x and y.
x = grovepi.analogRead(xPin)
y = grovepi.analogRead(yPin)
# Check to see if the joystick has been pressed down.
click = 1 if x >= 1020 else 0
print(str(x) + ", " + str(y))
# Check to see if we've been put into flying mode. If we have, we can teleport ourselves!
if(flying):
jump = 5 # This is the jump size, how far we're going to jump in each direction.
playerPosition = mc.player.getPos() # Get our persons position in Minecraft.
# Now we'll take the joystick values and jump in the direction it tells us to.
if(x < 400):
mc.player.setPos(playerPosition.x+jump, playerPosition.y, playerPosition.z)
# Here we will make sure that the click and the x-axis reading are not confused.
elif(x > 600 and (click == 0)):
mc.player.setPos(playerPosition.x-jump, playerPosition.y, playerPosition.z)
elif(y > 600):
mc.player.setPos(playerPosition.x, playerPosition.y+jump, playerPosition.z)
elif(y < 400):
mc.player.setPos(playerPosition.x, playerPosition.y-jump, playerPosition.z)
# If we didn't read anything, unpress the buttons.
else:
unpress()
# If the joystick is clicked, we fly up one spot.
if(click):
pag.keyUp(' ')
pag.keyDown(' ')
except IOError:
print("Error")

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View file

@ -0,0 +1,37 @@
## **Mine Controls.**
![Picture](Minecraft-dexter-industries.jpg)
### What is it?
Mine Controls are custom hardware controls for Minecraft and the Raspberry Pi! In this project we show you how to build a custom controller for Minecraft using the Raspberry Pi and the GrovePi. You can get [all the hardware for this project from the Dexter Industries website.](http://dexterindustries.com/grovepi)
### Setup
See the [full project description for making a custom Minecraft controller for your Raspberry Pi here](http://www.dexterindustries.com/projects/custom-minecraft-controller/).
Software Setup:
Before we begin, run the following commands to setup:
`sudo apt-get install minecraft-pi `
`sudo pip3 install python3-xlib`
`sudo pip3 install pyautogui`
Hardware Setup:
Setup the GrovePi on the Raspberry Pi.
Connect a touch Sensor to port A0.
Connect a Joystick to port A2.
Connect a touch sensor to Port D3.
Connect a touch sensor to Port D4.
To run:
1. Start Minecraft on the Pi.
2. Start a world.
3. Start Python3 (IDLE).
4. Open this file (GrovePi-Controller.py)
5. Click "Run" --> "Run Module"
6. Click back into Minecraft.
See more at the [Dexter Industries](http://dexterindustries.com/).

View file

@ -0,0 +1,80 @@
#This is an example for the using the Grove OLED as a weather display
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
from grove_oled import *
import json
import urllib
#Get the weather
city="Chennai"
url="http://api.openweathermap.org/data/2.5/weather?q="+city
jsonurl = urllib.urlopen(url)
text = json.loads(jsonurl.read())
weather_desc=text["weather"][0]["description"] # General description of the weather
temp=float(text["main"]["temp"])-273.15 # Temperature in C
pressure=text["main"]["pressure"] # Pressure in hPa
humidity=text["main"]["humidity"] # Humidity %
wind_speed=text["wind"]["speed"] # Wind speed mps
print(weather_desc,temp,pressure,humidity,wind_speed)
#Print the data on the OLED
#Initialize the OLED
oled_init()
oled_clearDisplay()
oled_setNormalDisplay()
oled_setVerticalMode()
time.sleep(.1)
line=0
oled_setTextXY(line,0)
oled_putString("WEATHER:")
line+=2
oled_setTextXY(line,0)
oled_putString(weather_desc[:12])
line+=1
oled_setTextXY(line,0)
oled_putString("Temp:"+str(temp)+"C")
line+=1
oled_setTextXY(line,0)
oled_putString("Hum:"+str(humidity)+"%")
line+=1
oled_setTextXY(line,0)
oled_putString("Wind:"+str(wind_speed)+"mps")
line+=2
oled_setTextXY(line,0)
oled_putString("Pressure:")
line+=1
oled_setTextXY(line,0)
oled_putString(str(pressure)+"hPa")

View file

@ -0,0 +1,116 @@
# Adapted from home_temp_hum_display.py
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
from grovepi import *
from grove_oled import *
import threading
dht_sensor_port = 7 # Connect the DHt sensor to port 7
#Start and initialize the OLED
oled_init()
oled_clearDisplay()
oled_setNormalDisplay()
oled_setVerticalMode()
time.sleep(.1)
def get_outside_weather(location='Bucharest,ro'):
import pyowm # Do a 'sudo pip install pyowm' to get this module
owm = pyowm.OWM()
#forecast = owm.daily_forecast(location)
observation = owm.weather_at_place(location)
weather = observation.get_weather()
return weather
def update_outside_weather():
# This uses OpenWeatherMap via the PyOWM module;
# pywom module needs to be installed via pip,
# see https://github.com/csparpa/pyowm
weather = get_outside_weather()
# by default location is Bucharest,ro; change it to your own
oled_setTextXY(5, 1)
oled_putString("OUTSIDE")
oled_setTextXY(7, 0)
oled_putString("Temp:")
oled_putString(str(weather.get_temperature("celsius")['temp']) + "C")
oled_setTextXY(8, 0)
oled_putString("Hum :")
oled_putString(str(weather.get_humidity()) + "%")
oled_setTextXY(9, 0)
oled_putString("Rain:")
rain = weather.get_rain()
if len(rain) > 0:
pass
else:
oled_putString("0%")
print(("Weather: ", weather.get_temperature("celsius")))
print(("Humidity: ", weather.get_humidity()))
while True:
try:
# Get the temperature and Humidity from the DHT sensor
[temp, hum] = dht(dht_sensor_port, 1)
print(("Temp =", temp, "C\tHumidity =", hum, "%"))
t = str(temp)
h = str(hum)
#outside_thread = threading.Thread(target=update_outside_weather)
#outside_thread.start()
oled_setTextXY(0, 1) # Print "INSIDE" at line 1
oled_putString("INSIDE")
oled_setTextXY(2, 0) # Print "TEMP" and the temperature in line 3
oled_putString("Temp:")
oled_putString(t + "C")
oled_setTextXY(3, 0) # Print "HUM :" and the humidity in line 4
oled_putString("Hum :")
oled_putString(h + "%")
#outside_thread.join()
update_outside_weather()
except (IOError, TypeError, Exception) as e:
print(("Error:" + str(e)))
finally:
#outside_thread.join()
pass

View file

@ -0,0 +1,94 @@
## **GrovePi Open Wifi Finder**
GrovePi is an open source platform for connecting Grove Sensors to the Raspberry Pi. Create your Internet of Things devices and inventions, no soldering!
Scan for open wifi networks! This is a portable wifi hotspot finder. See our project [here](http://www.dexterindustries.com/GrovePi) for more information on turning this into a portable wifi hotspot finder.
### How Does it Work?
The GrovePi board slips over the Raspberry Pi. Connect the Grove Sensors to the GrovePi board.
####Software Setup Notes:
* This example uses [wifi library](https://wifi.readthedocs.org/en/latest/wifi_command.html). Install with pip install wifi
* Wifi dongle must be on wlan0 ; Check this with the command "ifconfig" on the command line.
####Hardware Setup Notes:
* Buzzer goes on port D2 of the GrovePi.
* LED Goes on port D3 of the GrovePi.
* The LCD goes on I2C-1. Check this with the command "sudo i2cdetect -y 1"
The GrovePi connects the Raspberry Pi and Grove sensors. You can learn [more about GrovePi here.](http://www.dexterindustries.com/GrovePi)
### Make This Start at Boot!
If you're going to take this outside, make sure you can start this at boot.
First, the files in this directory are copied into the home directory.
Make a script "start.sh" and put a command to start the wifi_finder.py script.
```
sudo nano start.sh
```
The contents of start.sh are going to be:
```
#!/bin/bash
sudo python /home/pi/wifi_finder.py
```
And then open up rc.local
```
sudo nano /etc/rc.local
```
and add the last few lines of this file should be:
```
sudo sh /home/pi/start.sh
exit 0
```
Then that's it! Reboot and test!
Have a question about this example? [Ask on the forums here.](http://forum.dexterindustries.com/c/grovepi)
LICENSE:
These files have been made available online through a [Creative Commons Attribution-ShareAlike 3.0](http://creativecommons.org/licenses/by-sa/3.0/) license.
### Raspberry Pi Compatibility
The GrovePi is compatible with the Raspberry Pi models A, A+, B, B+, and 2.
### Programming the GrovePi
The GrovePi can be programmed in Python, C, C#, Go, and NodeJS on the Raspberry Pi. Simply start with one of our [example projects](http://www.dexterindustries.com/GrovePi/projects-for-the-raspberry-pi/) or [example code](https://github.com/DexterInd/GrovePi/tree/master/Software).
The GrovePi uses an Arduino to interface between the Raspberry Pi and the Grove Sensors, and comes programmed with a standard firmware. The firmware can be rewritten from the Raspberry Pi.
### Getting Help
Need help? We [have a forum here where you can ask questions or make suggestions](http://www.dexterindustries.com/GrovePi/projects-for-the-raspberry-pi/).
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
See more at the [GrovePi Site](http://dexterindustries.com/GrovePi/)

View file

@ -0,0 +1,119 @@
#!/usr/bin/env python
'''
wifi_finder.py
Scan for open wifi networks! This is a portable wifi hotspot finder. See our project at www.dexterindustries.com/GrovePi for more information on turning this into a portable wifi hotspot finder.
Software Setup Notes:
* This example uses https://wifi.readthedocs.org/en/latest/wifi_command.html. Install with pip install wifi
* Wifi dongle must be on wlan0 ; Check this with the command "ifconfig" on the command line.
Hardware Setup Notes:
* Buzzer goes on port 8 of the GrovePi.
* LED Goes on port 4 of the GrovePi.
* The LCD goes on I2C-1. Check this with the command "sudo i2cdetect -y 1"
The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
'''
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
'''
from wifi import *
import time
import grovepi
from grove_rgb_lcd import *
## Connections
# LCD Goes on I2C-1
buzzer = 2 # Connect the Grove Buzzer to digital port D8
led = 3 # Connect the Grove LED to digital port D3
grovepi.pinMode(buzzer, "OUTPUT")
grovepi.pinMode(led, "OUTPUT")
def check_open_ssids():
open_ssids = []
for cell in Cell.all('wlan0'):
if cell.encrypted == False:
# print cell.ssid
open_ssids.append(cell.ssid)
return open_ssids
def alert_user():
# Buzz for 0.1 seconds
grovepi.digitalWrite(buzzer,1)
grovepi.digitalWrite(led,1) # Send HIGH to switch on LED
time.sleep(0.5)
# Don't buzz for 0.1 seconds
grovepi.digitalWrite(buzzer,0)
grovepi.digitalWrite(led,0) # Send LOW to switch off LED
time.sleep(0.5)
# Print the ssid name to the LCD, beep and turn the LED on and off.
def display_ssid(ssid):
alert_user()
string_out = "SSID Available: " + str(ssid)
try:
setText(string_out)
setRGB(0,128,64)
alert_user()
for c in range(0,255):
setRGB(c,255-c,0)
time.sleep(0.01)
time.sleep(3)
setRGB(0,0,0)
except:
print("Failed on something or other!")
try:
while True:
list_of_open = []
# 1). Test for any open ssids
list_of_open = check_open_ssids()
print(list_of_open)
# 2). If we find open ssids turn light and buzzer on, print to SSID.
for ssid in list_of_open:
display_ssid(ssid)
# 3). Look around ever 5 seconds.
time.sleep(5)
except:
pass
finally:
setText("")
setRGB(0,0,0)
grovepi.digitalWrite(buzzer,0)
grovepi.digitalWrite(led,0)

59
Projects/README.md Normal file
View file

@ -0,0 +1,59 @@
## **GrovePi Projects Readme**
GrovePi is an electronics board that you can connect to hundreds of different sensors, so you can program them to monitor, control, and automate devices in your life. [View Product Details here.](http://www.dexterindustries.com/grovepi/)
- **Advanced_RGB_LCD_TempAndHumidity**: Changes the color of the RGB color LCD depending on the temperature. (Works with the GrovePi starter kit)
- **Button_And_Buzzer**: The buzzer makes a sound when the button is pressed. (Works with the GrovePi starter kit)
- **home_temp_humi_display**: Shows the temperature and humidity on Grove I2C OLED.
- **Home_Weather_Display**: Shows the temperature and humidity on Grove RGB LCD. (Works with the GrovePi starter kit)
- **IOT**: Plots the data from various grove sensors on Xively. (Works with the GrovePi starter kit)
- **LED Fade**: Changed the brightness of a LED from the value read from a potentiometer.(Works with the GrovePi starter kit)
- **OLED_Weather Display**: Fetch the live weather data from the internet and print on the OLED display
- **OLED_Weather Station**: Get weather data from the internet and the DHT sensor and print on the OLED
- **Open_Wifi_Finder**: Finds open WiFi networks and prints on the Grove RGB LCD. (Works with the GrovePi starter kit)
- **rain_notifier**: Get rain data from the internet and blink a LED if it'g going to rain. (Works with the GrovePi starter kit)
- **Sensor_Twitter_Feed**: Get Sensor data from GrovePi sensors and post the data on twitter. (Works with the GrovePi starter kit)
- **tilt_buzzer**: Turn the buzzer on/off deping on the values read from the accelerometer
- **Ultrasonic_And_Relay**: Read the ultrasonic ranger and turn the relay on/off depending on the values read
- **Whos_at_the_Door**: Checks if someone is at the door, if there is someone then it takes a photo and mails it
- **CO2_sensor**: Read the data from the CO2 Sensor and print it in the terminal
See more at the [GrovePi Site](http://dexterindustries.com/GrovePi/)
## License
.
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,88 @@
#! /usr/local/bin/python
# This is an example of sending an e-mail with the Raspberry Pi. This is a very
# useful example, if you want to send an e-mail or alert on some hardware change!
# In this example we use a hotmail/outlook account. Settings may vary depending
# on the e-mail provider you are using.
#
# The GrovePi connects the Raspberry Pi and Grove sensors.
# You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example?
# Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
SMTPserver = 'smtp.live.com' # This is the SMTP server. In our example, we use Microsoft Outlook.
sender = 'dex@outlook.com' # This is your login email.
destination = ['dex@dexterindustries.com'] # This is the e-mail address you want to send an e-mail to.
# You can send to multiple e-mails. The e-mail address is a string.
USERNAME = "dex@outlook.com"
PASSWORD = "my_password"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
import sys
import os
import re
# from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
from smtplib import *
from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
from email.MIMEText import MIMEText
#
def send_email(content, destination, subject):
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
# timeout is critical here for long term health.
conn = SMTP(SMTPserver, port = 587, timeout = 60)
conn.ehlo()
conn.starttls()
conn.ehlo()
conn.login(USERNAME, PASSWORD)
conn.set_debuglevel(1)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.close()
except Exception as exc:
# sys.exit( "mail failed; %s" % str(exc) ) # give a error message
print("Mail failed; %s" % str(exc))
print("Moving on!")

View file

@ -0,0 +1,13 @@
#TWEET YOUR VALUES
This folder contains the code necessary to tweet your sensor values once a minute.
It requires python-twitter library which you can get by
**sudo pip install python-twitter**
Sensors used in this code are:
* light sensor on port A1
* sound sensor on port A0
* temperature and humidity sensor on port D2
* LED for visual feedback on port D3 (with PWM)

View file

@ -0,0 +1,93 @@
# Tweet the temperature, light, and sound levels with our Raspberry Pi
# http://www.dexterindustries.com/GrovePi/projects-for-the-raspberry-pi/raspberry-pi-twitter-sensor-feed/
# GrovePi + Sound Sensor + Light Sensor + Temperature Sensor + LED
# http://www.seeedstudio.com/wiki/Grove_-_Sound_Sensor
# http://www.seeedstudio.com/wiki/Grove_-_Light_Sensor
# http://www.seeedstudio.com/wiki/Grove_-_Temperature_and_Humidity_Sensor_Pro
# http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
'''
import twitter
import time
import grovepi
import math
# Connections
sound_sensor = 0 # port A0
light_sensor = 1 # port A1
temperature_sensor = 2 # port D2
led = 3 # port D3
intro_str = "DI Lab's"
# Connect to Twitter
api = twitter.Api(
consumer_key='YourKey',
consumer_secret='YourKey',
access_token_key='YourKey',
access_token_secret='YourKey'
)
grovepi.pinMode(led,"OUTPUT")
grovepi.analogWrite(led,255) #turn led to max to show readiness
while True:
# Error handling in case of problems communicating with the GrovePi
try:
# Get value from light sensor
light_intensity = grovepi.analogRead(light_sensor)
# Give PWM output to LED
grovepi.analogWrite(led,light_intensity/4)
# Get sound level
sound_level = grovepi.analogRead(sound_sensor)
time.sleep(0.5)
# Get value from temperature sensor
[t,h]=[0,0]
[t,h] = grovepi.dht(temperature_sensor,0)
# Post a tweet
out_str ="%s Temp: %d C, Humidity: %d, Light: %d, Sound: %d" %(intro_str,t,h,light_intensity/10,sound_level)
print (out_str)
api.PostUpdate(out_str)
except IOError:
print("Error")
except KeyboardInterrupt:
exit()
except Exception as e:
print("Duplicate Tweet or Twitter Refusal: {}".format(e))
time.sleep(60)

View file

@ -0,0 +1,15 @@
This project was created for the GrovePi0 as an example of a portable project
![alt text](http://32414320wji53mwwch1u68ce.wpengine.netdna-cdn.com/wp-content/uploads/2016/07/20160703_144803-1024x576.jpg "Pi on a Bike")
You can equip your bike with a GPS logger, which will take a photo every minute,
and stamp it with the GPS coordinates, and temperature/humidity data.
Project is documented at http://www.dexterindustries.com/projects/take-grovepizero-bike-trip/
You will need a Pizero with a Pi camera (it requires a special cable for the pizero),
you will need to run Cinch on your SD card
The GPS sensor goes into port RPISER
The temperature/humidity sensor goes into port D3
An optional LCD screen goes into one of the I2C ports.
You will also need to make a copy of the dextergps.py library into this folder.
You can find that file in **GrovePi/Software/Python/grove_gps/**

View file

@ -0,0 +1,186 @@
# -*- coding: utf-8 -*-
import grovepi
import grove_rgb_lcd as lcd
import dextergps
import time
import picamera
import atexit,sys
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime,timedelta
###############################################
@atexit.register
def cleanup():
print ("Cleanup")
try:
grovepi.digitalWrite(led,0)
lcd.setRGB(0,0,0)
lcd.setText("")
fobj.close()
except:
pass
###############################################
###############################################
# LED on D7 # only for big brother GrovePi
# DHT on D3
# LCD on I2C
# GPS on RPISER
###############################################
# Variables - adapt as needed
###############################################
photo_location = "/media/KINGSTON/"
logfile=photo_location+"trip.csv"
led = 7
dht_sensor_port = 3
dht_sensor_type = 0
temp = 0
hum = 0
use_lcd = True # if lcd display is used for feedback
overlay_txt_ypos = 440
#degree_sign= u'\N{DEGREE SIGN}'
###################################
def display(in_str,bgcol=(255,255,255),in_lcd=use_lcd):
print(in_str)
try:
if in_lcd:
lcd.setRGB(bgcol[0],bgcol[1],bgcol[2])
lcd.setText(in_str)
except KeyboardInterrupt:
sys.exit()
except:
pass
def format_coord(in_lat, in_lon):
'''
TBD:
takes in a latitude and a longitude in
returns a nicely formatted string in degrees minutes seconds
'''
out_lat = in_lat
out_lon = in_lon
return (out_lat, out_lon)
def handlegpsdata():
'''
Read GPS
if we get valid data, blink the LED, return True
and save the info
else return False
'''
try:
g.read()
if g.lat != -1.0:
display( "valid GPS data",in_lcd=False)
return True
except KeyboardInterrupt:
sys.exit()
except:
pass
display( "invalid GPS data",in_lcd=True)
return False
def handledhtdata():
global temp, hum
[ temp, hum ] = grovepi.dht(dht_sensor_port,dht_sensor_type)
if temp != -1 and hum != -1:
display("temp = {}C humidity={}%".format(temp,hum),(0,255,0))
else:
display("Error reading DTH sensor")
def logtofile():
try:
fobj = open( logfile,"a")
fobj.write("#{:3d},{:.4f}, {:.4f}, {}, {:.2f}, {:.2f}%\n".format(
count,g.latitude,g.longitude, g.timestamp, temp,hum))
fobj.flush()
fobj.close()
except KeyboardInterrupt:
sys.exit()
except:
display("Error writing to USB Drive",in_lcd=True)
time.sleep(3)
# handle time. Convert according to timezone
# convert timestamp to struct_time
#my_time = time.strptime(g.timestamp,"%H%M%S.000")
#print my_time
def savephoto():
try:
photoname = photo_location+str(g.timestamp)+".jpg"
display( photoname,in_lcd=False)
cam.capture(photoname)
grovepi.digitalWrite(led,0)
time.sleep(1)
grovepi.digitalWrite(led,255)
# Get ready to watermark the image
# 1. grab the image
base = Image.open(photoname).convert('RGBA')
# 2. create overlay
txt = Image.new('RGBA', base.size, (255,255,255,50))
# get a drawing context
d = ImageDraw.Draw(txt)
# 3. prepare text to overlay
d.text((20,overlay_txt_ypos),
"#{}: lon: {:.4f} lat: {:.4f} temp: {:.1f}C humidity: {:.1f}%".format(
count,g.longitude,g.latitude, temp,hum), font=fnt, fill=(255,255,255,255))
# 4. do composite and save
out = Image.alpha_composite(base, txt)
out.save(photoname)
grovepi.digitalWrite(led,255)
except KeyboardInterrupt:
sys.exit()
except:
display("Error saving photo",in_lcd=True)
time.sleep(3)
###############################################################
try:
display("Starting up...",in_lcd=True)
grovepi.digitalWrite(led,0)
except:
pass
# check camera
try:
g = grovegps.GROVEGPS()
cam = picamera.PiCamera(sensor_mode=3)
display("Camera working",in_lcd=True)
except:
display("Camera NOT working!!",in_lcd=True)
# get a font
fnt = ImageFont.truetype('/usr/share/fonts/truetype/roboto/Roboto-Thin.ttf', 20)
count = 0
while True:
if handlegpsdata():
count += 1
grovepi.digitalWrite(led,255)
display("{} {}, {} {}, {}, {}".format(g.lat,g.NS,g.lon,g.EW, g.latitude,g.longitude),
in_lcd=False)
handledhtdata()
savephoto()
logtofile()
time.sleep(5)
display("lon: {:11.7f}lat: {:11.7f}".format(g.longitude,g.latitude),(0,0,255))
time.sleep(5)
grovepi.digitalWrite(led,0)

View file

@ -0,0 +1,58 @@
# GrovePi + Grove Ultrasonic Ranger
# http://www.seeedstudio.com/wiki/Grove_-_Ultrasonic_Ranger
# This is an project using the Grove Ultrasonic Ranger and Relay from GrovePi start kit
#
# In this project, the ultrasonic can figure out the distance of object in front,
# when object close to it within 10cm, the relay will turn on
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
'''
from grovepi import *
# Connect the Grove Ultrasonic Ranger to digital port D4
# SIG,NC,VCC,GND
ultrasonic_ranger = 4
Relay_pin = 2
pinMode(Relay_pin,"OUTPUT")
while True:
try:
# Read distance value from Ultrasonic
distant = ultrasonicRead(ultrasonic_ranger)
print(distant,'cm')
if distant <= 10:
digitalWrite(Relay_pin,1)
else:
digitalWrite(Relay_pin,0)
except TypeError:
print("Error")
except IOError:
print("Error")

View file

@ -0,0 +1,108 @@
# Detects motion, triggers Buzzer, LED and Relay, takes picture from RPi Camera, sends as attachment via Gmail
# http://www.dexterindustries.com/GrovePi/projects-for-the-raspberry-pi/whos-at-the-door/
# GrovePi + Ultrasonic Ranger + Buzzer + Switch + Relay + LED + RPi Camera
# http://www.seeedstudio.com/wiki/Grove_-_Ultrasonic_Ranger
# http://www.seeedstudio.com/wiki/Grove_-_Buzzer
# http://www.seeedstudio.com/wiki/Grove_-_Switch(P)
# http://www.seeedstudio.com/wiki/Grove_-_Solid_State_Relay
# http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit
# http://www.raspberrypi.org/camera
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
'''
import grovepi
# Import smtplib for the actual sending function
import smtplib, string, subprocess, time
# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from subprocess import call
print("System Working")
switch = 4
led_status = 3
relay = 2
buzzer = 5
SMTP_USERNAME = '' # Mail id of the sender
SMTP_PASSWORD = '' # Pasword of the sender
SMTP_RECIPIENT = '' # Mail id of the reciever
SMTP_SERVER = 'smtp.gmail.com' # Address of the SMTP server
SSL_PORT = 465
while True: # in case of IO error, restart
try:
grovepi.pinMode(switch,"INPUT")
while True:
if grovepi.digitalRead(switch) == 1: # If the system is ON
if grovepi.ultrasonicRead() < 100: # If a person walks through the door
print("Welcome")
grovepi.analogWrite(buzzer,100) # Make a sound on the Buzzer
time.sleep(.5)
grovepi.analogWrite(buzzer,0) # Turn off the Buzzer
grovepi.digitalWrite(led_status,1) # Turn on the status LED to indicate that someone has arrived
grovepi.digitalWrite(relay,1) # turn on the Relay to activate an electrical device
# Take a picture from the Raspberry Pi camera
call (["raspistill -o i1.jpg -w 640 -h 480 -t 0"], shell=True)
print("Image Shot")
p = subprocess.Popen(["runlevel"], stdout=subprocess.PIPE)
out, err=p.communicate() # Connect to the mail server
if out[2] == '0':
print('Halt detected')
exit(0)
if out [2] == '6':
print('Shutdown detected')
exit(0)
print("Connected to mail")
# Create the container (outer) email message
TO = SMTP_RECIPIENT
FROM = SMTP_USERNAME
msg = MIMEMultipart()
msg.preamble = 'Rpi Sends image'
# Attach the image
fp = open('i1.jpg', 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)
# Send the email via Gmail
print("Sending the mail")
server = smtplib.SMTP_SSL(SMTP_SERVER, SSL_PORT)
server.login(SMTP_USERNAME, SMTP_PASSWORD)
server.sendmail(FROM, [TO], msg.as_string())
server.quit()
print("Mail sent")
grovepi.digitalWrite(led_status,0) # Turn off the LED
grovepi.digitalWrite(relay,0) # Turn off the Relay
except IOError:
print("Error")

View file

@ -0,0 +1,61 @@
# home_temp_hum_display.py.py
#
# This is an project for using the Grove OLED Display and the Grove DHT Sensor from the GrovePi starter kit
#
# In this project, the Temperature and humidity from the DHT sensor is printed on the DHT sensor
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
from grovepi import *
from grove_oled import *
dht_sensor_port = 7 # Connect the DHt sensor to port 7
#Start and initialize the OLED
oled_init()
oled_clearDisplay()
oled_setNormalDisplay()
oled_setVerticalMode()
time.sleep(.1)
while True:
try:
[ temp,hum ] = dht(dht_sensor_port,1) #Get the temperature and Humidity from the DHT sensor
print("temp =", temp, "C\thumidity =", hum,"%")
t = str(temp)
h = str(hum)
oled_setTextXY(0,1) #Print "WEATHER" at line 1
oled_putString("WEATHER")
oled_setTextXY(2,0) #Print "TEMP" and the temperature in line 3
oled_putString("Temp:")
oled_putString(t+'C')
oled_setTextXY(3,0) #Print "HUM :" and the humidity in line 4
oled_putString("Hum :")
oled_putString(h+"%")
except (IOError,TypeError) as e:
print("Error")

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View file

@ -0,0 +1,125 @@
package grovepi.buttonrotarydemo;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove
* Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import grovepi.observer.ButtonInvoker;
import grovepi.observer.ButtonPressDistinguisher;
import grovepi.observer.DigitalInputReader;
import grovepi.observer.RotaryInvoker;
import grovepi.observer.RotaryAngleDeterminer;
import grovepi.observer.AnalogInputReader;
/**
* ButtonRotaryDemo
* This GrovePi sensor demonstration is part of a coursework project
* for CS505 Design Patterns, at Central Connecticut State University,
* Fall 2017, with Dr. Chad Williams.
*
* The main method creates a BottonInvoker object and begins listening for button events:
* singlePress, doublePress, and longPress. Each of these events will invoke methods
* implemented in SampleButtonInvoker. Write your own class that implements ButtonInvoker interface.
* (SampleButtonInvoker is quite boring)
*
* @see SampleButtonInvoker
* @see grovepi.observer.ButtonInvoker
*
* The main method also creates a RotaryInvoker object and begins reading the
* angle of the rotary sensor. Each time the angle is read, the method
* invokeWithDegrees(degrees) of SampleRotaryInvoker is executed. Write your own class that
* implements RotaryInvoker interface. (SampleRotaryInvoker is even more boring)
*
* @see SampleRotaryInvoker
* @see grovepi.observer.RotaryInvoker
*
* @author James Luczynski
* @author Jeff Blankenship
*/
public class ButtonRotaryDemo{
/**
* @param args the command line arguments
* @throws java.lang.InterruptedException
* @throws java.lang.Exception
*/
public static void main(String[] args){
//button can be connected to D2-D8.
int buttonPin = 6;
//rotary can be connected to A0, A1, A2
int rotaryPin = 2;
//instantiate a ButtonInvoker
SampleButtonInvoker invoker = new SampleButtonInvoker();
initButton(invoker, buttonPin);
//instantiate a RotaryInvoker
SampleRotaryInvoker rotaryInvoker = new SampleRotaryInvoker();
initRotary(rotaryInvoker,rotaryPin);
}
/**
* Initializes DigitalInputReader and ButtonPressDistinguisher objects.
* Button presses will invoke the methods defined in the ButtonInvoker parameter.
* @param invoker any object of a class that implements ButtonInvoker interface
* @param pin the GrovePi port number the button sensor is plugged into
*/
public static void initButton(ButtonInvoker invoker, int pin) {
try {
DigitalInputReader buttonReader = new DigitalInputReader(pin);
ButtonPressDistinguisher distinguisher = new ButtonPressDistinguisher(invoker);
buttonReader.addObserver(distinguisher);
buttonReader.startReading();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* Initializes AnalogInputReader and RotaryAngleDeterminer objects.
* Rotations of the rotary sensor will invoke the method defined in the RotaryInvoker parameter.
* @param invoker any object of a class that implements RotaryInvoker interface
* @param pin the GrovePi port number the rotary sensor is plugged into
*/
public static void initRotary(RotaryInvoker invoker, int pin){
try {
AnalogInputReader rotaryReader = new AnalogInputReader(pin);
RotaryAngleDeterminer determiner = new RotaryAngleDeterminer(invoker);
rotaryReader.addObserver(determiner);
rotaryReader.startReading();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,75 @@
package grovepi.buttonrotarydemo;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import grovepi.observer.ButtonInvoker;
/**
* ButtonInvoker Sample.
* This GrovePi sensor demonstration is part of a coursework project
* for CS505 Design Patterns, at Central Connecticut State University,
* Fall 2017, with Dr. Chad Williams.
*
* ButtonInvokerdemo realizes the ButtonInvoker interface and provides
* a sample implementation for each of its methods.
*
* You can write your own class that implements ButtonInvoker interface (this one is very boring)
* to determine what happens for each different press
*
* @see grovepi.observer.ButtonInvoker
* @author James Luczynski
* @author Jeff Blankenship
*/
public class SampleButtonInvoker implements ButtonInvoker{
@Override
public void singlePress(){
//singlePress code
System.out.println("Single Press");
}
@Override
public void doublePress(){
//doublePress code
System.out.println("Double Press");
}
@Override
public void longPress(){
//longPress code
System.out.println("Long Press");
}
}

View file

@ -0,0 +1,74 @@
package grovepi.buttonrotarydemo;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import grovepi.observer.RotaryInvoker;
import java.text.DecimalFormat;
/**
* This GrovePi sensor demonstration is part of a coursework project
* for CS505 Design Patterns, at Central Connecticut State University,
* Fall 2017, with Dr. Chad Williams.
*
* This class provides a sample implementation of the RotaryInvoker interface.
*
* You can write your own class that implements RotaryInvoker interface (this one is very boring)
* to determine what happens on based on the angle of the rotary sensor.
*
* @see grovepi.observer.ButtonInvoker
* @author James Luczynski
* @author Jeff Blankenship
*/
public class SampleRotaryInvoker implements RotaryInvoker{
/**
* Angle from the previous reading of the rotary sensor.
* NOTE: the rotary sensor has only 300 degrees of rotation.
*/
private double degrees;
/**
* A somewhat arbitrary number. If the difference in degrees from the previous
* reading and the most recent reading is less than the tolerance, don't do anything.
*/
private double tolerance = 4;
/**
* Prints current angle of rotary sensor if different from last reading
* @param degrees most recent reading of rotary sensor angle
*/
public void invokeWithDegrees(double degrees){
if (Math.abs(this.degrees - degrees) > tolerance)
{
this.degrees = degrees;
DecimalFormat df = new DecimalFormat("###.#");
String output = df.format(this.degrees);
System.out.println("Rotary sensor position (degrees): " + output);
}
}
}

View file

@ -0,0 +1,89 @@
package grovepi.observer;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import com.dexterind.grovepi.sensors.base.AnalogSensor;
import java.io.IOException;
/**
* An instance of this class reads sensor data from a GrovePi analog sensor and
* updates an observer with this data.
*
* @author James Luczynski
* @author Jeff Blankenship
*/
public class AnalogInputReader extends InputSensorReader implements Runnable{
private AnalogSensor sensor;
/**
* Constructor
* @param pin the GrovePi port number the sensor is plugged into
* @throws IOException
* @throws InterruptedException
* @throws Exception
*/
public AnalogInputReader(int pin) throws InterruptedException, Exception{
sensor = new AnalogSensor(pin, 4);
readDelay = 250;
}
/**
* Constructor
* @param pin the GrovePi port number the sensor is plugged into
* @param bufferLength length of byte[] to be read from the sensor
* @throws InterruptedException
* @throws Exception
*/
public AnalogInputReader(int pin, int bufferLength) throws InterruptedException, Exception{
sensor = new AnalogSensor(pin, bufferLength);
readDelay = 250;
}
/**
* Reads the values of the sensor, and notifies this instance's observers
* of these new values
*/
public void run() {
try {
byte[] newState = sensor.readBytes();
state = newState;
notifyObservers(state);
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Begins reading sensor values
*/
public void startReading(){
super.startReading(this);
}
}

View file

@ -0,0 +1,51 @@
package grovepi.observer;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Declares the methods that are called when ButtonPressDistinguisher identifies
* a single, double, and long press respectively. Write your own class that implements
* this interface to determine what specific behavior should occur for each specific
* button press.
* @see ButtonPressDistinguisher
* @see SamplebuttonInvoker
*
* @author James Luczynski
* @author Jeff Blankenship
*/
public interface ButtonInvoker {
public abstract void singlePress();
public abstract void doublePress();
public abstract void longPress();
}

View file

@ -0,0 +1,138 @@
package grovepi.observer;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* An instance of this class recieves updates containing sensor events, analyzes
* the timing of these events and invokes the appropriate method on this instance's
* ButtonInvoker object. The ButtonInvoker object can be changed at runtime
* to get different behaviour triggered by button presses.
*
* @see ButtonInvoker
* @author James Luczynski
* @author Jeff Blankenship
*/
public class ButtonPressDistinguisher implements InputSensorObserver, Runnable{
private boolean buttonDown = false;
private boolean waitingForSecondPress = false;
private long lastPress;
private long lastRelease;
private Thread thread = new Thread(this);
private int longPressTimeInterval = 1000;
private int doublePressTimeInterval = 1000;
private ButtonInvoker invoker;
/**
* Constructor
* @see ButtonInvoker
* @param invoker
*/
public ButtonPressDistinguisher(ButtonInvoker invoker){
this.invoker = invoker;
}
/**
* Changes this instance's buttonInvoker object to the one in the argument provided.
* @param invoker
*/
public void setInvoker(ButtonInvoker invoker){
this.invoker = invoker;
}
/**
* Analyzes the timing of button events and determines if a single, double or long press
* has occurred. It then invokes the associated method on this instance's ButtonInvoker object
* @param b the byte[] read from the button sensor
*/
public void update(byte[] b){
long timeOfAction = System.currentTimeMillis();
buttonDown = b[0] == 1 ? true : false;
if (buttonDown) { //if this update results from button being pressed down.
lastPress = timeOfAction;
} else{ //button was just released
lastRelease = timeOfAction;
if (lastRelease - lastPress > longPressTimeInterval){
invoker.longPress();
}
else{
if (thread.isAlive()){ //if thread still waiting, it's a double press
invoker.doublePress();
waitingForSecondPress = false;
}else{ //this press is not second press of a double press, must wait
waitingForSecondPress = true;
thread = new Thread(this);
thread.start();
}
}
}
}
public void run(){
try{
Thread.sleep(doublePressTimeInterval); //after "enough" time has elapsed,
if(waitingForSecondPress){ //and still waiting for second press, then it's a single press
invoker.singlePress();
waitingForSecondPress = false;
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
/**
* Changes the time interval that two button presses must occur within, in
* in order to be considered a double press
* @param interval the new double press interval in milliseconds
*/
public void setDoublePressInterval(int interval){
doublePressTimeInterval = interval;
}
/**
* @return the current double press time interval in milliseconds
*/
public int getDoublePressInterval(){
return doublePressTimeInterval;
}
/**
* Changes the length of time (in milliseconds) that the button must be
* continuously pressed down for in order for that press to be considered a long press
* @param interval the new long press interval in milliseconds
*/
public void setLongPressInterval(int interval){
longPressTimeInterval = interval;
}
/**
* @return the current long press time interval in milliseconds.
*/
public int getLongPressInterval(){
return longPressTimeInterval;
}
}

View file

@ -0,0 +1,79 @@
package grovepi.observer;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import com.dexterind.grovepi.sensors.base.DigitalSensor;
import java.io.IOException;
/**
* An instance of this class reads sensor data from a GrovePi digital sensor and
* updates an observer with this data.
*
* @author James Luczynski
* @author Jeff Blankenship
*/
public class DigitalInputReader extends InputSensorReader implements Runnable{
private DigitalSensor sensor;
/**
* Constructor
* @param pin the GrovePi port number the sensor is plugged into
* @throws IOException
* @throws InterruptedException
* @throws Exception
*/
public DigitalInputReader(int pin) throws IOException, InterruptedException, Exception{
this.pin = pin;
sensor = new DigitalSensor(pin);
readDelay = 125;
}
/**
* Reads the values of the sensor, and updates this object's observers
* if the values have changed from the last reading.
*/
public void run() {
try {
byte[] newState = sensor.readBytes();
if (!equals(state, newState)){
state = newState;
notifyObservers(state);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Begins reading sensor values.
*/
public void startReading(){
super.startReading(this);
}
}

View file

@ -0,0 +1,50 @@
package grovepi.observer;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Provides the interface that all concrete InputSensorObservers must implement.
* InputSensorObserver objects will receive updates from InputSensorReader objects.
* Concrete subclasses should process and analyze the data from these updates.
*
* @author James Luczynski
* @author Jeff Blankenship
*/
public interface InputSensorObserver {
/**
* Concrete implementations of this method should include a way to process
* the data in the byte[]
* @param b the byte[] read from a sensor
*/
public abstract void update(byte[] b);
}

View file

@ -0,0 +1,133 @@
package grovepi.observer;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
*
*
* @author James Luczynski
* @author Jeff Blankenship
* @author Chad Williams
*/
public abstract class InputSensorReader {
/**
* Time in milliseconds between consecutive readings of sensor values
* Each subclass reinitialize this differently in their constructors
*/
protected int readDelay = 100;
/**
* The pin number on the GrovePi that this object reads from
*/
protected int pin;
/**
* The list of observers that will be updated with the read values
*/
protected ArrayList<InputSensorObserver> observers = new ArrayList();
/**
* Responsible for making intermittent readings of sensor values
*/
private ScheduledExecutorService exec;
/**
* contains the most recent values read from the sensor
*/
protected byte[] state = {0};
/**
* Adds an InputSensorObserver object to the list of observers
* @param observer the InputSensorObserver object to be added
*/
public void addObserver(InputSensorObserver observer){
observers.add(observer);
}
/**
* Removes an InputSensorObserver object to the list of observers
* @param observer the InputSensorObserver object to be removed
*/
public void removeObserver(InputSensorObserver observer){
observers.remove(observer);
}
public ArrayList getObservers(){
return observers;
}
/**
* Begins reading the values of the sensor.
* @param r
*/
protected void startReading(Runnable r){
exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(r, 0, readDelay, TimeUnit.MILLISECONDS);
}
/**
* Stops the intermittent readings of the sensor.
*/
public void stopReading(){
if (exec != null)
exec.shutdown();
}
/**
* Changes the time interval between consecutive reads to the sensor
* @param delay the new time interval in milliseconds
*/
public void setDelay(int delay){
readDelay = delay;
}
/**
* Notifies all observers of this object of the newly read values from the sensor
* @param b
*/
public void notifyObservers(byte[] b){
for (InputSensorObserver obs : observers)
obs.update(b);
}
/**
* @param b1
* @param b2
* @return true if both byte[] are equal, false otherwise
*/
protected static boolean equals(byte[] b1, byte[] b2){
if (b1.length != b2.length)
return false;
else{
for (int i = 0; i < b1.length; i++)
if (b1[i] != b2[i])
return false;
}
return true;
}
}

View file

@ -0,0 +1,114 @@
package grovepi.observer;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* RotaryAngleDeterminer.
* This GrovePi sensor demonstration is part of a coursework project
* for CS505 Design Patterns, at Central Connecticut State University,
* Fall 2017, with Dr. Chad Williams.
*
* @author James Luczynski
* @author Jeff Blankenship
* @author Chad Williams
*/
public class RotaryAngleDeterminer implements InputSensorObserver{
/**
* Reference voltage of ADC is 5v
*/
private static final double ADC_REF = 5;
/**
* Vcc of the grove interface is 5 volts
*/
private static final double GROVE_VCC = 5;
/**
* Grove rotary sensor has only 300 degrees of rotation
*/
private static final double FULL_ANGLE = 300;
private RotaryInvoker invoker;
/**
* Constructor
* @see RotaryInvoker
* @param invoker
*/
public RotaryAngleDeterminer(RotaryInvoker invoker){
this.invoker = invoker;
}
/**
* Changes this instance's rotaryInvoker object to the one in the argument provided.
* @param invoker
*/
public void setInvoker(RotaryInvoker invoker){
this.invoker = invoker;
}
/**
* Computes the angle in degrees from the parameter b,
* Invokes this instance's RotaryInvoker invokeWithDegrees(double) method
* @see RotaryInvoker
* @param b
*/
public void update(byte[] b) {
double degrees = getDegrees(b);
if (inRange(degrees))
invoker.invokeWithDegrees(degrees);
}
/**
* Computes the angle in degrees from the byte[] b
* @param b byte[] read from the rotary sensor
* @return angle in degrees
*/
private double getDegrees(byte[] b){
int[] v = unsign(b);
double sensorValue = (v[1]*256) + v[2];
double voltage = sensorValue * ADC_REF / 1023;
double degrees = voltage * FULL_ANGLE / GROVE_VCC;
return degrees;
}
private int[] unsign(byte[] b) {
int[] v = new int[b.length];
for (int i = 0; i < b.length; i++)
v[i] = unsign(b[i]);
return v;
}
private int unsign(byte b) {
return b & 0xFF;
}
private boolean inRange(double degrees){
return (0 <= degrees && degrees <= FULL_ANGLE);
}
}

View file

@ -0,0 +1,49 @@
package grovepi.observer;
/*
* **********************************************************************
* PROJECT : GrovePi Java Library
*
* This file is part of the GrovePi Java Library project. More information about
* this project can be found here: https://github.com/DexterInd/GrovePi
* **********************************************************************
*
* ## License
*
* The MIT License (MIT)
* GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Declares the methods that are called when RotaryAngleDeterminer receives
* an update containing the current angle of the rotary sensor.
* You can write your own class that implements
* this interface to determine what specific behavior should occur on these updates
*
* @see RotaryAngleDeterminer
* @see SampleRotaryInvoker
*
* @author James Luczynski
* @author Jeff Blankenship
* @author Chad Williams
*/
public interface RotaryInvoker {
public abstract void invokeWithDegrees(double degrees);
}

View file

@ -0,0 +1,98 @@
### GrovePi sensors implemented using Java
This project is an example of how GrovePi libraries can be used in a Java application which interacts with GrovePi sensors, specifically the button and rotary used in this project. The GrovePi.observer package has been written in a way to provide a framework where these classes can be extended to use other sensors as needed.
### ButtonRotaryDemo
ButtonRotaryDemo provides an example of a client class interacting with the observer package.
For each button or rotary sensor that is desired, the developer must implement an invoker interface (either implements ButtonInvoker or implements RotaryInvoker). Within the newly created class include the code for the action desired for any of the button/rotary events.
Invokers
* **SamplebuttonInvoker**: Provides specific code to be executed when a single, double, or long press is invoked. In this example it simply prints a message to the console.
* **SampleRotaryInvoker**: Provides code to be executed when a change is detected in the position of the rotary sensor. In this example a filter is applied such that minimum difference of SampleRotaryInvoker.tolerance is required to trigger a display. Also, the output is formatted for single decimal place display.
Once an invoker is implemented, the next step is to code a driver that uses the invoker. In this example,
**ButtonRotaryDemo.java**: Instantiates invokers, assigns invokers to sensors and pins and starts reading the sensors.
### Deploying to your machine
This project was devoloped using NetBeans IDE 8.2. Only the java files have been included in the repository to allow users to compile them as projects in any developement environment.
Specifically for NetBeans, the process to create and run this as a project is as follows:
1. Clone a local copy of the repository.
2. Create a new project in NetBeans: File-> New Project, Java, Java Application.
3. Within the "Source Packages" folder of the newly created project, copy the folders
~\GrovePi\Projects\java\ButtonRotaryObserver\Project\grovepi\buttonrotarydemo
~\GrovePi\Projects\java\ButtonRotaryObserver\Project\grovepi\observer
4. The project uses the other GrovePi packages through jar files. The NetBeans project must be pointed to the correct jar files.
a. Right click the project name and select "Properties".
b. In the Categories tree on the lest, select "Libraries".
c. Click "Add JAR/Folder"
d. Navigate to ~\GrovePi\Projects\java\ButtonRotaryObserver\Project\grovepi\observer and select each of the jar files there, grovepi.jar and pi4j.jar. *Note: This step must be repeated after moving the project to a different platform (ie moving it to the pi) due to different file structures.*
e. Click OK to accept changes.
5. Run the file ButtonRotaryDemo.
### Package grovepi.observer
This package provides the tools used to create the invokers.
* **InputSensorReader**: Provides a common set of control methods and class variables for subclasses.
* **DigitalInputReader (extends InputSensorReader)**: Reads sensor data from a GrovePi digital sensor and updates an observer with this data.
* **AnalogInputReader (extends InputSensorReader)**: An instance of this class reads sensor data from a GrovePi analog sensor and updates an observer with this data.
* **InputSensorObserver**: Provides the interface that all concrete InputSensorObservers must implement.
* **ButtonPressDistinguisher (implements InputSensorObserver)**: Receives updates containing sensor events, analyzes the timing of these events and invokes the appropriate method on this instance's ButtonInvoker object.
* **RotaryAngleDeterminer (implements InputSensorObserver)**: Determines and reports the angular position of the rotary angle sensor.
* **Interfaces**:
* **ButtonInvoker**: Declares the methods that are called when ButtonPressDistinguisher identifies a single, double, and long press respectively.
* **RotaryInvoker**: Declares a method to call when RotaryAngleDenterminer is updated.
This package uses the Observer design pattern, and can be used to easily incorporate other input sensors into your project. Simply write a class that implements the InputSensorObserver interface and includes a way of processing the data read from the sensor.
### Credits
This GrovePi sensor demonstration is an extension of coursework for CS505 Design Patterns at Central Connecticut State University,
Fall 2017, with Dr. Chad Williams.
Interested in Computer Science at CCSU?: http://www.ccsu.edu/cs/
@author James Luczynski
@author Jeff Blankenship
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,130 @@
#!/usr/bin/env python
#
# GrovePi Project for a Plant monitoring project.
# * Reads the data from moisture, light, temperature and humidity sensor
# and takes pictures from the Pi camera periodically and logs them
# * Sensor Connections on the GrovePi:
# -> Grove Moisture sensor - Port A1
# -> Grove light sensor - Port A2
# -> Grove DHT sensors - Port D4
#
# NOTE:
# * Make sure that the Pi camera is enabled and works. Directions here: https://www.raspberrypi.org/help/camera-module-setup/
#
# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
#
# Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import time
import grovepi
import subprocess
import math
#analog sensor port number
mositure_sensor = 1
light_sensor = 2
#digital sensor
temp_himidity_sensor = 4
#temp_himidity_sensor type
# grove starter kit comes with the bluew sensor
blue=0
white=1
#############
#test timings
time_for_sensor = 4 # 4 seconds
time_for_picture = 12 # 12 seconds
# final
# time_for_sensor = 1*60*60 #1hr
# time_for_picture = 8*60*60 #8hr
time_to_sleep = 1
log_file="plant_monitor_log.csv"
#Read the data from the sensors
def read_sensor():
try:
moisture=grovepi.analogRead(mositure_sensor)
light=grovepi.analogRead(light_sensor)
[temp,humidity] = grovepi.dht(temp_himidity_sensor,white)
#Return -1 in case of bad temp/humidity sensor reading
if math.isnan(temp) or math.isnan(humidity): #temp/humidity sensor sometimes gives nan
return [-1,-1,-1,-1]
return [moisture,light,temp,humidity]
#Return -1 in case of sensor error
except IOError as TypeError:
return [-1,-1,-1,-1]
#Take a picture with the current time using the Raspberry Pi camera. Save it in the same folder
def take_picture():
try:
cmd="raspistill -t 1 -o plant_monitor_"+str(time.strftime("%Y_%m_%d__%H_%M_%S"))+".jpg"
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
print("Picture taken\n------------>\n")
except:
print("Camera problem,please check the camera connections and settings")
#Save the initial time, we will use this to find out when it is time to take a picture or save a reading
last_read_sensor=last_pic_time= int(time.time())
while True:
curr_time_sec=int(time.time())
# If it is time to take the sensor reading
if curr_time_sec-last_read_sensor>time_for_sensor:
[moisture,light,temp,humidity]=read_sensor()
# If any reading is a bad reading, skip the loop and try again
if moisture==-1:
print("Bad reading")
time.sleep(1)
continue
curr_time = time.strftime("%Y-%m-%d:%H-%M-%S")
print(("Time:%s\nMoisture: %d\nLight: %d\nTemp: %.2f\nHumidity:%.2f %%\n" %(curr_time,moisture,light,temp,humidity)))
# Save the sensor reading to the CSV file
f=open(log_file,'a')
f.write("%s,%d,%d,%.2f,%.2f;\n" %(curr_time,moisture,light,temp,humidity))
f.close()
#Update the last read time
last_read_sensor=curr_time_sec
# If it is time to take the picture
if curr_time_sec-last_pic_time>time_for_picture:
take_picture()
last_pic_time=curr_time_sec
#Slow down the loop
time.sleep(time_to_sleep)

View file

@ -0,0 +1,37 @@
## **Rain Notifier**
This is an project that uses the Grove LED attached to an umbrella to remind people to take their umbrella if it's raining or going to rain. To find out the weather outside this project uses the Zip code for the location and the Wunderground API to find the weather.
### How to use
Connect an LED to Port 7 which can be used as an indicator for the rain.
Get your API key from Wunderground and add it to the program
Add the zip code of your location to the program.
Run the program to fetch the weather data.
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN

View file

@ -0,0 +1,193 @@
# rain_notifier.py
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
'''
# This is a project that uses the Grove LED attached to an umbrella to remind
# people to take their umbrella if it's raining or going to rain that day.
#
# You will need to modify the first few lines for this project work for you.
# Fee free to modify the rest of the program to make it
# behave the way you want it to.
#
# Enter your zip code (or Postal Code) on the following line
# (leave the name 'zip' as is, even if you have a postal code. )
zipcode = 'YOUR_ZIP_CODE'
# once you have gotten an API Key from Wunderground (see tutorial),
# pleave provide it here
# Wunderground API Key
api_key = 'YOUR_WUNDERGROUND_API_KEY'
# if you wish to use two LEDs, provide the port number of the second LED
# The second LED is the one that will indicate
# if there's no rain in the weather prediction
# With two LEDs, one will always be on.
# if you do not want a second LED, set this to -1
clearled = 8
############################################################################
# no modifications are required after this
# however the next few lines can be tweaked easily
############################################################################
# in case of rain, do you want the LED to blink
# to catch your attention more?
# set to True for blinking, set to False for a steady warning
BLINK = True
# this is the delay between each polling of Wunderground.
# It's set to poll once every 5 minutes
# you may prefer a faster polling.
# the Wunderground free account does set a limit
DELAY = 5*60 # in seconds
# Do you prefer to work in metric or imperial?
# set METRIC to 1 to use the metric system
# set METRIC to 0 to use imperial system
METRIC = 1
# rain threshold: what's your safety zone?
# before you need an umbrella
# if METRIC is set to 1, this will be in millimeters
# if METRIC is set to 0, this will be in inches
RAIN_THRESHOLD = 1
# Pin for the rain LED on the umbrella
rainled = 7
############################################################################
# nothing needs to be modified after this
# if you are familiar with Python, feel free to change anything to improve this
# we welcome additions and suggestions
############################################################################
import urllib2
import json
from grovepi import *
import time
import sys
def clear_led(status):
""" change clear sky LED status """
if clearled > -1:
digitalWrite(clearled, status)
def assign_rain(status, blink):
""" controls the LEDs status
Arguments:
status: True if it will be raining
False if there's no rain in the forecast
blink: True if the rain led should blink when on
False if the rain led does not need blinking
no return value
"""
if status is True: # there will be rain
clear_led(0) # Turn off the CLEAR LED on the umbrella
# Light the RAIN LED on the umbrella
# first check if it needs to be blinking
if blink is True:
led_blink(DELAY) # no sleep required here
else:
digitalWrite(rainled, 1)
time.sleep(DELAY)
else: # no rain in forecast
# turn off the RAIN LED on the umbrella
digitalWrite(rainled, 0)
# Turn on the CLEAR LED on the umbrella
clear_led(1)
time.sleep(DELAY)
def led_blink(blinkdelay):
""" forces the rain LED to blink
rain LED will blink at a rate of 0.2 secs on, and 0.2 secs off
it will blink for a duration set by blinkdelay
no additional sleep() is required as it's incorporated in the blinking
"""
count = 0.0
blinkrate = 0.4
while count < float(blinkdelay):
digitalWrite(rainled, 1)
time.sleep(blinkrate)
digitalWrite(rainled, 0)
time.sleep(blinkrate)
count += (2*blinkrate)
#########################################################################
# Zip code of location
url = 'http://api.wunderground.com/api/' + api_key
url = url + '/geolookup/conditions/q/' + zipcode + '.json'
pinMode(rainled, "OUTPUT")
if clearled > -1:
pinMode(clearled, "OUTPUT")
if len(sys.argv) > 1 and sys.argv[1] == 'test':
try:
clear_led(1)
led_blink(5)
clear_led(0)
except KeyboardInterrupt:
digitalWrite(clearled, 0)
digitalWrite(rainled, 0)
quit()
try:
while True:
f = urllib2.urlopen(url)
json_string = f.read()
f.close()
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
if METRIC is 0:
precip_today = parsed_json['current_observation']['precip_today_in']
else:
precip_today = parsed_json['current_observation']['precip_today_metric']
print("Current precipitation in %s is: %s" % (location, precip_today))
if float(precip_today) > float(RAIN_THRESHOLD):
print("Rain today, take the umbrella")
assign_rain(True, BLINK)
else:
print("No Rain today")
assign_rain(False, BLINK)
except KeyboardInterrupt:
clear_led(0)
digitalWrite(rainled, 0)

View file

@ -0,0 +1,61 @@
# tilt_buzzer.py
#
# This is an project using the Grove Switch, Buzzer and accelerometer from the GrovePi starter kit
#
# In this project, the buzzer starts making a sound when the accelerometer is held perpendicular and the Switch is on
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
'''
import time
from grovepi import *
import math
buzzer_pin = 2 #Port for buzzer
switch_pin = 4 #Port for switch
pinMode(buzzer_pin,"OUTPUT") # Assign mode for buzzer as output
pinMode(switch_pin,"INPUT") # Assign mode for switch as input
while True:
try:
switch_status= digitalRead(switch_pin) #Read the switch status
if switch_status: #If the switch is in HIGH position, run the program
accl = acc_xyz() # Get the value from the accelerometer
print "\nX:",accl[0],"\tY:",accl[1],"\tZ:",accl[2],
if accl[0] > 16: # If the value on X-axis is greater than the Threshold, start the buzzer
digitalWrite(buzzer_pin,1)
print ("\tBuzzing")
else: #Else stop the buzzer
digitalWrite(buzzer_pin,0)
else: #If switch is in Off position, print "Off" on the screen
print("Off")
time.sleep(.1)
except KeyboardInterrupt: # Stop the buzzer before stopping
digitalWrite(buzzer_pin,0)
break
except (IOError,TypeError) as e:
print("Error")

View file

@ -0,0 +1,35 @@
## **GrovePi Weather Station**
- **Raspberry Pi Classroom Weather Station**: Read the local weather and record it to a file.
- **Sensor Connections on the GrovePi:**
* [Grove light sensor](http://www.dexterindustries.com/shop/grove-light-sensor/) - Port A2
* [Grove Temperature and Humidity Sensor](http://www.dexterindustries.com/shop/grovepi-starter-kit-raspberry-pi/) - Port D4
* [Raspberry Pi Camera](http://www.dexterindustries.com/shop/raspberry-pi-camera/)
* Grove Pressure sensor (BMP 180) - Any I2C port, I2C-1, I2C-2, or I2C-3.
See more at the [GrovePi Site](http://dexterindustries.com/GrovePi/).
## License
.
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,147 @@
#!/usr/bin/env python
#
# GrovePi Project for a Weather Station project.
# * Reads the data from light, temperature and humidity sensor
# and takes pictures from the Pi camera periodically and logs them
# coming soon: reading atmospheric pressure(BMP180)
# * Sensor Connections on the GrovePi:
# -> Grove light sensor - Port A2
# -> Grove Temperature and Humidity sensor - Port D4
# -> Raspberry Pi Camera
# -> Grove Pressure sensor (BMP 180) - Any I2C port, I2C-1, I2C-2, or I2C-3.
#
# NOTES:
# * Make sure that the Pi camera is enabled and working. You can see detailed directions here: https://www.raspberrypi.org/help/camera-module-setup/
# * The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
# * Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
#################################################################
import time
import grovepi
import subprocess
import math
# import picamera
from grove_i2c_barometic_sensor_BMP180 import BMP085
#################################################################
## File Location
log_file="/home/pi/Desktop/weather_station_log.csv" # This is the name of the file we will save data to.
# This is hard coded to the Desktop.
#################################################################
## Sensors
light_sensor = 2 #Light Sensor Port Number
temp_humidity_sensor = 4 #Temperature sensor Port Number
# Temp humidity sensor type. You can use the blue or the white version.
# Note the GrovePi Starter Kit comes with the blue sensor
blue=0
white=1
therm_version = blue # If you change the thermometer, this is where you redefine.
# bmp = BMP085(0x77, 1) #Initialize the pressure sensor (barometer)
# camera = picamera.PiCamera() # Initialize the camera.
#################################################################
# Timings
# You can adjust the frequency of the operations here: how frequently the sensors are read,
# how frequently the data is written to csv, and how frequently pictures are taken.
time_for_sensor = 1*60*60 # Take sensor data every 1 hour
time_for_picture = 8*60*60 # Take sensor data every 8 hours
time_to_sleep = 10 # The main loop runs every 10 seconds.
# Timings
#################################################################
#Read the data from the sensors.
def read_sensor():
try:
# pressure=pressure = bmp.readPressure()/100.0
light=grovepi.analogRead(light_sensor)
[temp,humidity] = grovepi.dht(temp_humidity_sensor,therm_version) # Here we're using the thermometer version.
#Return -1 in case of bad temp/humidity sensor reading
if math.isnan(temp) or math.isnan(humidity): #temp/humidity sensor sometimes gives nan
# return [-1,-1,-1,-1]
return [-1,-1,-1]
# return [pressure,light,temp,humidity]
return [light,temp,humidity]
#Return -1 in case of sensor error
except (IOError,TypeError) as e:
return [-1,-1,-1]
# return [-1,-1,-1,-1]
#Take a picture with the current time using the Raspberry Pi camera. Save it in the same folder.
''' def take_picture():
try:
picture_name = "plant_monitor_"+str(time.strftime("%Y_%m_%d__%H_%M_%S"))+".jpg"
camera.capture(picture_name)
print "Picture taken\n------------>\n"
except:
print "Camera problem! Please check the camera connections and settings"
'''
#Save the initial time, we will use this to find out when it is time to take a picture or save a reading
last_read_sensor=last_pic_time= int(time.time())
# Main Loop
while True:
curr_time_sec=int(time.time())
[light,temp,humidity]=read_sensor()
# If any reading is a bad reading, skip the loop and try again
if light==-1:
print("Bad reading")
time.sleep(1)
continue
curr_time = time.strftime("%Y-%m-%d:%H-%M-%S")
print(("Time:%s\nLight: %d\nTemp: %.2fC\nHumidity:%.2f %%\n" %(curr_time,light,temp,humidity)))
# If it is time to take the sensor reading
if curr_time_sec-last_read_sensor>time_for_sensor:
# Save the sensor reading to the CSV file
print("Save the sensor reading to the CSV file.")
f=open(log_file,'a')
f.write("%s,%d,%.2f,%.2f;\n" %(curr_time,light,temp,humidity))
f.close()
#Update the last read time
last_read_sensor=curr_time_sec
# If it is time to take the picture
if curr_time_sec-last_pic_time>time_for_picture:
# take_picture()
last_pic_time=curr_time_sec
#Slow down the loop
time.sleep(time_to_sleep)

View file

@ -0,0 +1,147 @@
#!/usr/bin/env python
#
# GrovePi Project for a Weather Station project.
# * Reads the data from light, temperature and humidity sensor
# and takes pictures from the Pi camera periodically and logs them
# coming soon: reading atmospheric pressure(BMP180)
# * Sensor Connections on the GrovePi:
# -> Grove light sensor - Port A2
# -> Grove Temperature and Humidity sensor - Port D4
# -> Raspberry Pi Camera
# -> Grove Pressure sensor (BMP 180) - Any I2C port, I2C-1, I2C-2, or I2C-3.
#
# NOTES:
# * Make sure that the Pi camera is enabled and working. You can see detailed directions here: https://www.raspberrypi.org/help/camera-module-setup/
# * The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
# * Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
#################################################################
import time
import grovepi
import subprocess
import math
# import picamera
from grove_i2c_barometic_sensor_BMP180 import BMP085
#################################################################
## File Location
log_file="/home/pi/Desktop/weather_station_log.csv" # This is the name of the file we will save data to.
# This is hard coded to the Desktop.
#################################################################
## Sensors
light_sensor = 2 #Light Sensor Port Number
temp_humidity_sensor = 4 #Temperature sensor Port Number
# Temp humidity sensor type. You can use the blue or the white version.
# Note the GrovePi Starter Kit comes with the blue sensor
blue=0
white=1
therm_version = blue # If you change the thermometer, this is where you redefine.
bmp = BMP085(0x77, 1) #Initialize the pressure sensor (barometer)
# camera = picamera.PiCamera() # Initialize the camera.
#################################################################
# Timings
# You can adjust the frequency of the operations here: how frequently the sensors are read,
# how frequently the data is written to csv, and how frequently pictures are taken.
time_for_sensor = 1*60*60 # Take sensor data every 1 hour
time_for_picture = 8*60*60 # Take sensor data every 8 hours
time_to_sleep = 10 # The main loop runs every 10 seconds.
# Timings
#################################################################
#Read the data from the sensors.
def read_sensor():
try:
pressure=pressure = bmp.readPressure()/100.0
light=grovepi.analogRead(light_sensor)
[temp,humidity] = grovepi.dht(temp_humidity_sensor,therm_version) # Here we're using the thermometer version.
#Return -1 in case of bad temp/humidity sensor reading
if math.isnan(temp) or math.isnan(humidity): #temp/humidity sensor sometimes gives nan
return [-1,-1,-1,-1]
#return [-1,-1,-1]
return [pressure,light,temp,humidity]
#return [light,temp,humidity]
#Return -1 in case of sensor error
except (IOError,TypeError) as e:
# return [-1,-1,-1]
return [-1,-1,-1,-1]
#Take a picture with the current time using the Raspberry Pi camera. Save it in the same folder.
''' def take_picture():
try:
picture_name = "plant_monitor_"+str(time.strftime("%Y_%m_%d__%H_%M_%S"))+".jpg"
camera.capture(picture_name)
print "Picture taken\n------------>\n"
except:
print "Camera problem! Please check the camera connections and settings"
'''
#Save the initial time, we will use this to find out when it is time to take a picture or save a reading
last_read_sensor=last_pic_time= int(time.time())
# Main Loop
while True:
curr_time_sec=int(time.time())
[pressure,light,temp,humidity]=read_sensor()
# If any reading is a bad reading, skip the loop and try again
if light==-1:
print("Bad reading")
time.sleep(1)
continue
curr_time = time.strftime("%Y-%m-%d:%H-%M-%S")
print(("Time:%s\nLight: %d\nTemp: %.2fC\nHumidity:%.2f%%\nPressure: %d hPa\n" %(curr_time,light,temp,humidity,pressure)))
# If it is time to take the sensor reading
if curr_time_sec-last_read_sensor>time_for_sensor:
# Save the sensor reading to the CSV file
print("Save the sensor reading to the CSV file.")
f=open(log_file,'a')
f.write("%s,%d,%.2f,%.2f,%d;\n" %(curr_time,light,temp,humidity,pressure))
f.close()
#Update the last read time
last_read_sensor=curr_time_sec
# If it is time to take the picture
if curr_time_sec-last_pic_time>time_for_picture:
# take_picture()
last_pic_time=curr_time_sec
#Slow down the loop
time.sleep(time_to_sleep)

View file

@ -0,0 +1,148 @@
#!/usr/bin/env python
#
# GrovePi Project for a Weather Station project.
# * Reads the data from light, temperature and humidity sensor
# and takes pictures from the Pi camera periodically and logs them
# coming soon: reading atmospheric pressure(BMP180)
# * Sensor Connections on the GrovePi:
# -> Grove light sensor - Port A2
# -> Grove Temperature and Humidity sensor - Port D4
# -> Raspberry Pi Camera
# -> Grove Pressure sensor (BMP 180) - Any I2C port, I2C-1, I2C-2, or I2C-3.
#
# NOTES:
# * Make sure that the Pi camera is enabled and working. You can see detailed directions here: https://www.raspberrypi.org/help/camera-module-setup/
# * The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
# * Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
#
'''
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
#################################################################
import time
import grovepi
import subprocess
import math
# import picamera
from grove_i2c_barometic_sensor_BMP180 import BMP085
#################################################################
## File Location
log_file="/home/pi/Desktop/weather_station_log.csv" # This is the name of the file we will save data to.
# This is hard coded to the Desktop.
#################################################################
## Sensors
light_sensor = 2 #Light Sensor Port Number
temp_humidity_sensor = 4 #Temperature sensor Port Number
# Temp humidity sensor type. You can use the blue or the white version.
# Note the GrovePi Starter Kit comes with the blue sensor
blue=0
white=1
therm_version = white # If you change the thermometer, this is where you redefine.
# bmp = BMP085(0x77, 1) #Initialize the pressure sensor (barometer)
# camera = picamera.PiCamera() # Initialize the camera.
#################################################################
# Timings
# You can adjust the frequency of the operations here: how frequently the sensors are read,
# how frequently the data is written to csv, and how frequently pictures are taken.
time_for_sensor = 1*60*60 # Take sensor data every 1 hour
time_for_picture = 8*60*60 # Take sensor data every 8 hours
time_to_sleep = 10 # The main loop runs every 10 seconds.
# Timings
#################################################################
#Read the data from the sensors.
def read_sensor():
try:
# pressure=pressure = bmp.readPressure()/100.0
light=grovepi.analogRead(light_sensor)
[temp,humidity] = grovepi.dht(temp_humidity_sensor,therm_version) # Here we're using the thermometer version.
#Return -1 in case of bad temp/humidity sensor reading
if math.isnan(temp) or math.isnan(humidity): #temp/humidity sensor sometimes gives nan
# return [-1,-1,-1,-1]
return [-1,-1,-1]
# return [pressure,light,temp,humidity]
return [light,temp,humidity]
#Return -1 in case of sensor error
except (IOError,TypeError) as e:
return [-1,-1,-1]
# return [-1,-1,-1,-1]
#Take a picture with the current time using the Raspberry Pi camera. Save it in the same folder.
'''
def take_picture():
try:
picture_name = "plant_monitor_"+str(time.strftime("%Y_%m_%d__%H_%M_%S"))+".jpg"
camera.capture(picture_name)
print "Picture taken\n------------>\n"
except:
print "Camera problem! Please check the camera connections and settings"
'''
#Save the initial time, we will use this to find out when it is time to take a picture or save a reading
last_read_sensor=last_pic_time= int(time.time())
# Main Loop
while True:
curr_time_sec=int(time.time())
[light,temp,humidity]=read_sensor()
# If any reading is a bad reading, skip the loop and try again
if light==-1:
print("Bad reading")
time.sleep(1)
continue
curr_time = time.strftime("%Y-%m-%d:%H-%M-%S")
print(("Time:%s\nLight: %d\nTemp: %.2fC\nHumidity:%.2f %%\n" %(curr_time,light,temp,humidity)))
# If it is time to take the sensor reading
if curr_time_sec-last_read_sensor>time_for_sensor:
# Save the sensor reading to the CSV file
print("Save the sensor reading to the CSV file.")
f=open(log_file,'a')
f.write("%s,%d,%.2f,%.2f;\n" %(curr_time,light,temp,humidity))
f.close()
#Update the last read time
last_read_sensor=curr_time_sec
# If it is time to take the picture
if curr_time_sec-last_pic_time>time_for_picture:
# take_picture()
last_pic_time=curr_time_sec
#Slow down the loop
time.sleep(time_to_sleep)