def on_message(id, value): if id.endswith(actuatorId1) == True: value = value.lower() #make certain that the value is in lower case, for 'True' vs 'true' if value == "true": grovepi.digitalWrite(actuatorPin1, 1) IOT.send("true", actuatorId1) #provide feedback to the cloud that the operation was succesful elif value == "false": grovepi.digitalWrite(actuatorPin1, 0) IOT.send("false", actuatorId1) #provide feedback to the cloud that the operation was succesful else: print("unknown value: " + value) elif id.endswith(actuatorId2) == True: value = value.lower() #make certain that the value is in lower case, for 'True' vs 'true' if value == "true": grovepi.digitalWrite(actuatorPin2, 1) IOT.send("true", actuatorId2) #provide feedback to the cloud that the operation was succesful elif value == "false": grovepi.digitalWrite(actuatorPin2, 0) IOT.send("false", actuatorId2) #provide feedback to the cloud that the operation was succesful else: print("unknown value: " + value) elif id.endswith(actuatorId3) == True: grovepi.analogWrite(actuatorPin3, int(value/100)) IOT.send(int(value), actuatorId3) #provide feedback to the cloud that the operation was succesful else: print("unknown actuator: " + id)
def function_Estop(self): try: print("EStop - Activated") #remember not to disable sensor reading aircon_output.aircon_enabled = 0 coldblock_output.coldblock_enabled = 0 hotend_output.hotend_enabled = 0 stepper_output.motor_enabled = 0 camera_linedetection.camera_enabled = 0 herkulex.servo_enabled = 0 grovepi.analogWrite(self.peltierfanpin1, 0) grovepi.analogWrite(self.peltierfanpin2, 0) #grovepi.ledCircle_off(self.ledcirclepin) time.sleep(0.1) self.peltier1.start(0) self.peltier2.start(0) self.heater.start(0) GPIO.output(self.motor_enable_pin, 1) #set H to disable GPIO.output(self.motor_dir_pin, 0) #set H to disable GPIO.output(self.motor_step_pin, 0) #set H to disable print("Successful = Power down system") buzzer.beep(self.buzzerpin, 2) except Exception, e: print("--- Failed = Pls manual power down ---\n") print("--- Failed = Pls manual power down ---\n") print("--- Failed = Pls manual power down ---\n") buzzer.beep_fail(self.buzzerpin) print(str(e))
def function_Estop(self): try: print("EStop - Activated") #remember not to disable sensor reading aircon_output.aircon_enabled = 0 coldblock_output.coldblock_enabled = 0 hotend_output.hotend_enabled = 0 stepper_output.motor_enabled = 0 camera_linedetection.camera_enabled = 0 herkulex.servo_enabled = 0 grovepi.analogWrite(self.peltierfanpin1,0) grovepi.analogWrite(self.peltierfanpin2,0) #grovepi.ledCircle_off(self.ledcirclepin) time.sleep(0.1) self.peltier1.start(0) self.peltier2.start(0) self.heater.start(0) GPIO.output(self.motor_enable_pin,1) #set H to disable GPIO.output(self.motor_dir_pin,0) #set H to disable GPIO.output(self.motor_step_pin,0) #set H to disable print("Successful = Power down system") buzzer.beep(self.buzzerpin,2) except Exception, e: print("--- Failed = Pls manual power down ---\n") print("--- Failed = Pls manual power down ---\n") print("--- Failed = Pls manual power down ---\n") buzzer.beep_fail(self.buzzerpin) print(str(e))
def adjustBrightness(portNumber, brightness): led = portNumber if (led not in [3, 5, 6, 9]): print("try_next_led") else: if (grovepi.pinMode(led, "OUTPUT") != 1): print("Error") else: try: if (brightness == 0): grovepi.digitalWrite(led, 0) print("LED turned off") else: if (brightness > 1023): brightness = 1023 #analogWrite takes args btw 0-255 which is why we divide by 4 grovepi.analogWrite(led, brightness // 4) print("Brightness Adjusted") except (IOError): print("Error") except (KeyboardInterrupt): grovepi.digitalWrite(led, 0) print("Interrupted")
def exitProgram(): print("Exiting...type1\n\n\n") herkulex.alive = 0 camera_linedetection.alive = 0 stepper_output.alive = 0 coldblock_output.alive = 0 hotend_output.alive = 0 aircon_output.alive = 0 sensors.alive = 0 herkulex.clear_errors() servo1.torque_off() servo2.torque_off() servo3.torque_off() sensors.ambience_sensor_enabled = 0 sensors.adc1_sensor_enabled = 0 sensors.adc2_sensor_enabled = 0 sensors.adc3_sensor_enabled = 0 aircon_output.aircon_enabled = 0 coldblock_output.coldblock_enabled = 0 hotend_output.hotend_enabled = 0 stepper_output.motor_enabled = 0 herkulex.servo_enabled = 0 time.sleep(1.0) grovepi.analogWrite(peltierfanpin1,0) grovepi.analogWrite(peltierfanpin2,0) grovepi.ledCircle_off(ledcirclepin) time.sleep(0.2) peltier1.start(0) peltier2.start(0) heater.start(0) GPIO.output(motor_enable_pin,1) #set H to disable GPIO.output(motor_dir_pin,0) #set H to disable GPIO.output(motor_step_pin,0) #set H to disable herkulex.close()
def demoKnob(self): while True: try: # Read sensor value from potentiometer sensor_value = grovepi.analogRead(potentiometer) # Calculate voltage voltage = round((float)(sensor_value) * adc_ref / 1023, 2) # Calculate rotation in degrees (0 to 300) degrees = round((voltage * full_angle) / grove_vcc, 2) # Calculate LED brightess (0 to 255) from degrees (0 to 300) brightness = int(degrees / full_angle * 255) # Give PWM output to LED grovepi.analogWrite(gled, brightness) print( "sensor_value = %d voltage = %.2f degrees = %.1f brightness = %d" % (sensor_value, voltage, degrees, brightness)) except KeyboardInterrupt: grovepi.analogWrite(gled, 0) break except IOError: print("Error")
def automaticLightSensor(sensorPortNumber, ledPortNumber): # Connect the Grove Light Sensor to analog port A0 # SIG,NC,VCC,GND light_sensor = sensorPortNumber # Connect the LED to digital port D4 # SIG,NC,VCC,GND led = ledPortNumber grovepi.pinMode(light_sensor,"INPUT") grovepi.pinMode(led,"OUTPUT") i =1; try: # Get sensor value (wiill return btw 0-1023 sensor_value = grovepi.analogRead(light_sensor) if(sensor_value <= 0): sensor_value = 1 brightness = 1023-sensor_value #analogWrite takes args btw 0-255 which is why we divide by 4 grovepi.analogWrite(led, brightness//4) print("sensor_value = %d brightness =%d " %(sensor_value, brightness)) time.sleep(.2) except (IOError): print ("Error") except (KeyboardInterrupt): print("Interrupted")
def listenerLED(publisherLED): print("LED Thread Ready" ) # Printing this to show that the program has been started for dweet in dweepy.listen_for_dweets_from( 'mypicontrolboardLED' ): # Looping through mypicontrolboardLED Dweet Thing content = dweet[ "content"] # Assigning value from content on Dweet to variable content ledStatus = content[ "LEDStatus"] # Assigning value from LEDStatus on Dweet to variable ledStatus LEDbrightness = content[ "LightLevel"] # Assigning value from LightLevel on Dweet to variable LEDBrightness print ledStatus if ledStatus == "true": # If value is true then we run the code block below # start the publisher thread global publisher_state_for_led publisher_state_for_led = True global lightBrightness # Creating a variable lightBrightness that will store the value of LEDbrightness lightBrightness = LEDbrightness if not publisherLED.is_alive(): publisherLED = Thread(target=led_publisher_method) publisherLED.start() else: publisher_state_for_led = False print "wasn't true" grovepi.analogWrite( led, 0 / 4 ) # if the script crashes we can just press the off button and the sensors will turn off.
def slideDrone(self,gauchedroite, force): ## en fonction de gauche/droite ou bas/haut (premier 0 second 1) if gauchedroite: ## on envoie au drone une diminution ou augmentation de la valeur du millieu en fonction du sens, changement que l'on definit comme suit : valeurmin ou max * (force_demandée_entre_1_et_20) / 20) on utilise truediv car sans cela python ne prend pas en charge les virgules pour des int -> 0.5 = 0 grovepi.analogWrite(self.slide,int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20))))) else: ## on envoie au drone une diminution ou augmentation de la valeur du millieu en fonction du sens, changement que l'on definit comme suit : valeurmin ou max * (force_demandée_entre_1_et_20) / 20) on utilise truediv car sans cela python ne prend pas en charge les virgules pour des int -> 0.5 = 0 grovepi.analogWrite(self.slide,int(self.valeurmillieu-(self.diminutionmax*(truediv(force,20))))) grovepi.analogWrite(self.slide,int(self.valeurmillieu+(self.augmentationmax*(truediv(force,20)))))
def listen(publisher_thread ): # The listen() method takes the publisher thread as a parameter print(listener_thread_name + " is Listening!") # Print Starting Listening! global publisher_state # Set publisher state as a global variable publisher_state = True # Set publisher state to true global button_clicked if not publisher_thread.is_alive( ): # If publisher thread is not running execute the following code publisher_thread.start() # Start publisher thread for dweet in dweepy.listen_for_dweets_from( thingTwoName ): # For loop listens for dweets from a specific thing called GrahamThingTwo content = dweet[ "content"] # Store the content from each dweet into a variable called content print(str(content)) # Print content try: button_clicked = content["ButtonClicked"] except: print("Button not clicked yet!") thing = dweet[ "thing"] # Store the thing from each dweet into a variable called thing print("Reading from " + str(thing) + ": " + str(content)) print("") # Adds an empty line in the terminal below our output above try: if int(button_clicked ) == 1: # Check if the button has been pressed brightness = 255 # Set maximum brightness grovepi.analogWrite(led, brightness) # Give PWM output to LED else: brightness = 0 # Set minimum brightness grovepi.analogWrite(led, brightness) # Give PWM output to LED except: print("Button still not clicked yet!") print("Listening Ending!") # Print Listening Ending!
def fan_turn_off(): fan_port = 5 grovepi.pinMode(fan_port, "OUTPUT") speed = 0 grovepi.analogWrite(fan_port, speed) hub.PERSISTENCE['SPEED'] = speed return jsonify({'status': 'OFF'})
def FadeLed(pin=5): # set pin mode to output grovepi.pinMode(pin, 'OUTPUT') pinOutRange = range(0, 100, 15) for o in pinOutRange: print(o) grovepi.analogWrite(pin, o) time.sleep(1)
def getLed(): # Read resistance from Potentiometer i = grovepi.analogRead(potentiometer) # Send PWM signal to LED grovepi.analogWrite(led, i // 4) return i
def emergency(): grovepi.digitalWrite(door_relay_port, 1) # open doors grovepi.digitalWrite(door_relay_indicator, 1) grovepi.digitalWrite(led_port, 0) # turn on lights grovepi.digitalWrite( ac_relay_port, 0) # turn off ac, as not to potentially take power away from alarm grovepi.digitalWrite(ac_relay_indicator, 0) grovepi.analogWrite(emergency_buzzer_port, 255)
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 decrease_fan_speed(body): decrement = body['decrement'] fan_port = 5 speed = hub.PERSISTENCE['SPEED'] speed -= int(decrement) if(speed < 0 or speed > 250): return jsonify({ "error": "speed " + str(speed) + " out of range (" + str(0) + "-" + str(250) + ")", 'speed': hub.PERSISTENCE['SPEED'] }), 400 grovepi.analogWrite(fan_port,speed) hub.PERSISTENCE['SPEED'] = speed return jsonify({'speed': speed})
def on(portNumber): minifan = portNumber grovepi.pinMode(minifan, "OUTPUT") try: grovepi.analogWrite(minifan, 255) except (IOError, TypeError): print("Error")
def adjustSpeed(portNumber, speed): minifan = portNumber grovepi.pinMode(minifan, "OUTPUT") try: grovepi.analogWrite(minifan, speed) except (IOError, TypeError): print("Error")
def led_publisher_method(): while publisher_state_for_led: grovepi.analogWrite( led, int(lightBrightness) / 4 ) # Turning on the LED light and also giving it a brightness level that can be set by the user, the default button will turn the led to 1000/4 value time.sleep(1) print "Turning LED light off" grovepi.analogWrite( led, 0 / 4 ) # Turning off the led light after publister_state_for_led returns false
def __init__(self, connector, logger, nuances_resolution): super(LedResource, self).__init__(connector, logger, nuances_resolution) #set Contenttype to text/plain self.ct = 0 self.value = 0 self.button_pressed = False try: grovepi.analogWrite(self.connector, int(self.value)) except IOError: self.logger.debug("Error of initial digitalWrite call.")
def increase_fan_speed(body): increment = body fan_port = 5 # speed = hub.PERSISTENCE['SPEED'] #globalspeed += int(increment) speed = 100 speed += body if(speed < 0 or speed > 250): return { "error": "speed " + str(speed) + " out of range (" + str(0) + "-" + str(250) + ")", 'speed': speed}, 400 grovepi.pinMode(fan_port,"OUTPUT") grovepi.analogWrite(fan_port,speed) # hub.PERSISTENCE['SPEED'] = speed return {'speed': speed}
def run(peltierpin1, peltier1, peltierfanpin1): global aircon_enabled, aircon_setpoint aircon_pwm = 0 peltier1.start(0) airconPID = PIDclass(18, 6, 5) #init P I D value airconPID.setSampleTime(0) print("Aircon PID ... Started") next_call = time.time() while (alive): airconPID.SetPoint = aircon_setpoint #target temperature in degree airconPID.update(sensors.adc1_temp_cur) #peltier blue #print datetime.datetime.now() buf = airconPID.output * -1.0 #print(buf) if (buf > 100): aircon_pwm = 100 elif (buf <= 0): aircon_pwm = 0 else: aircon_pwm = buf if (sensors.adc1_temp_cur <= -900): print("Error: Run away thermistor - Aircon") aircon_enabled = 0 airconPID.clear() peltier1.start(0) else: if (aircon_enabled): peltier1.start(aircon_pwm) print( "Aircon Temp = Tgt:%.1fC Cur:%.1fC PeltierOutput = %.1f" % (aircon_setpoint, sensors.adc1_temp_cur, aircon_pwm) + "%" + " Enable = %d" % (aircon_enabled)) if (sensors.adc1_temp_cur <= 25.5 or aircon_pwm >= 75.0): #dew point grovepi.analogWrite(peltierfanpin1, 255) #full elif (aircon_pwm >= 50.0): grovepi.analogWrite(peltierfanpin1, 200) #full-half elif (aircon_pwm >= 10.0): grovepi.analogWrite(peltierfanpin1, 125) #half else: peltier1.start(0) if (sensors.adc1_temp_cur <= 20.0): #dew point print("Aircon Self Protection : Fan On") grovepi.analogWrite(peltierfanpin1, 255) #on else: grovepi.analogWrite(peltierfanpin1, 0) #off next_call = next_call + 1 time.sleep(next_call - time.time()) peltier1.start(0)
def clients(): while True: time.sleep(0.2) if 'sensors.mode' in actuator_commands and actuator_commands[ 'sensors.mode'] == 'emergency': # check if emergency was set elsewhere (web interface) emergency() continue emergency_trigger = grovepi.analogRead( emergency_button_port ) # enable emergency (simulate smoke detector) if emergency_trigger > 50: rmq1.send( "sensors.mode", "emergency" ) # see emergency from web ui (only it can turn off emergency) emergency() continue grovepi.analogWrite(emergency_buzzer_port, 0) # turn off buzzer if not emergency mode lightlevel = grovepi.analogRead(light_port) print("sent lightlevel: " + str(lightlevel)) rmq1.send("sensors.lightlevel", str(lightlevel)) [temp, hum] = grovepi.dht(temp_port, 0) print("sent temperature: " + str(temp)) rmq1.send("sensors.temperature", str(temp)) distance = grovepi.ultrasonicRead( ultrasonic_port) # for presence in room print("sent ultrasonic: " + str(distance)) rmq1.send("sensors.ultrasonic", str(distance)) if 'actuators.ac' in actuator_commands: ac_cmd = int(actuator_commands['actuators.ac']) print("received ac: " + str(ac_cmd)) grovepi.digitalWrite(ac_relay_port, ac_cmd) grovepi.digitalWrite(ac_relay_indicator, ac_cmd) if 'actuators.door' in actuator_commands: door_cmd = int(actuator_commands['actuators.door']) print("received door: " + str(door_cmd)) grovepi.digitalWrite(door_relay_port, door_cmd) grovepi.digitalWrite(door_relay_indicator, door_cmd) if 'actuators.led' in actuator_commands: led_cmd = int(actuator_commands['actuators.led']) print("received led: " + str(led_cmd)) grovepi.digitalWrite(led_port, led_cmd)
def signal_outputs(level, avg_wind): if int(level) > 1023: level = 1023 grovepi.analogWrite(led, int(level) // 4) cw = str(current_wind) aw = str(int(avg_wind)) n = str(current_noise) # Control the Grove LCD setRGB(0, 128, 64) if current_wind >= 75: setText("Operation Halt:\n" + "Windspeed= " + cw + "mph") else: setText("avgwind=" + aw + "mph\n" + "noise=" + n + "units")
def set_actuator(self, value): try: if self.button_pressed: grovepi.analogWrite(self.connector, self.value) else: # The button is not pressed but we've received a new value through # the RotaryResource. # Simply disable the LED in this case. grovepi.analogWrite(self.connector, 0) self.updated_state() self.logger.debug("****** DP **** set_actuator with value: [" + str(self.value) + "]") except IOError: self.logger.debug("Error in writing to sensor at pin " + str(self.connector))
def fan_set(target_speed): #target_speed = body['target_speed'] speed = int(target_speed) if (speed < 0 or speed > 250): return jsonify({ "error": "speed " + str(speed) + " out of range (" + str(0) + "-" + str(250) + ")", 'speed': hub.PERSISTENCE['SPEED'] }), 400 fan_port = 5 grovepi.pinMode(fan_port, "OUTPUT") grovepi.analogWrite(fan_port, speed) hub.PERSISTENCE['SPEED'] = speed return jsonify({'speed': speed})
def run(peltierpin1, peltier1, peltierfanpin1): global aircon_enabled, aircon_setpoint aircon_pwm = 0 peltier1.start(0) airconPID = PIDclass(18,6,5) #init P I D value airconPID.setSampleTime(0) print("Aircon PID ... Started") next_call = time.time() while(alive): airconPID.SetPoint = aircon_setpoint #target temperature in degree airconPID.update(sensors.adc1_temp_cur) #peltier blue #print datetime.datetime.now() buf = airconPID.output * -1.0 #print(buf) if(buf > 100): aircon_pwm = 100 elif(buf <= 0): aircon_pwm = 0 else: aircon_pwm = buf if(sensors.adc1_temp_cur <= -900): print("Error: Run away thermistor - Aircon") aircon_enabled = 0 airconPID.clear() peltier1.start(0) else: if(aircon_enabled): peltier1.start(aircon_pwm) print("Aircon Temp = Tgt:%.1fC Cur:%.1fC PeltierOutput = %.1f" %(aircon_setpoint,sensors.adc1_temp_cur,aircon_pwm) + "%" + " Enable = %d" %(aircon_enabled)) if(sensors.adc1_temp_cur <= 25.5 or aircon_pwm >= 75.0): #dew point grovepi.analogWrite(peltierfanpin1,255) #full elif(aircon_pwm >= 50.0): grovepi.analogWrite(peltierfanpin1,200) #full-half elif(aircon_pwm >= 10.0): grovepi.analogWrite(peltierfanpin1,125) #half else: peltier1.start(0) if(sensors.adc1_temp_cur <= 20.0): #dew point print("Aircon Self Protection : Fan On") grovepi.analogWrite(peltierfanpin1,255) #on else: grovepi.analogWrite(peltierfanpin1,0) #off next_call = next_call + 1 time.sleep(next_call - time.time()) peltier1.start(0)
def analog_write(pin_obj, val): if device_type == DEVICE_TYPE_MRAA: raise NotImplementedError elif device_type == DEVICE_TYPE_RPI: raise NotImplementedError elif device_type == DEVICE_TYPE_GPI: return grovepi.analogWrite(pin_obj, val)
def listen(publisher_thread): # The listen() method takes the publisher thread as a parameter print(listener_thread_name + " is Listening!") # Print Starting Listening! global publisher_state # Set publisher state as a global variable publisher_state = True # Set publisher state to true if not publisher_thread.is_alive(): # If publisher thread is not running execute the following code publisher_thread.start() # Start publisher thread for dweet in dweepy.listen_for_dweets_from(thingOneName): # For loop listens for dweets from a specific thing called GrahamThingOne content = dweet["content"] # Store the content from each dweet into a variable called content sensor_value = content["Potentiometer"] # Get the value from the potentiometer thing = dweet["thing"] # Store the thing from each dweet into a variable called thing print("Reading from " + str(thing) + ": " + str(content)) print("") # Adds an empty line in the terminal below our output above voltage = round((float)(sensor_value) * adc_ref / 1023, 2) # Calculate voltage degrees = round((voltage * full_angle) / grove_vcc, 2) # Calculate rotation in degrees (0 to 300) brightness = int(degrees / full_angle * 255) # Calculate LED brightess (0 to 255) from degrees (0 to 300) grovepi.analogWrite(led,brightness) # Give PWM output to LED print("Listening Ending!") # Print Listening Ending!
def increase_fan_speed(increment): #increment = body['increment'] fan_port = 5 speed = hub.PERSISTENCE['SPEED'] speed += int(increment) if (speed < 0 or speed > 250): return jsonify({ "error": "speed " + str(speed) + " out of range (" + str(0) + "-" + str(250) + ")", 'speed': hub.PERSISTENCE['SPEED'] }), 400 grovepi.pinMode(fan_port, "OUTPUT") print(speed) grovepi.analogWrite(fan_port, speed) hub.PERSISTENCE['SPEED'] = speed return jsonify({'speed': speed})
def sound_alarm(): type = "" exit_flag = False now = datetime.datetime.now() alm_min = now.minute now_min = now.minute val = 10 lcd.rgb(255, 0, 0) lcd.text(" Alarm!!!") while alm_min == now_min: now = datetime.datetime.now() now_min = now.minute grovepi.analogWrite(buzzer, val) if grovepi.digitalRead(button) == True: break else: if val == 10: val = 70 else: val = 10 sleep(1) grovepi.analogWrite(buzzer, 0) #Wait for button to be releasd while True: try: if grovepi.digitalRead(button) == False: break except IOError: pass lcd.text("") lcd.rgb(50,50,50) alm["quiet"] = "X"
def function_Exit(self): print("Exiting...type2\n\n\n") buzzer.beep_click(self.buzzerpin) self.function_Estop() grovepi.analogWrite(self.peltierfanpin1,0) #aircon, 0-255 grovepi.analogWrite(self.peltierfanpin2,0) #coldblock, 0-255 grovepi.ledCircle_off(self.ledcirclepin) herkulex.alive = 0 camera_linedetection.alive = 0 stepper_output.alive = 0 coldblock_output.alive = 0 hotend_output.alive = 0 aircon_output.alive = 0 sensors.alive = 0 time.sleep(1.0) sensors.ambience_sensor_enabled = 0 sensors.adc1_sensor_enabled = 0 sensors.adc2_sensor_enabled = 0 sensors.adc3_sensor_enabled = 0 time.sleep(1.0) sys.exit()
def manual(): #This is a program that allows you to control the blinds with a knob. global potentiometer_pin, button_pin, led1_pin, led2_pin adc_ref = 5 #Reference voltage of ADC is 5v grove_vcc = 5 #Vcc of the grove interface is normally 5v full_angle = 300 #Full value of the rotary angle is 300 degrees, as per it's specs (0 to 300) sensor_value = grovepi.analogRead(potentiometer_pin) #Read sensor value from potentiometer voltage = round((float)(sensor_value) * adc_ref / 1023, 2) #Calculate voltage degrees = round((voltage * full_angle) / grove_vcc, 2) #Calculate rotation in degrees (0 to 300) #This will be replaced with a distance measurment brightness = int(degrees / full_angle * 255) #Calculate LED brightess (0 to 255) from degrees (0 to 300) button_test = grovepi.digitalRead(button_pin) #Is the button on or off? On will control the blinds, off will control the shutters if (button_test==1): #Give PWM output to LED grovepi.analogWrite(led1_pin,brightness) #Move blinds else: grovepi.analogWrite(led2_pin,brightness) #Move shutters print("sensor_value =", sensor_value, " voltage =", voltage, " degrees =", degrees, " brightness =", brightness)
def function_Exit(self): print("Exiting...type2\n\n\n") buzzer.beep_click(self.buzzerpin) self.function_Estop() grovepi.analogWrite(self.peltierfanpin1, 0) #aircon, 0-255 grovepi.analogWrite(self.peltierfanpin2, 0) #coldblock, 0-255 grovepi.ledCircle_off(self.ledcirclepin) herkulex.alive = 0 camera_linedetection.alive = 0 stepper_output.alive = 0 coldblock_output.alive = 0 hotend_output.alive = 0 aircon_output.alive = 0 sensors.alive = 0 time.sleep(1.0) sensors.ambience_sensor_enabled = 0 sensors.adc1_sensor_enabled = 0 sensors.adc2_sensor_enabled = 0 sensors.adc3_sensor_enabled = 0 time.sleep(1.0) sys.exit()
def on_message(client, userdata, msg): """ Called for each message received :param client :param userdata: :param msg: :return: none """ print("Received message from MQTT Broker.....") print(msg.topic, msg.payload) _topic = msg.topic led_payload = jsonpickle.decode(msg.payload) if _topic == 'SNHU/IT697/leds/red': print("Processing " + _topic + " with msg " + msg.payload) # write discrete for RED LED grovepi.analogWrite(RED_LED, led_payload['red']) elif _topic == 'SNHU/IT697/leds/green': print("Processing " + _topic + " with msg " + msg.payload) # write discrete for GREEN LED grovepi.analogWrite(GREEN_LED, led_payload['green']) elif _topic == 'SNHU/IT697/leds/blue': print("Processing " + _topic + " with msg " + msg.payload) # write discrete for BLUE LED grovepi.analogWrite(BLUE_LED, led_payload['blue']) else: print("No Registered Topic......")
def Fade(): # Connect the Rotary Angle Sensor to analog port A2 potentiometer = 2 # Connect the LED to digital port D5 led = 5 grovepi.pinMode(led,"OUTPUT") time.sleep(1) i = 0 while True: try: # Read resistance from Potentiometer i = grovepi.analogRead(potentiometer) print(i) # Send PWM signal to LED grovepi.analogWrite(led,i//4) except IOError: print("Error")
def formMenu(self, items): itemRange = int(1000/len(items)) while True: try: # Read sensor value from potentiometer sensor_value = grovepi.analogRead(potentiometer) selection = int(sensor_value/itemRange) # check to make sure that our index value isn't going over if selection >= len(items): selection = len(items) - 1 setText(list(items[selection])) self.colorSelect(selection) if grovepi.digitalRead(button) == 1: self.clear() return selection time.sleep(0.5) except KeyboardInterrupt: grovepi.analogWrite(gled,0) break except IOError: print ("Error")
def demoKnob(self): while True: try: # Read sensor value from potentiometer sensor_value = grovepi.analogRead(potentiometer) # Calculate voltage voltage = round((float)(sensor_value) * adc_ref / 1023, 2) # Calculate rotation in degrees (0 to 300) degrees = round((voltage * full_angle) / grove_vcc, 2) # Calculate LED brightess (0 to 255) from degrees (0 to 300) brightness = int(degrees / full_angle * 255) # Give PWM output to LED grovepi.analogWrite(gled,brightness) print("sensor_value = %d voltage = %.2f degrees = %.1f brightness = %d" %(sensor_value, voltage, degrees, brightness)) except KeyboardInterrupt: grovepi.analogWrite(gled,0) break except IOError: print ("Error")
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)
def run(peltierpin2, peltier2, peltierfanpin2): global coldblock_enabled, coldblock_setpoint coldblock_pwm = 0 peltier2.start(0) coldblockPID = PIDclass(15,5,10) #init P I D value coldblockPID.setSampleTime(0) print("Coldblock PID ... Started") next_call = time.time() while(alive): coldblockPID.SetPoint = coldblock_setpoint #target temperature in degree coldblockPID.update(sensors.adc2_temp_cur) #peltier blue #print datetime.datetime.now() buf = coldblockPID.output * -1.0 #print(buf) if(buf > 100): coldblock_pwm = 100 elif(buf <= 0): coldblock_pwm = 0 else: coldblock_pwm = buf if(sensors.adc2_temp_cur <= -900): print("Error: Run away thermistor - ColdBlock") coldblock_enabled = 0 coldblockPID.clear() peltier2.start(0) else: if(coldblock_enabled): peltier2.start(coldblock_pwm) grovepi.analogWrite(peltierfanpin2,250) #full print("ColdblockTemp = Tgt:%.1fC Cur:%.1fC PeltierOutput = %.1f" %(coldblock_setpoint,sensors.adc2_temp_cur,coldblock_pwm) + "%" + " Enable = %d" %(coldblock_enabled)) else: peltier2.start(0) if(sensors.adc2_temp_cur <= 20.0): #dew point print("Coldblock Self Protection : Fan On") grovepi.analogWrite(peltierfanpin2,255) #on else: grovepi.analogWrite(peltierfanpin2,0) #off next_call = next_call + 1 time.sleep(next_call - time.time()) peltier2.start(0)
elif msg[:15].lower()=="digitalWriteLow".lower(): if en_grovepi: port=int(msg[15:]) grovepi.digitalWrite(port,0) if en_debug: print msg elif match_sensors(msg,pwm) >=0: if en_grovepi: s_no=match_sensors(msg,pwm) sens=pwm[s_no] l=len(sens) port=int(msg[l:l+1]) power=int(msg[l+1:]) grovepi.pinMode(port,"OUTPUT") grovepi.analogWrite(port,power) if en_debug: print msg elif match_sensors(msg,digitalOp) >=0: if en_grovepi: s_no=match_sensors(msg,digitalOp) sens=digitalOp[s_no] l=len(sens) port=int(msg[l:l+1]) state=msg[l+1:] grovepi.pinMode(port,"OUTPUT") if state=='on': grovepi.digitalWrite(port,1) else: grovepi.digitalWrite(port,0)
period = timedelta(minutes=1) next_time = datetime.now() + period minutes = 0 motion_litz_on = False while True: try: # ROTARY LIGHTS for i, senz in enumerate(sensorz): sensor_value = grovepi.analogRead(senz) voltage = round((float)(sensor_value) * adc_ref / 1023, 2) degrees = round((voltage * full_angle) / grove_vcc, 2) brightness = int(degrees / full_angle * 255) if brightness != prevv[i]: prevv[i] = brightness grovepi.analogWrite(lightz[i],brightness) # MOTION LIGHT ## Light timeout if next_time <= datetime.now(): minutes += 1 next_time += period grovepi.digitalWrite(litzmotion,0) motion_litz_on = False ## Motion detect if motion_litz_on==False: motion=grovepi.digitalRead(senzormotion) if motion==0 or motion==1: if motion==1: grovepi.digitalWrite(litzmotion,1) motion_litz_on = True
#Grove pi test with Pot and LED import smbus import time import grovepi # for RPI version 1, use "bus = smbus.SMBus(0)" bus = smbus.SMBus(0) # This is the address we setup in the Arduino Program address = 0x04 grovepi.pinMode(5,"OUTPUT") time.sleep(1) i=0 while True: try: i=grovepi.analogRead(2) print i grovepi.analogWrite(5,i/4) except IOError: print "Error"
#Aircon GPIO.setup(peltierpin1, GPIO.OUT) peltier1 = GPIO.PWM(peltierpin1, 50) peltier1.start(0) grovepi.pinMode(peltierfanpin1,"OUTPUT") #ColdBlock GPIO.setup(peltierpin2, GPIO.OUT) peltier2 = GPIO.PWM(peltierpin2, 50) peltier2.start(0) grovepi.pinMode(peltierfanpin2,"OUTPUT") #HotEnd GPIO.setup(heaterpin, GPIO.OUT) heater = GPIO.PWM(heaterpin, 50) heater.start(0) #Fans grovepi.analogWrite(peltierfanpin1,0) #aircon, 0-255 grovepi.analogWrite(peltierfanpin2,0) #coldblock, 0-255 #Buzzer grovepi.pinMode(buzzerpin,"OUTPUT") grovepi.digitalWrite(buzzerpin,0) #off #LED Circular for Camera grovepi.pinMode(ledcirclepin,"OUTPUT") #Starting Individual Thread thread.start_new_thread(sensors.read_sensors, ("SensorsThread",)) #start sensor thread thread.start_new_thread(camera_linedetection.run, ("CameraThread",)) #start camera thread aircon = threading.Thread(target=aircon_output.run, args = (peltierpin1,peltier1,peltierfanpin1)) aircon.daemon = True aircon.start()
def on_message(client, userdata, msg): print "Topic: " + msg.topic + "\nValue: " + msg.payload # Send PWM signal to LED grovepi.analogWrite(led,int(msg.payload)/4)
import grovepi import grovelcd import time grovepi.pinMode(3,"OUTPUT") print "time,ultra,analog" while True: ultra=grovepi.ultrasonicRead(2) ana=grovepi.analogRead(0) digi=grovepi.digitalRead(4) grovepi.analogWrite(3,ultra/2) grovelcd.setRGB(ultra/2,200-ultra/2,0) txt="%d - %d\n wooo yay"%(digi, ana) grovelcd.setText(txt,True) print "%f,%d,%d"%(time.time(),ultra,ana) time.sleep(0.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 sensor_value = grovepi.analogRead(potentiometer) # Calculate voltage voltage = round((float)(sensor_value) * adc_ref / 1023, 2) # Calculate rotation in degrees (0 to 300) degrees = round((voltage * full_angle) / grove_vcc, 2) # Calculate LED brightess (0 to 255) from degrees (0 to 300) brightness = int(degrees / full_angle * 255) # Give PWM output to LED grovepi.analogWrite(led,brightness) print "sensor_value =", sensor_value, " voltage =", voltage, " degrees =", degrees, " brightness =", brightness except IOError: print "Error"
#LED Fade Example import smbus import time import grovepi # for RPI version 1, use "bus = smbus.SMBus(0)" bus = smbus.SMBus(0) # This is the address we setup in the Arduino Program address = 0x04 grovepi.pinMode(5,"OUTPUT") time.sleep(1) i=0 while True: if i>255: i=0 grovepi.analogWrite(5,i) i=i+20 time.sleep(.5) print grovepi.analogRead(0) time.sleep(1)
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import time import grovepi # Connect the Rotary Angle Sensor to analog port A2 potentiometer = 2 # Connect the LED to digital port D5 led = 5 grovepi.pinMode(led,"OUTPUT") time.sleep(1) i = 0 while True: try: # Read resistance from Potentiometer i = grovepi.analogRead(potentiometer) print(i) # Send PWM signal to LED grovepi.analogWrite(led,i//4) except IOError: print("Error")
# One side for power source and the other side for the device you want to control. import time import grovepi # Connect the Grove MOSFET to analog port D6 # SIG,NC,VCC,GND mosfet = 6 grovepi.pinMode(mosfet,"OUTPUT") time.sleep(1) while True: try: # Full speed grovepi.analogWrite(mosfet,255) print "full speed" time.sleep(2) # Half speed grovepi.analogWrite(mosfet,128) print "half speed" time.sleep(2) # Off grovepi.analogWrite(mosfet,0) print "off" time.sleep(2) except KeyboardInterrupt: grovepi.analogWrite(mosfet,0)
grovepi.dust_sensor_en() grovepi.setDustSensorInterval(5000) grovepi.ir_recv_pin(ir) # grovepi.ledBar_init(ledbar, 0) data = { 'sound': 0, 'light': 0, 'button': 0, 'temp': 0, 'humidity': 0, 'prox': 0, 'dust': 0, 'ir': 3 * [0] } while True: data['sound'] = grovepi.analogRead(sound_sensor) data['light'] = grovepi.analogRead(light_sensor) # [data['temp'],data['humidity']] = grovepi.dht(dht_sensor,0) data['button'] = grovepi.digitalRead(button) data['prox'] = grovepi.ultrasonicRead(ultrasonic_ranger) data['dust'] = grovepi.dustSensorRead() grovepi.analogWrite(led, val % 256) # grovepi.ledBar_setBits(ledbar, val % 1024) if grovepi.ir_is_data(): data['ir'] = list(grovepi.ir_read_signal()) val += 10 print(json.dumps(data)) time.sleep(0.2)
light_sensor = 1 # port A1 temperature_sensor = 2 # port D2 led = 3 # port D3 intro_str = "DI Lab's" # Connect to Twitter api = twitter.Api( consumer_key='YourKey', consumer_secret='YourKey', access_token_key='YourKey', access_token_secret='YourKey' ) grovepi.pinMode(led,"OUTPUT") grovepi.analogWrite(led,255) #turn led to max to show readiness while True: # Error handling in case of problems communicating with the GrovePi try: # Get value from temperature sensor [t,h] = grovepi.dht(temperature_sensor,0) # 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
def _set_pwm_duty_cycle(self, pin, value): grovepi.analogWrite(pin.location, int(value * 2.55))
last_sound = 0 while True: # Error handling in case of problems communicating with the GrovePi try: # Get value from temperature sensor [temp,humidity] = grovepi.dht(temperature_sensor,0) t=temp h=humidity # 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 ("Temp: %.2f, Hum: %.2f, Light: %d, Sound: %d" %(t,h,light_intensity/10,last_sound)) api.update_status("Temp: %.2f, Hum: %.2f, Light: %d, Sound: %d" %(t,h,light_intensity/10,last_sound)) time.sleep(180) except IOError: print "Error" except: print "Twittwer exception"
buzzer = 5 SMTP_USERNAME = '' # Mail id of the sender SMTP_PASSWORD = '' # Pasword of the sender SMTP_RECIPIENT = '' # Mail id of the reciever SMTP_SERVER = 'smtp.gmail.com' # Address of the SMTP server SSL_PORT = 465 while True: # in case of IO error, restart try: grovepi.pinMode(switch,"INPUT") while True: if grovepi.digitalRead(switch) == 1: # If the system is ON if grovepi.ultrasonicRead() < 100: # If a person walks through the door print "Welcome" grovepi.analogWrite(buzzer,100) # Make a sound on the Buzzer time.sleep(.5) grovepi.analogWrite(buzzer,0) # Turn off the Buzzer grovepi.digitalWrite(led_status,1) # Turn on the status LED to indicate that someone has arrived grovepi.digitalWrite(relay,1) # turn on the Relay to activate an electrical device # Take a picture from the Raspberry Pi camera call (["raspistill -o i1.jpg -w 640 -h 480 -t 0"], shell=True) print "Image Shot" p = subprocess.Popen(["runlevel"], stdout=subprocess.PIPE) out, err=p.communicate() # Connect to the mail server if out[2] == '0': print 'Halt detected' exit(0) if out [2] == '6': print 'Shutdown detected'
# Digital ports that support Pulse Width Modulation (PWM) # D3, D5, D6 # Digital ports that do not support PWM # D2, D4, D7, D8 grovepi.pinMode(led,"OUTPUT") time.sleep(1) i = 0 while True: try: # Reset if i > 255: i = 0 # Current brightness print (i) # Give PWM output to LED grovepi.analogWrite(led,i) # Increment brightness for next iteration i = i + 20 time.sleep(.5) except KeyboardInterrupt: grovepi.analogWrite(led,0) break except IOError: print ("Error")