Example #1
0
def buzzer_write(value):
	grovepi.pinMode(buzzer,"OUTPUT")

        grovepi.digitalWrite(buzzer,1)
        time.sleep(value)
        grovepi.digitalWrite(buzzer,0)
        time.sleep(.5)
def startup():
    #This function is the first to run.
    global light_sensor_pin, relay_pin, potentiometer_pin, button_pin, led1_pin, led2_pin, mototrFw_pin, motorBk_pin, strText

    #GPIO.setwarnings(False)
    
    light_sensor_pin = 0
    potentiometer_pin = 1
    button_pin = 3
    led1_pin = 5 #for testing
    led2_pin = 6 #for testing
    
    motorFw_pin=33
    motorBk_pin=35

    strText = "First Run"

    grovepi.pinMode(potentiometer_pin,"INPUT")
    grovepi.pinMode(button_pin,"INPUT")
    grovepi.pinMode(led1_pin,"OUTPUT") #for testing
    grovepi.pinMode(led2_pin,"OUTPUT") #for testing
    grovepi.pinMode(light_sensor_pin,"INPUT")

    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(motorFw_pin, GPIO.OUT)
    GPIO.setup(motorBk_pin, GPIO.OUT)

    time.sleep(1)
    checkTxt() #Get initial Settings
    def __init__(self, _temperature_pin, _thermocouple_pin, _json_path = None):

        if(_json_path is None):
            _json_path = 'thermocouple_table.json'

        try:
            with open(_json_path) as table_file:
                table = json.load(table_file)

            self.__interpolateTable(table)
            self.__amp_av = table["amp_factor"]
            self.__vol_offset = table["amp_offset"]

        except:
            self.sensor_table = None
            self.__amp_av = 1
            self.__vol_offset = 1
            self.voltage_to_degrees_table = None

        # save the variables inside the object
        self.temperature_pin = _temperature_pin
        self.thermocouple_pin = _thermocouple_pin

        # set the pins as INPUT
        # this sensor outputs analog values so you can
        # use one of the 3 analog ports on the GrovePi
        grovepi.pinMode(self.temperature_pin, "INPUT")
        grovepi.pinMode(self.thermocouple_pin, "INPUT")
Example #4
0
    def _poll(self):
        device = self.sensor.device
        pin = self.sensor.pin
        value = None

        grovepilib.pinMode(pin,"INPUT")
        if device == 'GroveButton':
            value = grovepilib.digitalRead(pin)
        elif device == 'GroveLight':
            raw = grovepilib.analogRead(pin)
            if raw == 0:
                value = 0
            else:
                coefficient = ((1023.0-raw) * 10.0/raw) * 15.0
                exponent = 4.0/3.0
                value = 10000.0/pow(coefficient, exponent)
        elif device == 'GroveRotaryAngle':
            adc_ref = 5
            full_angle = 300
            grove_vcc = 5

            sensor_value = grovepilib.analogRead(pin)
            voltage = round((float)(sensor_value) * adc_ref / 1023, 2)
            degrees = round((voltage * full_angle) / grove_vcc, 2)
            value = degrees
        elif device == 'GroveSound':
            value = grovepilib.analogRead(pin)
        elif device == 'GroveTemperature':
            value = grovepilib.temp(pin,'1.1')
        elif device == 'GroveTouch':
            value = grovepilib.digitalRead(pin)

        return SensorReading(self.sensor, value)
 def __init__(self, gasid, sensor_number=MQ_PIN, Debug=False, Rload=RL_VALUE, \
              rawCleanAir=0, RoCleanAirFactor=RO_CLEAN_AIR_FACTOR, \
              Ro=RoH2, GasCurve=H2Curve,\
              ReadWait=READ_SAMPLE_INTERVAL, \
              ReadIter=READ_SAMPLE_TIMES, \
              ReadWaitCal=CALIBRATION_SAMPLE_INTERVAL, \
              ReadIterCal=CALIBRATION_SAMPLE_TIMES ):
    self.gasid = gasid       # e.g MQ8, but is arbitrary name
    self.pin = sensor_number # analog sensor number on GrovePI
    self.debug = Debug
    self.rload = Rload
    self.rawCleanAir = rawCleanAir
    self.RoCleanAirFactor = RoCleanAirFactor
    self.Ro = Ro
    self.GasCurve = GasCurve
    self.ReadWait = ReadWait
    self.ReadIter = ReadIter
    self.ReadWaitCal = ReadWaitCal
    self.ReadIterCal = ReadIterCal
    if self.debug:
        print self.gasid
        print self.pin
        print self.debug
        print self.rload
        print self.rawCleanAir
        print self.Ro
        print self.GasCurve
        print self.ReadWait
        print self.ReadIter
    try:
      grovepi.pinMode(sensor_number,"INPUT")
    except IOError as e:
      print "__init error", e
Example #6
0
def main():
    cfg = {
        "consumer_key":'9iHdYDCrzpNefQqtUyDh7tScN',
        "consumer_secret":'pYP8c8njj3vtJqeoDNZpR2kMwuNi0LQKmiGnBlL1Dg5sylEUyI',
        "access_token":'756129972075556864-8G9mT1j8RxOx7cgrTbWsQ9CqrK3f0iG',
        "access_token_secret":'ZmjDVFHZgYKNvI0Cr2bKQfSYue2tOh4R6uLBWblRUndvN'
    }

    grovepi.pinMode(button, "INPUT")
    print "Waiting for button to be pressed"

    while True:
        try:
            # get value of button status
            button_status = grovepi.digitalRead(button)

            # if button pressed
            if button_status == 1:
                api = get_api(cfg)
                print "I am posting a tweet via GrovePi!"
                
                # captures distance between ultrasonic sensor and the closest object
                distance = grovepi.ultrasonicRead(ultrasonic_ranger)
                tweet = "There is currently an object " + str(distance) + " cm away from my$
                status = api.update_status(status=tweet)
                # immediately print tweet
                print(tweet)
        except IOError:
            print("Error")
        except KeyboardInterrupt:
            exit()
def deliver():
    # Get the current uuid
    dic = dict(request.form)
    for each in dic:
        uuid = each
        break
    print uuid
    #Make sure it is in the table in DynamoDB
    orders=dynamodb.Table('Order')
    orders = orders.scan()
    for order in orders["Items"]:
        if order['ID']==uuid:
	    if order_dict_1['status']==0:
		order_dict_1['status']=1
		order_dict_1['ID']=uuid
		relay = order_dict_1['relay']
        	grovepi.pinMode(relay,"OUTPUT")
        	grovepi.digitalWrite(relay,1)
        	time.sleep(5)
        	grovepi.digitalWrite(relay,0)
		apns_sns_send()
		print 'box 1 put in food'
	    elif order_dict_2['status']==0:
                order_dict_2['status']=1
                order_dict_2['ID']=uuid
                relay = order_dict_2['relay']
                grovepi.pinMode(relay,"OUTPUT")
                grovepi.digitalWrite(relay,1)
                time.sleep(5)
                grovepi.digitalWrite(relay,0)
		print 'box 2 put in food'
		apns_sns_send()
    return 'delivery'
def start():
    grovepi.pinMode(ledbar, "OUTPUT")
    grovepi.ledBar_init(ledbar, 0)
    grovepi.ledBar_orientation(ledbar, 1)
    pinMode(led, "OUTPUT")

    json_obj = getTankInfos(code)
    if json_obj != []:
        updateTankStatus(json_obj)
        data = checkLightUPnP()
        if data != None:
            if data[0] == '1':
                level = int(data[1])
            else:
                json_brightness = getBrightnessLevel(json_obj)
                if json_brightness['time'] == "sun":
                    level = float(json_brightness['brightness'])
                else:
                    level = float(json_brightness['brightness'])
        setLedValue(int(level))
    else:
        for i in range(0, 4):
            digitalWrite(led, 1)
            time.sleep(1)
            digitalWrite(led, 0)
            time.sleep(1)
        time.sleep(60)
        start(json_obj)
def main():
    global isConnected
    # Create an MQTT client for connecting to AWS IoT via MQTT.
    client = mqtt.Client(deviceName + "_sr")  # Client ID must be unique because AWS will disconnect any duplicates.
    client.on_connect = on_connect  # When connected, call on_connect.
    client.on_message = on_message  # When message received, call on_message.
    client.on_log = on_log  # When logging debug messages, call on_log.

    # Set the certificates and private key for connecting to AWS IoT.  TLS 1.2 is mandatory for AWS IoT and is supported
    # only in Python 3.4 and later, compiled with OpenSSL 1.0.1 and later.
    client.tls_set(awsCert, deviceCertificate, devicePrivateKey, ssl.CERT_REQUIRED, ssl.PROTOCOL_TLSv1_2)

    # Connect to AWS IoT server.  Use AWS command line "aws iot describe-endpoint" to get the address.
    print("Connecting to AWS IoT...")
    client.connect("A1P01IYM2DOZA0.iot.us-west-2.amazonaws.com", 8883, 60)

    # Start a background thread to process the MQTT network commands concurrently, including auto-reconnection.
    client.loop_start()

    # Configure the Grove LED port for output.
    grovepi.pinMode(led, "OUTPUT")
    time.sleep(1)

    # Loop forever.
    while True:
        try:
            # If we are not connected yet to AWS IoT, wait 1 second and try again.
            if not isConnected:
                time.sleep(1)
                continue

            # Read Grove sensor values. Prepare our sensor data in JSON format.
            payload = {
                "state": {
                    "reported": {
                        # Uncomment the next line if you're using the Grove Analog Temperature Sensor.
                        # "temperature": round(grovepi.temp(temp_sensor, '1.1'), 1),
                        # Comment out the next 2 lines if you're using the Grove Analog Temperature Sensor.
                        "temperature": grovepi.dht(dht_sensor, 0)[0],  # The first 0 means that the DHT module is DHT11.
                        "humidity": grovepi.dht(dht_sensor, 0)[1],
                        "light_level": grovepi.analogRead(light_sensor),
                        "sound_level": grovepi.analogRead(sound_sensor),
                        "timestamp": datetime.datetime.now().isoformat()
                    }
                }
            }
            print("Sending sensor data to AWS IoT...\n" +
                  json.dumps(payload, indent=4, separators=(',', ': ')))

            # Publish our sensor data to AWS IoT via the MQTT topic, also known as updating our "Thing Shadow".
            client.publish("$aws/things/" + deviceName + "/shadow/update", json.dumps(payload))
            print("Sent to AWS IoT")

            # Wait 30 seconds before sending the next set of sensor data.
            time.sleep(30)

        except KeyboardInterrupt:
            break
        except IOError:
            print("Error")
Example #10
0
def setup():
# air sensor
  grovepi.pinMode(MQ_PIN,"INPUT")
  if debug: print("Calibrating.H2 sensor..")
  Ro = MQCalibration(MQ_PIN)  # Calibrating the sensor. Please make sure the sensor is in clean air
                              # when you perform the calibration
  print "Calibration H2 is done.  Ro= ", Ro , " kohm"
  time.sleep(1.)
Example #11
0
	def initialize(self):
		grovepi.pinMode(pins_bright,"INPUT")
		self.ser = serial.Serial('/dev/ttyAMA0', 9600, timeout = 0)
		self.ser.flush()
		self.bmp = BMP085(0x77, 1)
		rev = GPIO.RPI_REVISION
		if rev == 2 or rev == 3:
			bus = smbus.SMBus(1)
		else:
			bus = smbus.SMBus(0)
Example #12
0
  def handle(self, seconds):
    try: 
      grovepi.pinMode(self.port, "OUTPUT")
      #time.sleep(1)

      grovepi.digitalWrite(self.port, 1)
      time.sleep(seconds)

    except IOError:
      print ("Error")
   
    grovepi.digitalWrite(self.port, 0)
Example #13
0
    def update(self, sessionToken, username):
        self.username = username
        self.sessionToken = sessionToken
        self.temperature = 0
        self.humidity = 0
        self.moisture = 0
        self.light = 0
        self.waterNow = False
        grovepi.pinMode(constants.LIGHT_PIN,"INPUT")
        grovepi.pinMode(constants.MOISTURE_PIN,"INPUT")
        grovepi.pinMode(constants.TEMP_HUMIDITY_PIN,"INPUT")
        grovepi.pinMode(constants.PUMP_RELAY_PIN,"OUTPUT")
        self.pubnub = Pubnub(publish_key=constants.PUBNUB_PUBLISH_KEY, subscribe_key=constants.PUBNUB_SUBSCRIBE_KEY, ssl_on = True)
        self.sendSensors = False
        while True: #keep trying until you have internet
            try:
                req = urllib2.Request(constants.ROOT_URL + 'active-plant')
                req.add_header('x-access-token', sessionToken)
                result = json.loads(urllib2.urlopen(req).read())

                self.waterAmount = result["waterAmount"]
                self.harvest = len(result["harvests"])
                self.moistureLimit = result["moistureLimit"]                
                break
            except Exception as e:
                s = str(e)
Example #14
0
 def handle(self):
   grovepi.pinMode(self.port, "INPUT")
   while True:
     try:
       value = grovepi.digitalRead(self.port)
       if value: # GOAL!!
         #print "gooooool!!!!!", value
         for s in self.subscribers: # notify
           s.notify(1)
       time.sleep(.2)
     except TypeError:
       print ("Error")
     except IOError:
       print ("Error")
Example #15
0
  def notify(self, seconds):
    grovepi.pinMode(self.port, "OUTPUT")
    time.sleep(1)
    i = 0

    while i < seconds * 2:
      try:
        grovepi.analogWrite(self.port, 255)
        time.sleep(.5)
        i += 1 

      except KeyboardInterrupt:
        grovepi.analogWrite(self.port, 0)
        break
      except IOError:
        print ("Error")
    grovepi.analogWrite(self.port, 0)
Example #16
0
  def handle(self, seconds):
    grovepi.pinMode(self.port, "OUTPUT")
    time.sleep(1)
    i = 0

    while i < seconds * 2:
      try:
        grovepi.digitalWrite(self.port, 1)
        time.sleep(.5)
        i += 1 

      except KeyboardInterrupt:
        grovepi.digitalWrite(self.port, 0)
        break
      except IOError:
        print ("Error")
   
    grovepi.digitalWrite(self.port, 0)
Example #17
0
    def __init__(self):
        self.dataDict["p_brightness"] = 0
        self.dataDict["p_temperature"] = 0
        self.dataDict["p_humidity"] = 0
        self.dataDict["p_pressure"] = 0
        self.dataDict["p_lat"] = 0
        self.dataDict["p_lon"] = 0
        self.dataDict["p_alt"] = 0

        grovepi.pinMode(pins_brightness, "INPUT")

        self.serial = serial.Serial("/dev/ttyAMA0", 9600, timeout = 0)
        self.serial.flush()

        self.bmp = BMP085(0x77, 1)
        if GPIO.RPI_REVISION == 2 or GPIO.RPI_REVISION == 3:
            smbus.SMBus(1)
        else:
            smbus.SMBus(0)
def openbox():
    # Get the current uuid
    dic = dict(request.form)
    for each in dic:
        uuid = each
        break
    print uuid
    # Make sure the order number is valid
    if uuid == order_dict_1['ID'] and order_dict_1['status']==1:
        relay = order_dict_1['relay']
	grovepi.pinMode(relay,"OUTPUT")
        grovepi.digitalWrite(relay,1)
        time.sleep(5)
        grovepi.digitalWrite(relay,0)
	order_dict_1['ID'] = '0'
	order_dict_1['status'] = 2
        t = Thread(target=humexp, args=(order_dict_1,))
        t.daemon = True
        t.start()
	print 'food in box 1 took out'
        return 'opened'
    elif uuid == order_dict_2['ID'] and order_dict_2['status']==1:
        relay = order_dict_2['relay']
        grovepi.pinMode(relay,"OUTPUT")
        grovepi.digitalWrite(relay,1)
        time.sleep(5)
        grovepi.digitalWrite(relay,0)
	order_dict_2['ID'] = '0'
	order_dict_2['status'] = 2
        t = Thread(target=humexp, args=(order_dict_2,))
        t.daemon = True
        t.start()
	print 'food in box 2 took out'
        return 'opened'
    else:
	return 'no match'
Example #19
0
def handlerequests(req):
    if req.operation==0:
        pin = req.pin.split("Pin")[1]
        grovepi.pinMode(int(pin), "INPUT")
        try:
            sensorval = grovepi.digitalRead(int(pin))
        except:
            sensorval =0
        msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation)
        sys.stdout.write(json.dumps(msgtx.__dict__)+"\n")
    elif req.operation == 1:
        pin = req.pin.split("Pin")[1]
        grovepi.pinMode(int(pin), "OUTPUT")
        try:
            grovepi.digitalWrite(int(pin), int(req.payload))
        except:
            grovepi.digitalWrite(int(pin), int(req.payload))
    elif req.operation == 2:
        pin = req.pin.split("Pin")[1]
        grovepi.pinMode(int(pin), "INPUT")
        try:
            sensorval = grovepi.analogRead(int(pin))
        except:
            sensorval = 0
        msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation)
        sys.stdout.write(json.dumps(msgtx.__dict__)+"\n")
    elif req.operation ==4:
        pin = req.pin.split("Pin")[1]
        try:
            [temp,humidity] = grovepi.dht(int(pin),1)
        except:
            temp=0
            humidity =0
        a= json.dumps({'temp':temp,'humidity':humidity})
        msgtx = Python2Sharp(msg.isRequest,msg.watcherid,msg.syncid,a,msg.operation)
        sys.stdout.write(json.dumps(msgtx.__dict__)+"\n")
    elif req.operation == 5:
        pin = req.pin.split("Pin")[1]
        try:
            sensorval=grovepi.ultrasonicRead(int(pin))
        except:
            sensorval=0
        msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation)
        sys.stdout.write(json.dumps(msgtx.__dict__)+"\n")
    elif req.operation == 6:
        try:
            setRGB(0,128,64)
            setText(req.payload)
        except:
            pass
Example #20
0
def setupIO():
    # Initialisation des entrées sorties sur le GrovePi #
    grovepi.pinMode(relay_pin,"OUTPUT")
    grovepi.pinMode(RGB_pin,"OUTPUT")
    grovepi.pinMode(PIR_pin, "INPUT")
    grovepi.chainableRgbLed_init(RGB_pin,8)
    
    # On génère un PWM hardware de fréquence 50Hz #
    # La largeur de l'impulsion est entre 0,8 et 2ms #
    wiringPi.wiringPiSetupGpio()
    wiringPi.pinMode(PWM_GPIO, 2)
    wiringPi.pwmSetMode(0)
    wiringPi.pwmSetClock(384)
    wiringPi.pwmSetRange(1024)
    wiringPi.pwmWrite(PWM_GPIO,75)
Example #21
0
import station_admin_staffer
from grove_rgb_lcd import *
from decimal import Decimal

##################################### MANAGE CONNECTIONS ###########################
#connect to MySQLdb
#                    <host>      <MySQL user>      <pwrd>      <db_name>
db=MySQLdb.connect("localhost", "station_admin", "tcss499", "noise_canceller")

# populate sample data
station_admin_staffer.build_schedules(db)
station_admin_staffer.staff_admins(db)

# Physical connections
btn = 6
grovepi.pinMode(btn,"INPUT")
ths = 4

# day_of_week used to correlate with admin_schedules
# Use lowercase first 3 letters of the day_of_week being tested
# 'fri'day should be the only day with all 5 notifications added
global day_of_week 
day_of_week = "mon" 
iteration = 0




################################## functions for db interaction ###############
# executes the insert.  No changes here but uncommenting the print()s
# may help with debugging
Example #22
0
#When you press the button, LED should turn from on to off, or off to on.
import time
import grovepi

led = 9
button = 6

grovepi.pinMode(led, "OUTPUT")
grovepi.pinMode(button, "INPUT")

flag = False
'''
while(True):
    print grovepi.digitalRead(button)
'''

while (True):
    if grovepi.digitalRead(button) is 1:
        flag = flag ^ True
    grovepi.digitalWrite(led, flag)
    #time.sleep(1)
Example #23
0
import liblo, sys
import grovepi

# Connect the Grove Relay to digital port D4
# SIG,NC,VCC,GND
relay = 4
grovepi.pinMode(relay, "OUTPUT")

try:
    server = liblo.Server(5005)
except liblo.ServerError, err:
    print str(err)
    sys.exit()


def foo_bar_callback(path, args):
    i, f = args
    print "received message '%s' with arguments '%d' and '%f'" % (path, i, f)


def fallback(path, args, types, src):
    print "got unknown message '%s' from '%s'" % (path, src.get_url())
    for a, t in zip(args, types):
        print "argument of type '%s': %s" % (t, a)
        if a == 3:
            # switch on for 5 seconds
            grovepi.digitalWrite(relay, 1)
            print("on")
            time.sleep(5)

            # switch off for 5 seconds
Example #24
0
# Turn on/off LED light using top relay of Grove 2 channel relay connected to GrovePi+ port D4
# http://wiki.seeedstudio.com/Grove-2-Channel_SPDT_Relay/

import time
import grovepi

# Connect the Grove 2 ch relay (top relay) to digital port D4
# SIG,NC,VCC,GND
light = 4

grovepi.pinMode(light, "OUTPUT")

while True:
    try:
        # Turn light on for 10 seconds
        grovepi.digitalWrite(light, 1)
        print('start')
        time.sleep(10)

        # Turn off light for 10 seconds and repeat
        grovepi.digitalWrite(light, 0)
        print('stop')
        time.sleep(10)

    except KeyboardInterrupt:
        grovepi.digitalWrite(light, 0)
        break
    except IOError:
        print("Error")
Example #25
0
# Connect the Grove Thumb Joystick to analog port A0

# GrovePi Port A0 uses Arduino pins 0 and 1
# GrovePi Port A1 uses Arduino pins 1 and 2
# Don't plug anything into port A1 that uses pin 1
# Most Grove sensors only use 3 of their 4 pins, which is why the GrovePi shares Arduino pins between adjacent ports
# If the sensor has a pin definition SIG,NC,VCC,GND, the second (white) pin is not connected to anything

# If you wish to connect two joysticks, use ports A0 and A2 (skip A1)

# Uses two pins - one for the X axis and one for the Y axis
# This configuration means you are using port A0
xPin = 0
yPin = 1
grovepi.pinMode(xPin, "INPUT")
grovepi.pinMode(yPin, "INPUT")

# The Grove Thumb Joystick is an analog device that outputs analog signal ranging from 0 to 1023
# The X and Y axes are two ~10k potentiometers and a momentary push button which shorts the x axis

# My joystick produces slightly different results to the specifications found on the url above
# I've listed both here:

# Specifications
#     Min  Typ  Max  Click
#  X  206  516  798  1023
#  Y  203  507  797

# My Joystick
#     Min  Typ  Max  Click
Example #26
0
import asyncio
import json
import grovepi
from azure.iot.device.aio import IoTHubDeviceClient, ProvisioningDeviceClient

# The connection details from IoT Central for the device
id_scope = ID_SCOPE
key = KEY
device_id = "pi-temperature-sensor"

# Set the temperature sensor port to the digital port D4
# and mark it as INPUT meaning data needs to be
# read from it
temperature_sensor_port = 4
grovepi.pinMode(temperature_sensor_port, "INPUT")

# Set the sound sensor port to the analog port A0
# and mark it as INPUT meaning data needs to be
# read from it
sound_sensor_port = 0
grovepi.pinMode(sound_sensor_port, "INPUT")


# Gets telemetry from the Grove sensors
# Telemetry needs to be sent as JSON data
async def get_telemetry() -> str:
    # The dht call returns the temperature and the humidity,
    # we only want the temperature, so ignore the humidity
    [temperature, humidity] = grovepi.dht(temperature_sensor_port, 0)
# 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://www.dexterindustries.com/forum/?forum=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.
#
# NOTE: 4x red 7 segment display with colon and 8 luminance levels, but no decimal points

import time
import grovepi

# Connect the Grove 4 Digit Display to digital port D5
# CLK,DIO,VCC,GND
display = 5
grovepi.pinMode(display,"OUTPUT")

# If you have an analog sensor connect it to A0 so you can monitor it below
sensor = 0
grovepi.pinMode(sensor,"INPUT")

time.sleep(.5)

# 4 Digit Display methods
# grovepi.fourDigit_init(pin)
# grovepi.fourDigit_number(pin,value,leading_zero)
# grovepi.fourDigit_brightness(pin,brightness)
# grovepi.fourDigit_digit(pin,segment,value)
# grovepi.fourDigit_segment(pin,segment,leds)
# grovepi.fourDigit_score(pin,left,right)
# grovepi.fourDigit_monitor(pin,analog,duration)
Example #28
0
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: 4x red 7 segment display with colon and 8 luminance levels, but no decimal points

import time
import grovepi

# Connect the Grove 4 Digit Display to digital port D5
# CLK,DIO,VCC,GND
display = 5
grovepi.pinMode(display,"OUTPUT")

# If you have an analog sensor connect it to A0 so you can monitor it below
sensor = 0
grovepi.pinMode(sensor,"INPUT")

time.sleep(.5)

# 4 Digit Display methods
# grovepi.fourDigit_init(pin)
# grovepi.fourDigit_number(pin,value,leading_zero)
# grovepi.fourDigit_brightness(pin,brightness)
# grovepi.fourDigit_digit(pin,segment,value)
# grovepi.fourDigit_segment(pin,segment,leds)
# grovepi.fourDigit_score(pin,left,right)
# grovepi.fourDigit_monitor(pin,analog,duration)
Example #29
0
radioBtnPort = 5

# Button port for LED
lightBtnPort = 6

# Chainable RGB LED port
# if you use this with Encoder, update firmware and apply patch
rgbLEDPort = 7

# Number of chained RGB LED
num_of_leds = 1

# Normal LED port
feedbackLEDPort = 8

grovepi.pinMode(icloudBtnPort, 'INPUT')
grovepi.pinMode(radioBtnPort, 'INPUT')
grovepi.pinMode(lightBtnPort, 'INPUT')
grovepi.pinMode(rgbLEDPort, 'OUTPUT')
grovepi.pinMode(feedbackLEDPort, 'OUTPUT')

# Init Grove Encoder
atexit.register(grovepi.encoder_dis)
grovepi.encoder_en()
    
# 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
Example #30
0
 def __init__(self, analoguePort):
     print "Initialising temperature sensor v1.2 analogue port", analoguePort
     self.port = analoguePort
     grovepi.pinMode(self.port, "INPUT")
        if (differential <= -3):
            while differential <= -1:
                differential = BP.get_motor_encoder(
                    BP.PORT_A) - BP.get_motor_encoder(BP.PORT_D)
                BP.set_motor_power(BP.PORT_D, speedCon * 0.7)
                BP.set_motor_power(BP.PORT_A, speedCon)
except IOError as error:
    print(error)
except TypeError as error:
    print(error)
except KeyboardInterrupt:
    print("You pressed ctrl+C...")

led = 3
x = 1
# Turn on LED once sensor exceeds threshold resistance
grovepi.pinMode(led, "OUTPUT")
while x != 0:
    try:
        grovepi.digitalWrite(led, 1)
        time.sleep(1000)
        x = 0
    except IOError:
        print("Error")

BP.offset_motor_encoder(BP.PORT_A, BP.get_motor_encoder(BP.PORT_A))
BP.offset_motor_encoder(BP.PORT_B, BP.get_motor_encoder(BP.PORT_B))
BP.offset_motor_encoder(BP.PORT_C, BP.get_motor_encoder(BP.PORT_C))
BP.offset_motor_encoder(BP.PORT_D, BP.get_motor_encoder(BP.PORT_D))

BP.reset_all()
Example #32
0
from time import sleep
from math import isnan
import paho.mqtt.client as mqtt

# import time
# Sensor Input
light = 2  # Adc Port 2 - Light sensor
rotary = 0  # Adc Port 0 - Humidity temperature sensor
dht_port = 2  # DC Port 2 - Humidity temperature sensor
dht_type = 0  # use 0 for the blue-colored sensor and 1 for the white-colored sensor
# Output
relay = 8  # DC Port 8 - Relay
led = 4  # DC Port 4 - Led
buzzer = 7  # DC Port 7 - Buzzer

grovepi.pinMode(dht_port, "INPUT")
grovepi.pinMode(light, "INPUT")
grovepi.pinMode(rotary, "INPUT")

grovepi.pinMode(relay, "OUTPUT")
grovepi.pinMode(led, "OUTPUT")
grovepi.pinMode(buzzer, "OUTPUT")

# set orange as background color

# ------------------------------------- ------------------------------------------#
grove_rgb_lcd.setRGB(205, 31, 0)

while True:
    try:

# When a signal is received, activate the (above) receiveSignal method.
signal.signal(signal.SIGINT, receiveSignal)

# Initialize Grovepi
pi1 = pigpio.pi()  # Creates an Object from pi-class.

# Set ports
sensor = 0  # Connect the Grove 80cm Infrared Proximity Sensor to analog port A0
A1 = 20  # A  or M1
A2 = 21  # A/ or M2
D2 = 26  # N/ -> Turn on the motordriver A A/

# Setup Sensor
grovepi.pinMode(sensor, "INPUT")
adc_ref = 5  # Reference voltage of ADC is 5 [V]
grove_vcc = 5  # Vcc of the grove interface is normally 5 [V]
sensor_value = 0  # Initial sensor value
""" Settings """
# Amplification factor k [mm^-1] converting mm to value 0 - 255
k = 5  # Standard 5
# Number of distance measurements [] over which to average
nmeasurement = 10  # Standard = 10
# Waiting time between measurement points [s]
waittime = 0.1  # Standard = 0.1
# Offset velocity [12V / 255], in range 0 - 255
offset = 10  # Standard = 10
""" Initialize """
# Ask for the Set-distance
userinput = input(
Example #34
0
 def thread_init(self):
     from grovepi import pinMode, analogRead
     pinMode(self.port, 'INPUT')
Example #35
0
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 Grove Touch Sensor to digital port D4
# SIG,NC,VCC,GND
touch_sensor = 4

grovepi.pinMode(touch_sensor,"INPUT")

while True:
    try:
        print(grovepi.digitalRead(touch_sensor))
        time.sleep(.5)

    except IOError:
        print ("Error")
Example #36
0
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>.
'''
import time
import grovepi

# Connect the Grove Magnetic Switch to digital port D3
# SIG,NC,VCC,GND
magnetic_switch = 3

grovepi.pinMode(magnetic_switch,"INPUT")

while True:
    try:
        print (grovepi.digitalRead(magnetic_switch))
        time.sleep(.5)

    except IOError:
        print ("Error")
Example #37
0
		elif match_sensors(msg,analog_sensors) >=0:
			if en_grovepi:
				s_no=match_sensors(msg,analog_sensors)
				sens=analog_sensors[s_no]
				port=int(msg[len(sens):])
				a_read=grovepi.analogRead(port)
				s.sensorupdate({sens:a_read})
				
			if en_debug:
				print msg
				print sens +'op:'+ str(a_read)
		
		elif msg[:8].lower()=="setInput".lower():
			if en_grovepi:
				port=int(msg[8:])
				grovepi.pinMode(port,"INPUT")
			if en_debug:
				print msg   
				
		elif msg[:9].lower()=="setOutput".lower():
			if en_grovepi:
				port=int(msg[9:])
				grovepi.pinMode(port,"OUTPUT")
			if en_debug:
				print msg
				
		elif msg[:11].lower()=="digitalRead".lower():
			if en_grovepi:
				port=int(msg[11:])
				grovepi.pinMode(port,"INPUT")
				d_read=grovepi.digitalRead(port)
Example #38
0
		elif match_sensors(msg,analog_sensors) >=0:
			if en_grovepi:
				s_no=match_sensors(msg,analog_sensors)
				sens=analog_sensors[s_no]
				port=int(msg[len(sens):])
				a_read=grovepi.analogRead(port)
				s.sensorupdate({sens:a_read})
				
			if en_debug:
				print msg
				print sens +'op:'+ str(a_read)
		
		elif msg[:8].lower()=="setInput".lower():
			if en_grovepi:
				port=int(msg[8:])
				grovepi.pinMode(port,"INPUT")
			if en_debug:
				print msg	
				
		elif msg[:9].lower()=="setOutput".lower():
			if en_grovepi:
				port=int(msg[9:])
				grovepi.pinMode(port,"OUTPUT")
			if en_debug:
				print msg
				
		elif msg[:11].lower()=="digitalRead".lower():
			if en_grovepi:
				port=int(msg[11:])
				d_read=grovepi.digitalRead(port)
				s.sensorupdate({'digitalRead':d_read})
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 Grove Tilt Switch to digital port D3
# SIG,NC,VCC,GND
tilt_switch = 3

grovepi.pinMode(tilt_switch,"INPUT")

while True:
    try:
        print(grovepi.digitalRead(tilt_switch))
        time.sleep(.5)

    except IOError:
        print ("Error")
Example #40
0
def setPinMode(pin, mode):
    grovepi.pinMode(pin, mode)
    pass
Example #41
0
import time
import grovepi
from siren import Siren

# Connect the Grove Button to digital port D3
# SIG,NC,VCC,GND
siren = Siren(4, 8)
button = 3

grovepi.pinMode(button, "INPUT")

while True:
    if (grovepi.digitalRead(button)):
        siren.start()
    else:
        siren.stop()

while True:
    try:
        print(grovepi.digitalRead(button))
        time.sleep(.5)

    except IOError:
        print("Error")
Example #42
0
def Set_Hardware():
    grovepi.pinMode(BUTTON_PIN, "INPUT")
    grovepi.pinMode(PROXIMITY_PIN, "INPUT")
    grovepi.pinMode(BUZZER_PIN, "OUTPUT")
Example #43
0
BP = brickpi3.BrickPi3()
RIGHTMOTOR_PORT = BP.PORT_A
LEFTMOTOR_PORT = BP.PORT_D
CONVEYOR_PORT = BP.PORT_B
HALL_PORT = BP.PORT_1
SONIC_PORT = 2
RIGHTLINE_PORT = 3
LEFTLINE_PORT = 4
powerMotor = 50
powerConveyor = 80
x = 0  # Trigger for determining if cargo has been dropped

# ---------------------------------------------------
#  Initialize Sensors
# ---------------------------------------------------
grovepi.pinMode(RIGHTLINE_PORT, "INPUT")
grovepi.pinMode(LEFTLINE_PORT, "INPUT")
BP.set_sensor_type(HALL_PORT, BP.SENSOR_TYPE.CUSTOM, [BP.SENSOR_CUSTOM.PIN1_ADC])


# ---------------------------------------------------
#  Define Functions
# ---------------------------------------------------

def setpower(port, power):
    BP.set_motor_power(port, -power)


# ---------------------------------------------------
#  Warm-Up
# ---------------------------------------------------
# GrovePi + Grove Chainable RGB LED
# http://www.seeedstudio.com/wiki/Grove_-_Chainable_RGB_LED

import time
import grovepi

# Connect first LED in Chainable RGB LED chain to digital port D7
# In: CI,DI,VCC,GND
# Out: CO,DO,VCC,GND
chain = 7

# I have 10 LEDs connected in series with the first connected to the GrovePi and the last not connected
# First LED input socket connected to GrovePi, output socket connected to second LED input and so on
numleds = 10

grovepi.pinMode(chain, "OUTPUT")
time.sleep(1)

# Chainable RGB LED methods
# grovepi.storeColor(red, green, blue)
# grovepi.chainableRgbLed_init(pin, numLeds)
# grovepi.chainableRgbLed_test(pin, numLeds, testColor)
# grovepi.chainableRgbLed_pattern(pin, pattern, whichLed)
# grovepi.chainableRgbLed_modulo(pin, offset, divisor)
# grovepi.chainableRgbLed_setLevel(pin, level, reverse)

# test colors used in grovepi.chainableRgbLed_test()
testColorBlack = 0  # 0b000 #000000
testColorBlue = 1  # 0b001 #0000FF
testColorGreen = 2  # 0b010 #00FF00
testColorCyan = 3  # 0b011 #00FFFF
Example #45
0
    BROADCAST_PERIOD = 5
CAM_PERIOD = 12  # How often to take a picture
if DEBUG:
    CAM_PERIOD = 5
SCAN_LEN = 2  # How long to scan bluetooth at one time

# Initialize start time for periodic events
broadcast_time = time.time()
broadcast_time -= BROADCAST_PERIOD  # Makes particle broadcast immediately
cam_time = time.time()

# Set up grovepi
TEMP_HUM_SENSOR = 6  # Connect to D6
LOOP = 5  # Connect to D5
LED = 3  # Connect to D3
grovepi.pinMode(TEMP_HUM_SENSOR, 'INPUT')
grovepi.pinMode(LOOP, 'INPUT')
grovepi.pinMode(TEMP_HUM_SENSOR, 'OUTPUT')
grove_queue = Queue()

# TODO: scanning bluetooth and cell broadcast are intertwined since the
# bluetooth scans are being broadcast over cell. Seperate this out or
# drop bluetooth scanning.

if SCAN_BLUETOOTH:
    # Setup bluetooth
    devices = []
    sc = btle.Scanner(0)

if CELL:
    # Cell configuration
Example #46
0
ultrasonic_ranger = 7

# initialize the blank display
is_on = MY_DISPLAY_OFF
setText("nothing")
setRGB(0, 0, 0)

# set up the rotary sensor =======================
# Connect the Grove Rotary Angle Sensor to analog port A1
# SIG,NC,VCC,GND
potentiometer = 1

grovepi.analogWrite(4, 0)
#grovepi.analogWrite(2,0)

grovepi.pinMode(potentiometer, "INPUT")

# Reference voltage of ADC is 5v
adc_ref = 5

# Vcc of the grove interface is normally 5v
grove_vcc = 5

# Full value of the rotary angle is 300 degrees, as per it's specs (0 to 300)
full_angle = 300

# button =================================
# Connect the Grove Button to digital port D2
# SIG,NC,VCC,GND
button = 2
grovepi.pinMode(button, "INPUT")
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import time
import grovepi

# Connect the Grove Rotary Angle Sensor to analog port A0
# SIG,NC,VCC,GND
potentiometer = 0

# Connect the LED to digital port D5
# SIG,NC,VCC,GND
led = 5

grovepi.pinMode(potentiometer, "INPUT")
grovepi.pinMode(led, "OUTPUT")
time.sleep(1)

# Reference voltage of ADC is 5v
adc_ref = 5

# Vcc of the grove interface is normally 5v
grove_vcc = 5

# Full value of the rotary angle is 300 degrees, as per it's specs (0 to 300)
full_angle = 300

while True:
    try:
        # Read sensor value from potentiometer
Example #48
0
THE SOFTWARE.
'''

import time
import grovepi

# Connect the Grove Light Sensor to analog port A0
light_sensor = 0

# Connect the LED to digital port D3
led = 3

# Turn on LED once sensor exceeds threshold resistance
threshold = 10

grovepi.pinMode(light_sensor, "INPUT")
grovepi.pinMode(led, "OUTPUT")

while True:
    try:
        # Get sensor value
        sensor_value = grovepi.analogRead(light_sensor)

        # Calculate resistance of sensor in K
        resistance = (float)(1023 - sensor_value) * 10 / sensor_value

        if resistance > threshold:
            # Send HIGH to switch on LED
            grovepi.digitalWrite(led, 1)
        else:
            # Send LOW to switch off LED
Example #49
0
 def __del__(self):
     print "destructor for temperature sensor v1.2 port", self.port
     grovepi.pinMode(self.port, "OUTPUT")
Example #50
0
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import time
import grovepi

# Connect the Grove Switch to digital port D3
# SIG,NC,VCC,GND
switch = 3

# Connect the Grove Relay to digital port D4
# SIG,NC,VCC,GND
relay = 4

grovepi.pinMode(switch, "INPUT")
grovepi.pinMode(relay, "OUTPUT")

while True:
    try:
        if grovepi.digitalRead(switch):
            grovepi.digitalWrite(relay, 1)
        else:
            grovepi.digitalWrite(relay, 0)

        time.sleep(.5)

    except KeyboardInterrupt:
        grovepi.digitalWrite(relay, 0)
        break
    except IOError:
THE SOFTWARE.
'''

import time
import grovepi

# Connect first LED in Chainable RGB LED chain to digital port D7
# In: CI,DI,VCC,GND
# Out: CO,DO,VCC,GND
pin = 7

# I have 10 LEDs connected in series with the first connected to the GrovePi and the last not connected
# 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 10 to 1

grovepi.pinMode(pin,"OUTPUT")
time.sleep(1)

# Chainable RGB LED methods
# grovepi.storeColor(red, green, blue)
# grovepi.chainableRgbLed_init(pin, numLeds)
# grovepi.chainableRgbLed_test(pin, numLeds, testColor)
# grovepi.chainableRgbLed_pattern(pin, pattern, whichLed)
# grovepi.chainableRgbLed_modulo(pin, offset, divisor)
# grovepi.chainableRgbLed_setLevel(pin, level, reverse)

# test colors used in grovepi.chainableRgbLed_test()
testColorBlack = 0   # 0b000 #000000
testColorBlue = 1    # 0b001 #0000FF
testColorGreen = 2   # 0b010 #00FF00
testColorCyan = 3    # 0b011 #00FFFF
Example #52
0
import sys
import time
import random
import grovepi

# read prog args

if len(sys.argv) < 2:
    print('Usage: {} D<pin>'.format(sys.argv[0]))
    sys.exit(1)

ledbar = int(sys.argv[1])

#print "slot " + ledbar
grovepi.pinMode(ledbar, "OUTPUT")
time.sleep(1)
i = 0

# LED Bar methods
# grovepi.ledBar_init(pin,orientation)
# grovepi.ledBar_orientation(pin,orientation)
# grovepi.ledBar_setLevel(pin,level)
# grovepi.ledBar_setLed(pin,led,state)
# grovepi.ledBar_toggleLed(pin,led)
# grovepi.ledBar_setBits(pin,state)
# grovepi.ledBar_getBits(pin)

while True:
    try:
        print "Test 1) Initialise - red to green"
        # ledbar_init(pin,orientation)
Example #53
0
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 Grove Line Finder to digital port D7
# SIG,NC,VCC,GND
line_finder = 7

grovepi.pinMode(line_finder,"INPUT")

while True:
    try:
        # Return HIGH when black line is detected, and LOW when white line is detected
        if grovepi.digitalRead(line_finder) == 1:
            print ("black line detected")
        else:
            print ("white line detected")

        time.sleep(.5)

    except IOError:
        print ("Error")
Example #54
0
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

# The sensitivity can be adjusted by the onboard potentiometer

# Connect the Grove HCHO Sensor to analog port A0
# SIG,NC,VCC,GND
hcho_sensor = 0

grovepi.pinMode(hcho_sensor, "INPUT")

# Vcc of the grove interface is normally 5v
grove_vcc = 5

while True:
    try:
        # Get sensor value
        sensor_value = grovepi.analogRead(hcho_sensor)

        # Calculate voltage
        voltage = (float)(sensor_value * grove_vcc / 1024)

        print("sensor_value =", sensor_value, " voltage =", voltage)
        time.sleep(.5)
Example #55
0
#!/usr/bin/env python
#
# GrovePi Example for using the Grove SPDT Relay(30A) (http://www.seeedstudio.com/wiki/Grove_-_SPDT_Relay(30A))
#
# 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://www.dexterindustries.com/forum/?forum=grovepi
#

# NOTE:
# 	Relay is both normally open and normally closed.
# 	When the coil is energised, they will both flip.
# 	LED will illuminate when normally open is closed (and normally closed is open).

import sys
import time
import grovepi

# Connect the Grove SPDT Relay to digital port D4
# SIG,NC,VCC,GND
# relay = 3
relay = int(sys.argv[1])
stat = int(sys.argv[2])

#grovepi.pinMode(relay,"INPUT")
grovepi.pinMode(relay,"OUTPUT")
# print "relais was ", grovepi.digitalRead(relay)
grovepi.digitalWrite(relay,stat)
# print "relais is ", grovepi.digitalRead(relay)
Example #56
0
# DEMO CONTROL CODE - FOR TESTING ONLY. ACTUAL CONTROLS WITHIN PONG.PY

import time
import grovepi

p1 = 0
p2 = 2

butt = 4

grovepi.pinMode(p1, "INPUT")
grovepi.pinMode(p2, "INPUT")
grovepi.pinMode(butt, "INPUT")
time.sleep(1)

# values from example for maths stuff
adc_ref = 5
grove_vcc = 5
full_angle = 300

def processRotaryInput(rotary_input):
    if rotary_input <= 11.5:
        paddle_coord = 0
    elif rotary_input >= (1023-11.5):
        paddle_coord = 1000
    else:
         paddle_coord = rotary_input
    
    return int(paddle_coord / 10)

# GrovePi + Grove Slide Potentiometer
# http://www.seeedstudio.com/wiki/Grove_-_Slide_Potentiometer

import time
import grovepi

# Connect the Grove Slide Potentiometer to analog port A0
# OUT,LED,VCC,GND
slide = 0   # pin 1 (yellow wire)

# The device has an onboard LED accessible as pin 2 on port A0
# OUT,LED,VCC,GND
led = 1     # pin 2 (white wire)

grovepi.pinMode(slide,"INPUT")
grovepi.pinMode(led,"OUTPUT")
time.sleep(1)

while True:
    try:
        # Read sensor value from potentiometer
        sensor_value = grovepi.analogRead(slide)

        # Illuminate onboard LED
        if sensor_value > 500:
            grovepi.digitalWrite(led,1)
        else:
            grovepi.digitalWrite(led,0)

        print "sensor_value =", sensor_value
# Start the communication loop
#client.loop_start()

# Sensor Pin configuration
# Analog Port Declaration for the Sensors
light_sensor_port = 0  # Grove Light Sensor on A0 Port

# Digital Port Declaration
digital_humidity_temperature_sensor_port = 7
ultra_sound_sensor_port = 3
indicator_led_1 = 4
indicator_led_2 = 3

# Setting the PinModes
grovepi.pinMode(light_sensor_port, "INPUT")
grovepi.pinMode(indicator_led_1, "OUTPUT")
grovepi.digitalWrite(indicator_led_1, 0)
grovepi.pinMode(indicator_led_2, "OUTPUT")
grovepi.digitalWrite(indicator_led_2, 0)

# Placeholders for all the sensors.
temperature_humidity_sensor_data = {'temperature': 0, 'humidity': 0}
assistant_control_status = {'light_status': False, 'heater_status': False}

# Threshold for light sensor
threshold_light_sensor = 10
server_address = ("localhost", 6969)
override_assitant = False
listening_message = "listen"
''' Data Packet containing all the sensor information to be transmitted to 
Example #59
0
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 Grove Water Sensor to digital port D2
# SIG,NC,VCC,GND
water_sensor = 2

grovepi.pinMode(water_sensor,"INPUT")

while True:
    try:
        print(grovepi.digitalRead(water_sensor))
        time.sleep(.5)

    except IOError:
        print ("Error")
Example #60
0
import time
import grove_i2c_temp_hum_mini # temp + humidity
import hp206c # altitude + temp + pressure
import grovepi  # used by air sensor and dust sensor
import atexit # used for the dust sensor
import json

# atexit.register(grovepi.dust_sensor_dis)

# Initialize the sensors
# t= grove_i2c_temp_hum_mini.th02()
h= hp206c.hp206c()
# grovepi.dust_sensor_en()
air_sensor = 0
grovepi.pinMode(air_sensor,"INPUT")

ret=h.isAvailable()
if h.OK_HP20X_DEV == ret:
	print "HP20x_dev is available."   
else:
	print "HP20x_dev isn't available."


while True:
	temp = h.ReadTemperature()
	# temp2 = t.getTemperature()
	pressure = h.ReadPressure()
	altitude = h.ReadAltitude()
	# humidity = t.getHumidity()
	air_quality = "--"