Exemple #1
0
 def Get_Data(self):
     import math
     sensor_value = grovepi.temp(0,'1.2')
     sensor_value = round (sensor_value,2)
     
     setText(get_ip_address('eth0')+"\nTemp is:"+str(sensor_value)+"C\n")
     return sensor_value
Exemple #2
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 get_temperature(self):
     """Return the temperature"""
     try:
         import grovepi
     except ImportError:
         return 0
     # On pin A0
     return grovepi.temp(self.analog_temperature, '1.2')
Exemple #4
0
 def get_temperature(self):
     """Return True if the button is pressed, False otherwise"""
     try:
         import grovepi
     except ImportError:
         return
     # On pin A0
     return grovepi.temp(self.analog_temperature, '1.2')
Exemple #5
0
def temp_read(pin_obj):
    if device_type == DEVICE_TYPE_MRAA:
        return pyupm_grove.GroveTemp(pin_obj).value()

    elif device_type == DEVICE_TYPE_RPI:
        raise NotImplementedError

    elif device_type == DEVICE_TYPE_GPI:
        return grovepi.temp(pin_obj, '1.1')
Exemple #6
0
def getSensorData():
    mosfet = 6
    while True:
        sensordata = {}
        try:
            # temp
            temp = grovepi.temp(tempsensor, '1.2')
            #print("temp =", temp)
            temp = float('%.1f' % (temp))
            sensordata["temp"] = temp

            #Moisture
            moisture = grovepi.analogRead(moisturesensor)
            #print(moisture)
            sensordata["mois"] = moisture
            # Get grovepi sensor value
            sensor_value = grovepi.analogRead(light_sensor)
            sensordata["light"] = sensor_value

            # Calculate resistance of sensor in K
            if sensor_value != 0:
                global resistance
                resistance = (float)(1023 - sensor_value) * 10 / sensor_value
            else:
                resistance = 0
            '''
            if moisture < 10:
                grovepi.analogWrite(6,255)
                print ("full speed")
                #sensordata["state"] = "on"
            else:
                grovepi.analogWrite(6,0)
                sensordata["state"] = "off"
                #print ("off")
            '''

            print("sensor_value = %d resistance =%.2f" %
                  (sensor_value, resistance))
            #setText("Temp  Mois light\n%.2f  %d    %d" %(temp, moisture, sensor_value))
            setText_norefresh("Mois Temp  light{}   {}   {}".format(
                str(moisture), str(temp), str(sensor_value)))
            time.sleep(.5)
            return sensordata

        except KeyboardInterrupt:
            grovepi.analogWrite(mosfet, 0)
            break
        except TypeError:

            REPORTER = "Please power off your raspberry3, and start it again!"
            print("The raspberry is overcurrent >>>>>")
            print(REPORTER)
            senderror.wechatreporter("Raspberry3 overcurrent", REPORTER)
            break
        except IOError:
            grovepi.analogWrite(mosfet, 0)
            print("Error")
def read_grove_dht11_sensor(ana_port):
    ''' Read the Grove DHT11 sensor '''
    try:
        temp = grovepi.temp(ana_port, GROVE_DHT11_VERSION)
    except Exception as e:
        # Raise a proper error later
        print('ERROR: Reading temp sensor (DHT11) gave error: {}'.format(e))
        return 'Error'
    return temp
Exemple #8
0
    def getValue3(self):
        print "getting temperature sensor v1.2 value v3..."

        # Get sensor value
        temperature = grovepi.temp(self.port, '1.2')

        print "temperature = %.2f" % (temperature)

        sensors3["temperatureSensor.temperature"] = int(temperature)

        return sensors3
Exemple #9
0
    def getValue(self):
        print "getting temperature sensor v1.2 value..."

        # Get sensor value
        temperature = grovepi.temp(self.port, '1.2')

        print "temperature = %.2f" % (temperature)

        sensors['temperatureSensor'][0]['value'] = int(temperature)

        return sensors
Exemple #10
0
    def demoTemp(self):
        while True:
            try:
                temp = grovepi.temp(sensor, '1.1')
                print("temp =", temp)
                time.sleep(.5)

            except KeyboardInterrupt:
                break
            except IOError:
                print("Error")
Exemple #11
0
 def demoTemp(self):
     while True:
         try:
             temp = grovepi.temp(sensor,'1.1')
             print("temp =", temp)
             time.sleep(.5)
     
         except KeyboardInterrupt:
             break
         except IOError:
             print ("Error")
Exemple #12
0
def greengrass_sensor_run():
    try:
        temp_value = 0.1
        mois_value = 0
        light_value = 0
        switch_status = 0
        lastTemp = 0.1
        lastMois = 0
        # Get value from temperature sensor
        temp_value = grovepi.temp(temp_sensor, "1.2")
        #temp_value = random.uniform(22.0, 23.9)
        # Get value from moisture sensor
        mois_value = grovepi.analogRead(mois_sensor)
        #mois_value = random.randint(150,350)
        # Get value from light sensor
        light_value = grovepi.analogRead(light_sensor)
        #light_value = random.randint(590,620)
        moment = "D" if light_value > 200 else "N"
        # Get status from relay
        switch_status = grovepi.digitalRead(relay)
        #switch_status = random.randint(0,1)
        # Set temperature and moisture to LCD
        if (abs(temp_value - lastTemp) >= 0.1) or (mois_value != lastMois):
            lastTemp = temp_value
            lastMois = mois_value
            bgList = calcBG(mois_value)
            setRGB(bgList[0], bgList[1], bgList[2])
            setText("Temp: %.1f C *%s\nMoisture: %d " %
                    (temp_value, moment, mois_value))

        # build the message to be sent
        message = {
            "clientId": "sensor001",
            "timestamp": int(datetime.now(timezone.utc).timestamp() * 1000),
            "temp": format(temp_value, '0.1f'),
            "moisture": mois_value,
            "light": light_value,
            "switch": switch_status
        }
        logger.info('Triggering publish to topic ' + sensor_topic + ' with ' +
                    json.dumps(message))

        client.publish(topic=sensor_topic,
                       queueFullPolicy='AllOrException',
                       payload=json.dumps(message))
    except IOError:
        logger.error('IO Error')
    except Exception as e:
        logger.error('Failed to publish message: ' + repr(e))

    # Asynchronously schedule this function to be run again in 5 seconds
    Timer(5, greengrass_sensor_run).start()
Exemple #13
0
def main():
   r = redis.Redis()
   while True:
        try:
            temp = grovepi.temp(sensor)
            temp = round(temp,1)
            print "temp =", temp
            r.set('temp', temp)
            time.sleep(10)


        except IOError:
            print "Error"
def getData():
    #Estableciendo que variables son Globales
    global luminosidad
    global temperatura
    global bombillo
    global ventilador

    releer = True

    while releer:
        try:
            # Obtener valor de luz
            luminosidad = grovepi.analogRead(sensorluzpin)

            # Obtener el valor de la temperatura
            temperatura = grovepi.temp(temperatutapin, '1.1')

            #Terminar bucle correctamente
            releer = False
        except:
            print "Error en la lectura de sesnores...volviendo a leer"
            time.sleep(.5)

    #Estado del Bombillo
    if (UmbraldeLuz()):
        bombillo = 1
    else:
        bombillo = 0

    #Estado del Ventilador
    if (UmbraldeTemperatura()):
        ventilador = 1
    else:
        ventilador = 0

    #Imprimir Valores
    ImprimirValorSensores()

    return temperatura, luminosidad, bombillo, ventilador
# NOTE:
# 	The sensor uses a thermistor to detect ambient temperature.
# 	The resistance of a thermistor will increase when the ambient temperature decreases.
#
# 	There are 3 revisions 1.0, 1.1 and 1.2, each using a different model thermistor.
# 	Each thermistor datasheet specifies a unique Nominal B-Constant which is used in the calculation forumla.
#
# 	The second argument in the grovepi.temp() method defines which board version you have connected.
# 	Defaults to '1.0'. eg.
# 		temp = grovepi.temp(sensor)        # B value = 3975
# 		temp = grovepi.temp(sensor,'1.1')  # B value = 4250
# 		temp = grovepi.temp(sensor,'1.2')  # B value = 4250

import time
import grovepi

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

while True:
    try:
        temp = grovepi.temp(sensor, "1.1")
        print "temp =", temp
        time.sleep(0.5)

    except KeyboardInterrupt:
        break
    except IOError:
        print "Error"
def grove():
        threading.Timer(30,grove).start()
        countly.event('Temperature', grovepi.temp(temperature_sensor,'1.1'))
        countly.event("Light", int(grovepi.analogRead(light_sensor)/10.24))
Exemple #17
0
# This is the address of the Atmega328 on the GrovePi
address = 0x04

#Connect to twitter
api = twitter.Api(consumer_key='YourKey',
                  consumer_secret='YourKey',
                  access_token_key='YourKey',
                  access_token_secret='YourKey')
print "Twitter Connected"
grovepi.pinMode(3, "OUTPUT")
last_sound = 0
while True:
    #Error handling in case of problems communicating with the Grove Pi
    try:
        #Get value from temperature sensor
        t = grovepi.temp(2)
        #Get value from light sensor
        light_intensity = grovepi.analogRead(1)
        #Give PWM output to LED
        grovepi.analogWrite(3, light_intensity / 4)
        #Get sound level
        sound_level = grovepi.analogRead(0)
        if sound_level > 0:
            last_sound = sound_level
        #Post a tweet
        print("DI Lab's Temp: %.2f, Light: %d, Sound: %d" %
              (t, light_intensity / 10, last_sound))
        api.PostUpdate("DI Lab's Temp: %.2f, Light: %d, Sound: %d" %
                       (t, light_intensity / 10, last_sound))
        time.sleep(3)
    except IOError:
Exemple #18
0
                else:
                    subMenuSelected = True
            elif display != MENU_DISPLAY:
                backLight = not (backLight)
            else:
                menu = True
                subMenu = 0
                subMenuSelected = False

        # Process sensor data
        period += 1
        #print "Period is " + str(period) + " of " + str(PUBLISH_PERIODS)
        if period >= PUBLISH_PERIODS:
            # Get sensor data
            period = 0
            temp = grovepi.temp(TEMPERATURE_PIN, '1.1')
            #print "  Temp =", temp
            sound = grovepi.analogRead(SOUND_PIN)
            #print "  Sound =", sound
            light = grovepi.analogRead(LIGHT_PIN)
            #print "  Light =", light

            # Check if Internet is available
            print "Internet on " + str(internet_on())

            os.system("./netcheck")

            # Publish sensor data
            client.publish(TEMPERATURE_TOPIC, str(temp * 10))
            client.publish(LIGHT_TOPIC, str(light))
Exemple #19
0
def grove():
    threading.Timer(30, grove).start()
    countly.event('Temperature', grovepi.temp(temperature_sensor, '1.1'))
    countly.event("Light", int(grovepi.analogRead(light_sensor) / 10.24))
Exemple #20
0
# SIG,NC,VCC,GND
temp_sensor = 1

# Connect the Grove Sound Sensor to analog port A2
# SIG,NC,VCC,GND
sound_sensor = 2

while True:
    try:
        # Get the current timestamp.
        now = datetime.datetime.now()
        timestamp = str(now)

        # Get sensor values.
        lightLevel = grovepi.analogRead(light_sensor)
        temp = grovepi.temp(temp_sensor, '1.1')
        soundLevel = grovepi.analogRead(sound_sensor)
        # TODO: Get this from a humidity sensor.
        humidity = "75"

        # Show the sensor values for debugging.
        print ("timestamp=", timestamp)
        print ("lightLevel=", lightLevel)
        print ("temp=", temp)
        print ("soundLevel=", soundLevel)

        # Send the sensor data to the Google Spreadsheet through Temboo.
        # Create a session with your Temboo account details
        session = TembooSession(“USERID”, “APPNAME”, “APPKEY”)

        # Instantiate the Choreo
Exemple #21
0
# digital write
grovepi.digitalWrite(2, 1)
grovepi.digitalWrite(2, 0)
time.sleep(1)
grovepi.digitalWrite(5, 0)
grovepi.digitalWrite(6, 0)
time.sleep(1)
grovepi.digitalWrite(5, 1)
grovepi.digitalWrite(6, 1)
time.sleep(1)
grovepi.digitalWrite(5, 0)
grovepi.digitalWrite(6, 0)
time.sleep(1)

# read temp
grovepi.temp(7)
grovepi.dht(7, 0)

# module_type:
#             DHT11 0
#             DHT22 1
#             DHT21 2
#             DHT2301 3

# read ultrasonic
grovepi.ultrasonicRead(4)

import grove_rgb_lcd as lcd
# set background to red, green and blue
lcd.setRGB(200, 0, 0)
time.sleep(1)
import grovepi

from common.Countly import Countly

temperature_sensor = 1
light_sensor = 0

countly = Countly("SERVER_URL", "APP_KEY", 5)
countly.event('Temperature', grovepi.temp(temperature_sensor, '1.1'))
countly.event("Light", int(grovepi.analogRead(light_sensor) / 10.24))
Exemple #23
0
# GrovePi + Grove Temperature Sensor
# http://www.seeedstudio.com/wiki/Grove_-_Temperature_Sensor

import grovepi

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

while True:
    try:
        temp = grovepi.temp(sensor)
        print "temp =", temp

    except IOError:
        print "Error"
Exemple #24
0
lcdDisplay.setText("Ready to Go!")
time.sleep(2)

with open(str(int(time.time())) + '.csv', 'wb') as csvfile:
    datawriter = csv.writer(csvfile,
                            delimiter=',',
                            quotechar='|',
                            quoting=csv.QUOTE_MINIMAL)
    datawriter.writerow([
        'temperature', 'sound', 'pressure', 'latitude', 'longitude', 'altitude'
    ])

while True:
    try:
        lcdDisplay.setText("Gathering Data")
        curTemp = gpi.temp(TEMP_SENSOR)  # Get temperature in celcius
        # Get current sound level in ???
        curSound = gpi.analogRead(SOUND_SENSOR)
        curPressure = bmpSensor.readPressure(
        ) / 100  # Get current presure in millibar
        curCoords = gpsSensor.read(
        )  # Get the current data from the GPS module

        print str(curTemp) + ', ' + str(curSound) + ', ' + \
            str(curPressure)  # Print Current Readings from Sensors
        print str(curCoords.latitude) + ', ' + str(curCoords.longitude) + \
            ', ' + str(curCoords.altitude)  # Print Current Readings from GPS
        lcdDisplay.setText("Saved Data")

        message = [curCoords.latitude, curCoords.longitude, curCoords.altitude]
# 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)

while True:
    try:
        grovepi.fourDigit_brightness(display,2)

        #seconds = 10
        #grovepi.fourDigit_monitor(display,sensor,seconds)
        temp = round(grovepi.temp(sensor,'1.2'), 2)
        grovepi.fourDigit_init(display)
        grovepi.fourDigit_number(display,int(temp * 100),0)
        #print(temp.__class__)
        #print("temp =", temp)
        time.sleep(.5)

    except KeyboardInterrupt:
        grovepi.fourDigit_off(display)
        break
    except IOError:
        print ("Error")
Exemple #26
0
def main():
    global isConnected
    global Like
    global tempL  ##  Added this
    # 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 and Light port for output/ input.
    grovepi.pinMode(led, "OUTPUT")
    time.sleep(1)
    grovepi.pinMode(light_sensor,"INPUT")

    # Loop forever.
    while True:

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

            # check for likes
            print("Getting likes...")
            page_data = get_page_data(page_id, token)
            Like = str(page_data['likes'])
            print("Likes: " + Like)

            if int(Like) > 0  and int(Like)>  int(tempL):

                print(tempL)
                print("Inside if -success 1")
                # Buzz for 1 second
                grovepi.digitalWrite(buzzer,1)
                print ('start')
                time.sleep(3)

        # Stop buzzing for 1 second and repeat
                grovepi.digitalWrite(buzzer,0)
                print ('stop')
                time.sleep(1)
                digitalWrite(led, 1)  # Send HIGH to switch on LED
                time.sleep(10)
                digitalWrite(led, 0)  # Send HIGH to switch on LED
                tempL = Like
                GPIO.cleanup()
                GPIO.setmode(GPIO.BOARD)
                m = Motor([18,22,24,26])

                m.rpm = 5
                print("Motor start 2 0")
                m.move_to(0)
                sleep(1)
                print("Motor start 2 90")
                m.move_to(90)

                sleep(5)
                m.mode = 2
                print("Motor start 2 again 0")
                m.move_to(0)
                GPIO.cleanup()
            #elif (int(Like) = int(tempL)):
              #  #tempL = int(Like) + int(1)
                #print(tempL)
                #print("Inside if -success 2")
                #digitalWrite(led, 1)  # Send HIGH to switch on LED
                #time.sleep(10)
                #digitalWrite(led, 0)  # Send HIGH to switch on LED

            else:
                print(" not inside if -not success")
                digitalWrite(led, 0)  # Send LOW to switch off LED
                print(tempL)
                time.sleep(5)

            # 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),
                        "Likes":Like,
                        "timestamp": datetime.datetime.now().isoformat()

                    }
                }
            }

            light_value = grovepi.analogRead(light_sensor)
            print ("Light Level =",light_value)

            if threshold > light_value:
                 print("light value is low ")
                 browser = webdriver.Firefox()

                 browser.get('http://www.proprofs.com/survey/stats/?title=tm54n&shr-id=a22c0d0970ca238804d1c5e8cc270a4c&oeq=946003f97ccc52d5d3b54ac0ec31bbfc')
                 # Save the window opener (current window, do not mistaken with tab... not the same)
                 main_window = browser.current_window_handle
                 browser.maximize_window()
                 sleep(2)
                 print ('LAST STEP')
                 #browser.close() #closes new tab
                 sleep(1)
                 browser.get('http://tp-iot.weebly.com')
                 #webbrowser.get('Firefox').open('file:///home/pi/Desktop/QR.html')
                 #browser.get('file:///home/pi/Desktop/QR.html')
                 # Save the window opener (current window, do not mistaken with tab... not the same)
                 sleep (1)
                 #browser.get('Firefox').close('file:///home/pi/Desktop/QR.html')
                 browser.close() #closes new tab

            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")
            driver.refresh()
            # Wait 30 seconds before sending the next set of sensor data.
            #schedule.run_pending()
            time.sleep(30)

        except KeyboardInterrupt:
            break
        except Exception as e:
            # For all other errors, we wait a while and resume.
            print("Exception: " + str(e))
            time.sleep(10)
            continue
Exemple #27
0
# GrovePi + Grove Temperature & Humidity Sensor Pro
# http://www.seeedstudio.com/wiki/Grove_-_Temperature_and_Humidity_Sensor_Pro

import grovepi

# Connect the Grove Temperature & Humidity Sensor Pro to digital port D4
# SIG,NC,VCC,GND
dht_sensor = 2
analog_sensor = 2
while True:
    try:
        [temp_dht, humidity] = grovepi.dht(dht_sensor, 1)
        print "dht_temp =", temp_dht, " humidity =", humidity
        analog_temp = grovepi.temp(analog_sensor)
        print "analog_temp = ", analog_temp

    except IOError:
        print "IOError"
Exemple #28
0
    def run(self):

        currentEI = 0  # This variable is used to avoid the transmission of multiple ER for the same set of detected EI

        while True:
            try:
                ## Check all connected sensors

                ## Only humidity is taken from DHT11, since the detectable temperature range is short
                [temp, humidity] = grovepi.dht(
                    sensorHumidity, 0
                )  #0 because the component is the "blue" one; 1 is for the "white" (DHT22) sensor
                noise = grovepi.analogRead(sensorAudio)
                noise = 20 * math.log(
                    noise, 10
                )  #Simple simplification to return value in dB (approximation, since the sensor is not calibrated)
                smoke = grovepi.analogRead(
                    sensorSmoke)  #MQ-2 reading (is also needs calibration)
                water = grovepi.digitalRead(
                    sensorWater)  #Returns 1 if it is dry, and 0 otherwise
                temperature = grovepi.temp(
                    sensorTemperature,
                    '1.2')  #This sensor has a better temperature range

                if debug:
                    print("\nSensed data at", datetime.datetime.today())
                    print("Relative humidity:", humidity, "%")
                    print("Noise:", noise, "dB")
                    print("Smoke:", smoke, "ppm")
                    if water == 1:
                        print("Water:", water, "- It is dry.")
                    else:
                        print("Water:", water, "- It is wet.")
                    print("Temperature:", temperature, "C")

                ## Test if any EI was detected.
                ## The sensors are mapped to the corresponding value of Y
                detectEI(humidity, events.getEventY(3))
                detectEI(noise, events.getEventY(8))
                detectEI(smoke, events.getEventY(4))
                detectEI(water, events.getEventY(16))
                ## Temperature is related to two EI (Heating and Freezing)
                detectEI(temperature, events.getEventY(1))
                detectEI(temperature, events.getEventY(2))

                ## If debug=False, only the LCD display will show information about detected events
                showDetectedEI()

                ## In this thread, a new ER is sent only when the current status of detected
                ## events is chaged
                if events.getNumberDetectedEI() == 0:
                    currentEI = 0
                elif events.getNumberDetectedEI(
                ) > 0 and currentEI != events.getNumberDetectedEI():
                    if debug:
                        print(
                            "A new EI was detected. An ER will be created...")
                    currentEI = events.getNumberDetectedEI()
                    createER(self)

            except (IOError, TypeError) as e:
                print(str(e))

            ## Frequency of monitoring
            time.sleep(fs)
Exemple #29
0
# This is the address of the Atmega328 on the GrovePi
address = 0x04

# Connect to twitter
api = twitter.Api(
    consumer_key="YourKey", consumer_secret="YourKey", access_token_key="YourKey", access_token_secret="YourKey"
)
print "Twitter Connected"
grovepi.pinMode(3, "OUTPUT")
last_sound = 0
while True:
    # Error handling in case of problems communicating with the Grove Pi
    try:
        # Get value from temperature sensor
        t = grovepi.temp(2)
        # Get value from light sensor
        light_intensity = grovepi.analogRead(1)
        # Give PWM output to LED
        grovepi.analogWrite(3, light_intensity / 4)
        # Get sound level
        sound_level = grovepi.analogRead(0)
        if sound_level > 0:
            last_sound = sound_level
            # Post a tweet
        print ("DI Lab's Temp: %.2f, Light: %d, Sound: %d" % (t, light_intensity / 10, last_sound))
        api.PostUpdate("DI Lab's Temp: %.2f, Light: %d, Sound: %d" % (t, light_intensity / 10, last_sound))
        time.sleep(3)
    except IOError:
        print "Error"
    except:
Exemple #30
0
temperature_sensor = 2  # port A2
led = 3                 # port D3

# Connect to Twitter
api = twitter.Api(consumer_key='YourKey',consumer_secret='YourKey',access_token_key='YourKey',access_token_secret='YourKey')
print "Twitter Connected"

grovepi.pinMode(led,"OUTPUT")

last_sound = 0

while True:
    # Error handling in case of problems communicating with the GrovePi
    try:
        # Get value from temperature sensor
        t = grovepi.temp(temperature_sensor)

        # 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)
        if sound_level > 0:
            last_sound = sound_level

        # Post a tweet
        print ("DI Lab's Temp: %.2f, Light: %d, Sound: %d" %(t,light_intensity/10,last_sound))
        api.PostUpdate("DI Lab's Temp: %.2f, Light: %d, Sound: %d" %(t,light_intensity/10,last_sound))
Exemple #31
0
# Connect to Twitter
api = twitter.Api(consumer_key='YourKey',
                  consumer_secret='YourKey',
                  access_token_key='YourKey',
                  access_token_secret='YourKey')
print "Twitter Connected"

grovepi.pinMode(led, "OUTPUT")

last_sound = 0

while True:
    # Error handling in case of problems communicating with the GrovePi
    try:
        # Get value from temperature sensor
        t = grovepi.temp(temperature_sensor)

        # 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)
        if sound_level > 0:
            last_sound = sound_level

        # Post a tweet
        print("DI Lab's Temp: %.2f, Light: %d, Sound: %d" %
              (t, light_intensity / 10, last_sound))
import time
import grovepi

period = 500000
ap = argparse.ArgumentParser()
ap.add_argument("-y",
                "--yaks",
                type=str,
                default="127.0.0.1",
                help="the YAKS instance")
ap.add_argument("-u", "--uri", required=True, help="the publication path")
ap.add_argument("-p", "--pin", required=True, help="GrovePi Pin")

args = vars(ap.parse_args())

pin = int(args['pin'])

y = Yaks.login(args['yaks'])
path = args['uri']
ws = y.workspace('/')

while True:
    try:
        value = grovepi.temp(pin, '1.2')
        print("value = {}".format(value))
        ws.put(path, Value(str(value), encoding=Encoding.STRING))
        time.sleep(.5)

    except IOError:
        print("Error")
import sys
import os.path

sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))

import grovepi

from common.Countly import Countly

temperature_sensor = 1
light_sensor = 0

countly = Countly("SERVER_URL", "APP_KEY", 5)
countly.event('Temperature', grovepi.temp(temperature_sensor,'1.1'))
countly.event("Light", int(grovepi.analogRead(light_sensor)/10.24))
Exemple #34
0
                else:
                    subMenuSelected = True
            elif display != MENU_DISPLAY:
                backLight = not(backLight)
            else:
                menu = True
                subMenu = 0
                subMenuSelected = False

        # Process sensor data
        period += 1
        #print "Period is " + str(period) + " of " + str(PUBLISH_PERIODS)
        if period >= PUBLISH_PERIODS:
	        # Get sensor data
	        period = 0        
	        temp = grovepi.temp(TEMPERATURE_PIN,'1.1')
	        #print "  Temp =", temp
	        sound = grovepi.analogRead(SOUND_PIN)
	        #print "  Sound =", sound
	        light = grovepi.analogRead(LIGHT_PIN)
	        #print "  Light =", light
	                         
	        # Check if Internet is available
	        print "Internet on " + str(internet_on())
	        
	        os.system("./netcheck")
	        
	        # Publish sensor data
	        client.publish(TEMPERATURE_TOPIC,str(temp*10));
	        client.publish(LIGHT_TOPIC,str(light));
Exemple #35
0
def main():
    global isConnected
    global Like
    global tempL  ##  Added this
    # 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:

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

            # check for likes
            print("Getting likes...")
            page_data = get_page_data(page_id, token)
            Like = str(page_data['likes'])
            print("Likes: " + Like)

            if int(Like) > 0  and int(Like)>  int(tempL):

                print(tempL)
                print("Inside if -success 1")
                # Buzz for 1 second
                grovepi.digitalWrite(buzzer,1)
                print ('start')
                time.sleep(1)

        # Stop buzzing for 1 second and repeat
                grovepi.digitalWrite(buzzer,0)
                print ('stop')
                time.sleep(1)
                digitalWrite(led, 1)  # Send HIGH to switch on LED
                time.sleep(10)
                digitalWrite(led, 0)  # Send HIGH to switch on LED
                tempL = Like
            #elif (int(Like) = int(tempL)):
              #  #tempL = int(Like) + int(1)
                #print(tempL)
                #print("Inside if -success 2")
                #digitalWrite(led, 1)  # Send HIGH to switch on LED
                #time.sleep(10)
                #digitalWrite(led, 0)  # Send HIGH to switch on LED

            else:
                print(" not inside if -not success")
                digitalWrite(led, 0)  # Send LOW to switch off LED
                print(tempL)
                time.sleep(5)

            # 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),
                        "Likes":Like,
                        "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")
            driver.refresh()
            # Wait 30 seconds before sending the next set of sensor data.
            #schedule.run_pending()
            time.sleep(30)

        except KeyboardInterrupt:
            break
        except Exception as e:
            # For all other errors, we wait a while and resume.
            print("Exception: " + str(e))
            time.sleep(10)
            continue
Exemple #36
0
        #Flame Sensor
        flame = grovepi.digitalRead(flame_sensor)
        if flame==0 or flame==1:	
            if flame==0:
                print ('Flame Detected')
                print("----------------")
                print("")

            else:
                print ('Flame Not Detected')
                print("----------------")
                print("")

    	# This example uses the blue colored sensor. 
        # The first parameter is the port, the second parameter is the type of sensor.
        temp = grovepi.temp(sensor,'1.1')
        print("Temperature =", temp,"C")
        print("----------------")
        print("")



        # Get touch sensor value
        touch = grovepi.digitalRead(touch_sensor)
        if touch==0 or touch==1:	
            if touch==1:
                print ('Touch Detected')
                print("---------------------")
                print("")
            else:
                print ('Touch Not Detected')
Exemple #37
0
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 temperature
            temp = grovepi.temp(temp_sensor,'1.1')
            distance_in_cm = grovepi.ultrasonicRead(ultrasonic_ranger)
           

            if distance_in_cm > 3 and distance_in_cm < 7 :
               grovepi.digitalWrite(led,1)  
               grovepi.digitalWrite(buzzer,0)
               msg = "Distance between bike and ground is more than 20 cm  ->Led on} : value of distance is %d " %distance_in_cm
            elif  distance_in_cm >= 7 :
               grovepi.digitalWrite(led, 1)
               grovepi.digitalWrite(buzzer,1)
               msg = "To much gap between bike and ground :->led on/buzzer on : value of distance is %d" %distance_in_cm
            else: 
               grovepi.digitalWrite(led,0)  
               grovepi.digitalWrite(buzzer,0)
               msg = "OK : distance is less than 20 cm: value of distance is %d" %distance_in_cm 

        #except KeyboardInterrupt:
        #    break
        #except IOError:
        #    print("error");
 
            #Get light sensor(LDR)/Sound_sensor value
            light_sensor_value = grovepi.analogRead(light_sensor)
            loudness_sensor_value = grovepi.analogRead(sound_sensor)
            axes = adxl345.getAxes(True)
            
            #time.sleep(1)
            # led off - buzzer off
            #grovepi.digitalWrite(led,0) 
            #grovepi.digitalWrite(buzzer,0)
            #time.sleep(1)
        
               # print ("temp =", temp)
                # Prepare our sample data in JSON format.
            payload = {
                "state": {
                    "reported": {
                        "temperature": temp,
                        "humidity": 55,
                        "light_level": light_sensor_value,
                        "sound_level": loudness_sensor_value,
                        "message": msg,
                        "distance":distance_in_cm,
                        "accelerometer":axes, 
                        "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(0.5)

        except KeyboardInterrupt:
            # Stop the program when we press Ctrl-C.
            break
        except IOError:
            # Some I/O problem happened.
            print("I/O Error")
            continue
        except:
            # For all other errors, we wait a while and resume.
            time.sleep(10)
            continue
# NOTE: 
# 	The sensor uses a thermistor to detect ambient temperature.
# 	The resistance of a thermistor will increase when the ambient temperature decreases.
#	
# 	There are 3 revisions 1.0, 1.1 and 1.2, each using a different model thermistor.
# 	Each thermistor datasheet specifies a unique Nominal B-Constant which is used in the calculation forumla.
#	
# 	The second argument in the grovepi.temp() method defines which board version you have connected.
# 	Defaults to '1.0'. eg.
# 		temp = grovepi.temp(sensor)        # B value = 3975
# 		temp = grovepi.temp(sensor,'1.1')  # B value = 4250
# 		temp = grovepi.temp(sensor,'1.2')  # B value = 4250

import time
import grovepi

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

while True:
    try:
        temp = grovepi.temp(sensor,'1.1')
        print("temp =", temp)
        time.sleep(.5)

    except KeyboardInterrupt:
        break
    except IOError:
        print ("Error")
Exemple #39
0
import grovepi
import time

light_sensor = 2  # A2
temp_sensor = 0  # A0
humidity_sensor = 6  # A6

while True:
    try:

        light_value = grovepi.analogRead(light_sensor)
        print("Niveaux de limiere :", light_value, "Lux")

        temp_value = grovepi.temp(temp_sensor, 1.2)
        print("Temperature :", temp_value, "Degres Celsius")

        humidity_value = grovepi.analogRead(humidity_sensor)
        print("Taux d humidite :", humidity_value)

        time.sleep(1)

    except IOError:
        print("Error")