예제 #1
0
def collect_sensor_data():
    """Collects temperature and humidity data
    :return: The temperature and humidity data collected, formated with
             atmospheric pressure, air speed, metabolic rate, and clothing level.
    :rtype: list of tuples
    """
    sensor_data = []
    try:
        for y in range(3):
            [temp, humid] = grovepi.dht(DHT_SENSOR_PORT, BLUE_DHT)
            if not math.isnan(temp) and not math.isnan(humid):
                t_str = str(temp)
                h_str = str(humid)
                grove_rgb_lcd.setRGB(127, 127, 127)
                grove_rgb_lcd.setText_norefresh("Tmp: {} C\nHmd: {} %".format(
                    t_str, h_str))
                sensor_data.append(([[1013.25, 0.1, humid, 1.0, 0.61, temp]]))
            # For DHT11, wait three seconds before next reading
            time.sleep(3)
            grove_rgb_lcd.setRGB(0, 0, 0)
    except (IOError, TypeError) as ex:
        print("Error: {}".format(str(ex)))
        shutdown_board()
    except KeyboardInterrupt:
        shutdown_board()
    for index, data in enumerate(sensor_data):
        print("Sample #{0} collected: {1}".format(index + 1, data))
    shutdown_board()
    return sensor_data
예제 #2
0
def sensors_test():
    """Test the GrovePi DHT sensor, LEDs and RGB LCD screen."""
    try:
        for y in range(3):
            # Get sensor data and actuate LEDs and RGB LCD screen
            [temp, humid] = grovepi.dht(DHT_SENSOR_PORT, BLUE_DHT)
            if not math.isnan(temp) and not math.isnan(humid):
                if temp >= 20.0:
                    # Temperature is good: Everything is green.
                    grove_rgb_lcd.setRGB(0, 255, 0)
                    grovepi.digitalWrite(GREEN_LED, ON)
                    time.sleep(2)
                    grovepi.digitalWrite(GREEN_LED, OFF)
                else:
                    # Temperature is too low: Turn to red.
                    grove_rgb_lcd.setRGB(255, 0, 0)
                    grovepi.digitalWrite(RED_LED, ON)
                    time.sleep(2)
                    grovepi.digitalWrite(RED_LED, OFF)
                t_str = str(temp)
                h_str = str(humid)
                print("Temperature: {}C | Humidity: {}%".format(t_str, h_str))
                grove_rgb_lcd.setText_norefresh("Tmp: {} C\nHmd: {} %".format(
                    t_str, h_str))
            # For DHT22, wait three seconds before next reading
            time.sleep(3)
            grove_rgb_lcd.setRGB(0, 0, 0)
    except (IOError, TypeError) as ex:
        print("Error: {}".format(str(ex)))
        shutdown_board()
    except KeyboardInterrupt:
        shutdown_board()
    shutdown_board()
예제 #3
0
def doorbell_callback(client, userdata, msg):
    if lock_status:
        with lock:
            grove_rgb_lcd.setRGB(0, 0, 255)
            grove_rgb_lcd.setText_norefresh(
                "Doorbell Rung   \nStatus: Unlocked")
            grovepi.digitalWrite(buzzer, 1)
            time.sleep(0.3)
            grovepi.digitalWrite(buzzer, 0)
            time.sleep(0.1)
            grovepi.digitalWrite(buzzer, 1)
            time.sleep(0.1)
            grovepi.digitalWrite(buzzer, 0)
    else:
        with lock:
            grove_rgb_lcd.setRGB(0, 0, 255)
            grove_rgb_lcd.setText_norefresh(
                "Doorbell Rung   \nStatus: Locked  ")
            grovepi.digitalWrite(buzzer, 1)
            time.sleep(0.5)
            grovepi.digitalWrite(buzzer, 0)
            time.sleep(0.1)
            grovepi.digitalWrite(buzzer, 1)
            time.sleep(0.1)
            grovepi.digitalWrite(buzzer, 0)
    time.sleep(1)
예제 #4
0
def display(inTemp, outTemp, setTemp, HVACset, windowMode):
    global HVAC
    in_out = [setTemp, outTemp]
    mode = ['Desired: ', 'Outdoor: ']
    if (windowMode == 0 or windowMode == 1):
        lcd.setText_norefresh(
            "Temp: " + "{:>3}".format(inTemp) + "F  " +
            "{:>4}\n".format(HVAC[HVACset]) +
            "{:>8} {:>3}F".format(mode[windowMode], in_out[windowMode]))
    else:
        lcd.setText_norefresh("Set Temp: " + "{:>3}F".format(setTemp))
예제 #5
0
def lcd_update():
    while True:
        potentiometer_read = grovepi.analogRead(potentiometer)
        voltage = round((float)(potentiometer_read) * adc_ref / 1023, 2)
        degrees = round((voltage * full_angle) / grove_vcc, 2)
        level = int(degrees / full_angle * 5)
        if level >= len(word_list):
            level = len(word_list) - 1
        print(word_list[level])
        lcd.setText_norefresh(
            str(level + 1) + ": {:<13}".format(word_list[level][0]) +
            "\nTyped " + str(word_list[level][1]) + " times    \n")
def lcdcallback(client, userdata, msg):
    keyvalue = str(msg.payload, "utf-8")  #w, a, s, or d
    print(keyvalue)
    with lock:
        grove_rgb_lcd.setText_norefresh(f"{keyvalue}")  #display key on lcd
        if keyvalue == "w":
            grove_rgb_lcd.setRGB(255, 255, 255)  #make white
        if keyvalue == "a":
            grove_rgb_lcd.setRGB(255, 0, 0)  #make red
        if keyvalue == "s":
            grove_rgb_lcd.setRGB(0, 255, 0)  #make green
        if keyvalue == "d":
            grove_rgb_lcd.setRGB(0, 0, 255)  #make blue
예제 #7
0
 def output_screen(self,
                   text,
                   color="green"):  ###########didnt mention port number
     pallete = {
         "white": (255, 255, 255),
         "red": (255, 0, 0),
         "green": (0, 255, 0),
         "blue": (0, 0, 255),
         "black": (0, 0, 0)
     }
     # port = ports["sensors"]["I2C"]["lcd"]
     if text != self.lastText:
         # lcd.setRGB(pallete[color][0], pallete[color][1], pallete[color][2])
         lcd.setText_norefresh(text)
         self.lastText = text
예제 #8
0
def process_sensor_data(label_names, selected_model, sensor_data):
    """Classify unlabeled sensor data against the selected model and get a prediction.

    :param label_names: The list of labels.
    :type label_names: list
    :param selected_model: The most accurate classifer model in the form of a history object.
    :type selected_model: object
    :param sensor_data: The temperature and humidity data collected, formated with
                        atmospheric pressure, air speed, metabolic rate, and clothing level.
    :type sensor_data: list of tuples
    """
    try:
        sensor_data = ast.literal_eval(sensor_data)
        sensation = 0
        for j, data in enumerate(sensor_data, start=1):
            print("Sensor data #{}: Prediction: {}".format(
                j, label_names[int(selected_model[1].predict(data))]))
            sensation += int(selected_model[1].predict(data))
        sensation = int(sensation / len(sensor_data))
        print("Overall sensation: {} ({})".format(
            sensation, label_names[sensation]))
        grove_rgb_lcd.setText_norefresh(
            "Sensation:\n{} ({})".format(sensation, label_names[sensation]))
        if sensation == 3:
            # Temperature is good: Everything is green.
            grove_rgb_lcd.setRGB(0, 255, 0)
            grovepi.digitalWrite(GREEN_LED, ON)
            time.sleep(2)
            grovepi.digitalWrite(GREEN_LED, OFF)
            grove_rgb_lcd.setRGB(0, 0, 0)
            grove_rgb_lcd.setText_norefresh("")
        else:
            # Temperature is too low: Turn to red.
            grove_rgb_lcd.setRGB(255, 0, 0)
            grovepi.digitalWrite(RED_LED, ON)
            time.sleep(2)
            grovepi.digitalWrite(RED_LED, OFF)
    except (IOError, TypeError) as ex:
        print("Error: {}".format(str(ex)))
        shutdown_board()
    except KeyboardInterrupt:
        shutdown_board()
    time.sleep(3)
    shutdown_board()
예제 #9
0
def sensor_test():
    """Collects and displays temperature and humidity data"""
    sensor_data = []

    for x in range(10):
        try:
            for y in range(3):
                [temp, humid] = grovepi.dht(DHT_SENSOR_PORT, BLUE_DHT)
                if not math.isnan(temp) and not math.isnan(humid):
                    if temp >= 20.0:
                        # Temperature is good: Everything is green.
                        grove_rgb_lcd.setRGB(0, 255, 0)
                        grovepi.digitalWrite(GREEN_LED, ON)
                        time.sleep(2)
                        grovepi.digitalWrite(GREEN_LED, OFF)
                    else:
                        # Temperature is too low: Turn to red.
                        grove_rgb_lcd.setRGB(255, 0, 0)
                        grovepi.digitalWrite(RED_LED, ON)
                        time.sleep(2)
                        grovepi.digitalWrite(RED_LED, OFF)
                    t_str = str(temp)
                    h_str = str(humid)
                    print("Temperature: {}C | Humidity: {}%".format(t_str, h_str))
                    grove_rgb_lcd.setText_norefresh(
                        "T: {} C\nH: {} %".format(temp, humid))
                    sensor_data.append([temp, humid])
                # For DHT11, wait three seconds before next reading
                time.sleep(3)
        except (IOError, TypeError) as ex:
            print("Error: {}".format(str(ex)))
            shutdown_board()
        except KeyboardInterrupt:
            shutdown_board()
        print(sensor_data)
        # Wait 30 seconds before collecting next set of data
        grove_rgb_lcd.setRGB(0, 0, 0)
        time.sleep(30)
    shutdown_board()
예제 #10
0
def on_message(client, userdata, msg):
    emotion = str(msg.payload, "utf-8")
    
    
    if emotion == "positive":
        lcd.setRGB(255,165,0) #orange
        lcd.setText_norefresh('positive')
    elif emotion == "negative":
        lcd.setRGB(255,255,0) #yellow
        lcd.setText_norefresh('negative')
    else: #neutral
        lcd.setRGB(0,255,0) #green
        lcd.setText_norefresh('neutral')
예제 #11
0
def door_status_callback(client, userdata, msg):
    door_status = str(msg.payload, "utf-8")
    if lock_status is 0:
        if door_status == "Motion Detected":
            with lock:
                grove_rgb_lcd.setRGB(255, 165, 0)
                grove_rgb_lcd.setText_norefresh(
                    "Motion Detected \nStatus: Locked  ")
            with lock:
                grovepi.digitalWrite(buzzer, 0)
        elif door_status == "SAFETY MODE":
            with lock:
                grove_rgb_lcd.setRGB(255, 0, 0)
                grove_rgb_lcd.setText_norefresh(
                    "SAFETY MODE     \nStatus: Locked  ")
            with lock:
                grovepi.digitalWrite(buzzer, 1)
        else:
            with lock:
                grove_rgb_lcd.setRGB(255, 255, 255)
                grove_rgb_lcd.setText_norefresh(
                    "No Motion       \nStatus: Locked  ")
            with lock:
                grovepi.digitalWrite(buzzer, 0)
예제 #12
0
def shutdown_board():
    """Turns off LEDs and clears LCD screen"""
    grovepi.digitalWrite(RED_LED, OFF)
    grovepi.digitalWrite(GREEN_LED, OFF)
    grove_rgb_lcd.setRGB(0, 0, 0)
    grove_rgb_lcd.setText_norefresh("")
예제 #13
0
                        break
                    if (sensor_value > 30):
                        setRGB(255, 69, 0)
                        setText_norefresh("Alarm           \nDeactivated     ")
                        time.sleep(2)
                        state = 0
                        break
                    time.sleep(0.4)

        # state 2 --> safety mode
        elif (timer is -1 and state is 2):
            while (state is 2):
                client.publish("timandrew/door_status", "SAFETY MODE")
                with lock:
                    setRGB(255, 0, 0)
                    grove_rgb_lcd.setText_norefresh(
                        "SAFETY MODE     \nStatus: " + lock_status + "  ")
                    if (lock_status == "Unlocked"):
                        break
        else:
            #state 0 --> sensor active
            client.publish("timandrew/door_status", "NO MOTION")
            with lock:
                setRGB(255, 255, 255)
                grove_rgb_lcd.setText_norefresh("SENSOR ACTIVE   \nStatus: " +
                                                lock_status + "  ")

    elif lock_status == "Unlocked":
        #reinitialize
        state = 0
        timer = 20
        with lock:
예제 #14
0
def main():
    global desired_temp_min 
    global desired_temp_max    
    global indoor_temp 
    global outdoor_temp 
    global temp 
    global desired_temp 
    global mode 
    global hvac 
    global wind_on
    global wind_off
    global i
    global flag

    read()

    while True:
        try:
            # Get indoor temp
            indoor_temp = int(get_indoor_temp())
            
            # lcd sleep after 5 seonds
            time.sleep(.2)
            button_status = grovepi.digitalRead(button)
            i = i + 1

            # if lcd is off turn on, if lcd is on change mode and sound buzzer
            # lcd sleep after 5 seconds
            if i < 6:
                if button_status:     
                    i = 0
                    lcd.setRGB(0,122,0)
                    grovepi.digitalWrite(buzzer_pin, 1)
                    time.sleep(.1)
                    grovepi.digitalWrite(buzzer_pin, 0)                    
                    if (mode <= 2):
                        mode = mode + 1
                    else:
                        mode = 0
            else:
                lcd.setRGB(0,0,0)
                print("asleep")
                if button_status:
                    i = 0
                    lcd.setRGB(0,122,0)
     
            # state machine for window
            if (indoor_temp > desired_temp):
                if (outdoor_temp < desired_temp):
                    if hvac != "wind":
                        # send open window
                        client.publish("rpi-jaeishin/HVAC", str(wind_on))
                        print(wind_on)
                    hvac = "wind"
                else:
                    if hvac == "wind":
                        # send close window
                        client.publish("rpi-jaeishin/HVAC", str(wind_off))
                        print(wind_off)
                    hvac = "AC"

            if (indoor_temp < desired_temp):
                if (outdoor_temp < desired_temp):
                    if hvac == "wind":
                        # send close window
                        client.publish("rpi-jaeishin/HVAC", str(wind_off))
                        print(wind_off)
                    hvac = "heat"
                else:
                    if hvac != "wind":
                        # send open window
                        client.publish("rpi-jaeishin/HVAC", str(wind_on))
                        print(wind_on)
                    hvac = "wind"

            if (indoor_temp == desired_temp):
                # send message close window
                if hvac == "wind":
                    client.publish("rpi-jaeishin/HVAC", str(wind_off))
                    print(wind_off)
                hvac = "fan"

            # measure outdoor temp from API
            outdoor_temp = int(get_weather(DEFAULT_ZIP))


            # Set LED to print in correct format

            #default
            if (mode == 1):
                print ("\nmode = 1 - Default")
                print("Temp: {:>3}F  {:>4}".format(indoor_temp, hvac))
                print("Desired: {:>3}F".format(desired_temp))
                lcd.setText_norefresh("Temp: {:>3}F {:>4}\nDesired: {:>3}F".format(indoor_temp, hvac, desired_temp))
                f=open('save.txt', 'w+')
                f.write(str(desired_temp))
                f.close()           
 
            #outdoor
            if (mode == 2):
                print("\nmode = 2 - Outdoor")
                print("Temp: {:>3}F {:>4}".format(indoor_temp, hvac))
                print("Outdoor: {:>3}F".format(outdoor_temp))
                lcd.setText_norefresh("Temp: {:>3}F {:>4}\nOutdoor: {:>3.2f}F".format(indoor_temp, hvac, outdoor_temp))
            
            #edit
            if (mode == 0):
                print("\nmode = 0 - Edit")
                # get rotary angle set desired temp
                desired_temp = get_rotary_angle()
                print("Set Temp: {:>3}F".format(desired_temp)) 
                lcd.setText_norefresh("Set Temp:{:>3}F".format(desired_temp))

        except KeyboardInterrupt:
            lcd.setRGB(0,0,0)
            setText_norefresh("")
            break
예제 #15
0
                if en_debug:
                    print msg[:3], msg[3:6], originalmsg[6:]
                import grove_rgb_lcd
                if msg[3:6].lower() == "col".lower(
                ):  #lower() added just for consistency. Not really needed
                    rgb = []
                    for i in range(0, 6, 2):
                        rgb.append(int(
                            msg[6:][i:i + 2],
                            16))  # convert from one hex string to three ints
                    if en_debug:
                        print "colours are:", rgb[0], rgb[1], rgb[2]
                    grove_rgb_lcd.setRGB(rgb[0], rgb[1], rgb[2])
                elif msg[3:6].lower() == "txt".lower():
                    txt = originalmsg[6:]
                    grove_rgb_lcd.setText_norefresh(txt)
                else:
                    pass
            if en_debug:
                print msg

        # elif msg[:10].lower()=="setOutput".lower():
        #   if en_grovepi:
        #       port=int(msg[10:])
        #       a_read=grovepi.analogRead(port)
        #       s.sensorupdate({'analogRead':a_read})
        #   if en_debug:
        #       print msg
        #       print "Analog Reading: " + str(a_read)
        elif msg.lower() == "READ_IR".lower() or msg.lower() == "IR".lower():
            print "READ_IR!"
예제 #16
0
            #			print("threshold = %d ranger = %d" %(threshold, ranger))

            # compare ranger and threshold
            inbound = "           "

            if ranger <= threshold:
                inbound = "OBJ PRESENT"

            # get the temperature and Humidity from the DHT sensor
            [temp, hum] = grovepi.dht(dht_sensor_port, dht_sensor_type)
            #			print("temp = %d humidity = %d%%" %(temp, hum))

            # check if we have nans
            # if so, then raise a type error exception
            if math.isnan(temp) is True or math.isnan(hum) is True:
                raise TypeError('nan error')

            # write all data to LCD
            grove_rgb_lcd.setText_norefresh(
                "%4d %s\n%4dcm %3d%% %3dC" %
                (threshold, inbound, ranger, hum, temp))

        except TypeError as e:
            print(str(e))
        except KeyboardInterrupt:
            print("KeyboardInterrupt")
            break
        except IOError:
            print("IOError")
예제 #17
0
while True:
    try:

        [temp, humi] = grovepi.dht(dht_port, dht_type)
        print("Temperature is", temp, "C\tHumidity is", humi, "%")

        if isnan(temp) is True or isnan(humi) is True:
            raise TypeError('nan error')

        t = str(temp)
        h = str(humi)

        # 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 program3
        # it's better to leave the LCD with a blank text
        setText("")
        break

    # wait some time before re-updating the LCD
        # Send PWM output to LED via MQTT
        if ranger > 255:
            led_ranger = 255
        else:
            led_ranger = ranger

        publish_data = {"red": led_ranger}
        local_client.publish('SNHU/IT697/leds-Node-RED',
                             json.dumps(publish_data))

        print("Angle: %d, Voltage: %.2f, degrees: %.1f, brightness: %d" %
              (angle_sensor, voltage, degrees, brightness))

        # 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
        grove_rgb_lcd.setText_norefresh("Temp: " + str(temp) + scale + '\n' +
                                        "Humidity: " + str(hum) + '%')

        # Publish to MQTT.
        # local_client.publish('SNHU/IT697/sensor/data', 'Temp: ' + str(temp) + scale + ', Humi: ' + str(hum) + '%')
        # local_client.publish('SNHU/IT697/sensor/data', 'Ranger: ' + str(ranger))
        # local_client.publish('SNHU/IT697/sensor/data', 'Degrees: ' + str(degrees))
        publish_data = {
            "timestamp": int(time.time() * 1000),
            "data": {
                "temperature": tempc,
                "humidity": hum,
                "range": ranger,
                "degrees": degrees
            }
        }
        #local_client.publish('SNHU/IT697/sensor/data/json', json.dumps(publish_data))
예제 #19
0
red = 5
blue = 6
relay = 2

grovepi.pinMode(button, 'INPUT')
grovepi.pinMode(red, 'OUTPUT')
grovepi.pinMode(blue, 'OUTPUT')
grovepi.pinMode(relay, 'OUTPUT')


while True:
    button_press = grovepi.digitalRead(button)


    if button_press == True: 
        grovepi.digitalWrite(red, 1)
        grovepi.digitalWrite(blue, 0)
        lcd.setRGB(200,0,0)
        lcd.setText_norefresh('Hi')
        grovepi.digitalWrite(relay,1)
    else: 
        grovepi.digitalWrite(red, 0)
        grovepi.digitalWrite(blue, 1)
        lcd.setRGB(0,0,200)
        lcd.setText_norefresh('GOObye')
        grovepi.digitalWrite(relay,0)


grovepi.ultrasonicRead()

예제 #20
0
            lcd.setRGB(0, 0, 0)  #turn off LCD
            screenFlag = False  #prevents update once the button is pressed
        if (counter % 2 == 0):
            HVACmode = hvac(init_temp, outTemp, set_temp, HVACmode)
        if (counter == 20):
            outTemp = int(outdoor_temp.get_weather())
            counter = 0
    return 0


if __name__ == '__main__':
    #Grabbing default temperature
    default_temp = 0
    client = window_mqtt.mqtt_init()  #initialize client
    try:
        ifile = open('default.txt', 'r')
        default_temp = int(ifile.read())
    except FileNotFoundError:
        default_temp = 70
    time.sleep(1)
    startup(default_temp)
    server_manager = serverManager.serverManager()
    server.run(debug=False, host='0.0.0.0', port=4250)
    #Send new temperature to the default file
    ofile = open('default.txt', 'w')
    ofile.write(str(set_temp))
    ofile.close()
    lcd.setText_norefresh('')
    lcd.setRGB(0, 0, 0)
    print('')
예제 #21
0
    grovepi.pinMode(button, "INPUT")

    # Initiate in locked mode
    lock_status = 0

    #splashscreen
    with lock:
        grove_rgb_lcd.setRGB(255, 255, 255)
        grove_rgb_lcd.setText("Tim & Andrew\nHomeowner")
        time.sleep(2)
        grove_rgb_lcd.setText("")

    client.publish("timandrew/homeowner_button", "Locked")
    with lock:
        grove_rgb_lcd.setRGB(255, 255, 255)
        grove_rgb_lcd.setText_norefresh("Locking Door... \nStatus: Locked  ")

    while True:
        with lock:
            buttonvalue = grovepi.digitalRead(button)  #check button reading
        if buttonvalue:
            if lock_status:
                lock_status = 0
                client.publish("timandrew/homeowner_button", "Locked")
                with lock:
                    grove_rgb_lcd.setRGB(255, 255, 255)
                    grove_rgb_lcd.setText_norefresh(
                        "Locking Door... \nStatus: Locked  ")
                with lock:
                    grovepi.digitalWrite(buzzer, 1)
                    time.sleep(0.1)
예제 #22
0
    try:
        # Check for input
        if grovepi.digitalRead(PORT_BUTTON):
            # BEEP!
            grovepi.digitalWrite(PORT_BUZZER, 1)

            # Switch app
            app = (app + 1) % len(APPS)
            ind = 0

        time.sleep(0.1)

        grovepi.digitalWrite(PORT_BUZZER, 0)

        # Display app name
        lcd.setText_norefresh(APPS[app]['name'])

        # Scroll output
        lcd.setText_norefresh('\n' + CACHE[app][ind:ind + LCD_LINE_LEN])
        # TODO: Make the output scroll across the screen (should take 1-2 lines of code)

    except KeyboardInterrupt:
        # Gracefully shutdown on Ctrl-C
        lcd.setText('')
        lcd.setRGB(0, 0, 0)

        # Turn buzzer off just in case
        grovepi.digitalWrite(PORT_BUZZER, 0)

        break
예제 #23
0
def on_message_lcd(client, userdata, msg):
    message = str(msg.payload, "utf-8")
    if not message:
        return
    else:
        grove_rgb_lcd.setText_norefresh(message)
예제 #24
0
            if en_grovepi:
                if en_debug:
                    print msg[:3], msg[3:6], originalmsg[6:]

                sys.path.insert(0, '/home/pi/Dexter/GrovePi/Software/Python/grove_rgb_lcd')
                import grove_rgb_lcd 
                if msg[3:6].lower() == "col".lower(): #lower() added just for consistency. Not really needed
                    rgb = []
                    for i in range(0,6,2): 
                        rgb.append(int(msg[6:][i:i+2],16))  # convert from one hex string to three ints
                    if en_debug:
                        print "colours are:",rgb[0],rgb[1],rgb[2]
                    grove_rgb_lcd.setRGB(rgb[0],rgb[1],rgb[2])
                elif msg[3:6].lower() == "txt".lower():
                    txt = originalmsg[6:]
                    grove_rgb_lcd.setText_norefresh(txt)
                else:
                    pass
            if en_debug:
                print msg
            
        # elif msg[:10].lower()=="setOutput".lower():
        #   if en_grovepi:
        #       port=int(msg[10:])
        #       a_read=grovepi.analogRead(port)
        #       s.sensorupdate({'analogRead':a_read})
        #   if en_debug:
        #       print msg
        #       print "Analog Reading: " + str(a_read)   
        elif msg.lower()=="READ_IR".lower() or msg.lower()=="IR".lower():
            print "READ_IR!" 
예제 #25
0
        #read ultrasonic ranger, convert int to string, display on LCD
        dist_int = ultrasonicRead(ultrasonic_ranger)
        dist_string = str(dist_int)

        #read humidity
        [temp,humidity] = dht(dht_pin,0) # instantiate a dht class with the appropriate pin
        # TODO: if isnano is true, just ignore don't print
        if isnan(temp) is False and isnan(humidity) is False:
            temp_int = int(temp)
            humidity_int = int(humidity)
            temp_string = str(temp_int)
            humidity_string = str(humidity_int)

        #display

        #format strings
        if len(dist_thresh_string) == 1:
            dist_thresh_string += "  "
        elif len(dist_thresh_string) == 2:
            dist_thresh_string += " "

        #compare ultrasonic ranger with threshold
        if isnan(temp) is False and isnan(humidity) is False:
            if dist_int < dist_thresh_int :
                grove_rgb_lcd.setText_norefresh(dist_thresh_string+" OBJ PRESENT"+"\n"+dist_string+"cm "+ humidity_string +"% " + temp_string + "C")
            else :   
                grove_rgb_lcd.setText_norefresh(dist_thresh_string+"            \n"+dist_string+"cm "+ humidity_string +"% " + temp_string + "C")



예제 #26
0
def ReadDHTandText(dhtport=7):
    [t, h] = grovepi.dht(dhtport, 0)
    msg = f'temp: {t}C\nhumidity: {h}%'
    print(msg)
    lcd.setText_norefresh(msg)
예제 #27
0
def lcd_callback(client, userdata, message):
    #or should we send all keys from VM, and filter out non a,s,d,w keys in this function?
    #print(str(message.payload, "utf-8")) # TODO: print str or char?
    grove_rgb_lcd.setText_norefresh(str(message.payload, "utf-8"))
예제 #28
0
is, if you run `python3 grovepi_sensors.py` in terminal, this if-statement will 
be true"""
t = grove_i2c_temp_hum_mini.th02()
t.getTemperature = protect(t.getTemperature)
t.getHumidity = protect(t.getHumidity)

if __name__ == '__main__':
    PORT = 4  # D4
    PORTR = 0
    PORTW = 1
    ldis = -1
    lsen = -1
    while True:
        #So we do not poll the sensors too quickly which may introduce noise,
        #sleep for a reasonable time of 200ms between each iteration.
        time.sleep(0.8)
        #try:
        temp = t.getTemperature()
        humid = t.getHumidity()
        #except TypeError:
        #        print ("Error")
        time.sleep(0.1)
        grove_rgb_lcd.setText(" " + str(temp) + "cm \n " + str(humid) + "cm")
        grove_rgb_lcd.setRGB(0, 255, 0)
        buf = list("Grove -Update without erase")
        grove_rgb_lcd.setText("".join(buf))
        for i in range(len(buf)):
            buf[i] = "."
            grove_rgb_lcd.setText_norefresh("".join(buf))
            time.sleep(.1)
    lcd.setRGB(0, 128, 0)

    # Load messages
    ciphertexts = ['khoor']  # test message: 'hello' encrypted with key 3
    # TODO: Load the contents of intercepted.txt into the ciphertexts list
    # ciphertexts = []

    index = 0

    while True:
        try:
            key = get_key_from_angle(get_rotary_angle())
            plaintext = caesar_decrypt(ciphertexts[index], key)

            # Update screen
            lcd.setText_norefresh('{:16}\nKey: {:02d}'.format(plaintext, key))

            # Check for input
            if grovepi.digitalRead(PORT_BUTTON):
                index += 1
                if index >= len(ciphertexts):
                    # Finished
                    break

            time.sleep(0.2)

        except KeyboardInterrupt:
            # Gracefully shutdown on Ctrl-C
            shutdown()
            break
예제 #30
0
        global RightFlag
        global WrongFlag
        global WinFlag
        global LoseFlag
        global EndFlag
        RightFlag = False
        WrongFlag = False
        WinFlag = False
        LoseFlag = False
        EndFlag = False

        lcd.setRGB(0, 16, 16)
        grovepi.digitalWrite(PORT_BUZZER, 0)

        letter = chr(0)
        while not EndFlag:
            letterValue = int(grovepi.analogRead(PORT_ROTARY) / 39.385)
            nextLetter = chr(97 + letterValue)
            if nextLetter != letter:
                letter = nextLetter
                lcd.setText_norefresh("Your guess: " + letter)
            if grovepi.digitalRead(PORT_BUTTON):
                client.publish("fyzhang/guess", str(letter))
                while grovepi.digitalRead(PORT_BUTTON):
                    checkFlags()
                    time.sleep(0.1)
            checkFlags()
    except KeyboardInterrupt:
        lcd.setText('')
        lcd.setRGB(0, 0, 0)
        grovepi.digitalWrite(PORT_BUZZER, 0)
예제 #31
0
import time
# By appending the folder of all the GrovePi libraries to the system path here,
# we are successfully `import grovepi`
sys.path.append('../../Software/Python/')
# This append is to support importing the LCD library.
sys.path.append('../../Software/Python/grove_rgb_lcd')

import grovepi
import grove_rgb_lcd

if __name__ == '__main__':
    pot_port = 0  # A0
    ultrasonic_port = 4  # D4

    grove_rgb_lcd.setRGB(255, 255, 255)

    while True:
        #So we do not poll the sensors too quickly which may introduce noise,
        #sleep for a reasonable time of 200ms between each iteration.
        time.sleep(0.2)

        threshold = grovepi.analogRead(pot_port)
        distance = grovepi.ultrasonicRead(ultrasonic_port)

        if distance < threshold:
            grove_rgb_lcd.setText_norefresh('%4dcm OBJ PRES\n%4dcm' %
                                            (threshold, distance))
        else:
            grove_rgb_lcd.setText_norefresh('%4dcm         \n%4dcm' %
                                            (threshold, distance))