def callLeft(data): #gets time time = rospy.get_time() #reads encoder inputs channelA = GPIO.input("P9_23") channelB = GPIO.input("P9_30") #puts inputs into the quadrature decoder program quadCalcL.update(channelA, channelB, time) #creates messages leftFMSG = JointState() leftRMSG = JointState() header = Header() #appends velocity and position data to the joinstate message #front wheel leftFMSG.header.stamp.secs = rospy.get_time() leftFMSG.name.append('front_left_wheel') leftFMSG.position.append(quadCalcL.position) #rear wheel leftRMSG.header.stamp.secs = rospy.get_time() leftRMSG.name.append('rear_left_wheel') leftRMSG.position.append(quadCalcL.position) #publishes message pubFL.publish(leftFMSG) pubRL.publish(leftRMSG)
def callRight(data): #gets time time = rospy.get_time() #reads encoder inputs channelA = GPIO.input("P8_17") channelB = GPIO.input("P8_26") #puts inputs into the quadrature decoder program quadCalcR.update(channelA, channelB, time) #creates messages rightFMSG = JointState() rightRMSG = JointState() header = Header() #appends velocity and position data to the joinstate message #front wheel rightFMSG.header.stamp.secs = rospy.get_time() rightFMSG.name.append('front_right_wheel') rightFMSG.position.append(quadCalcL.position) #rear wheel rightRMSG.header.stamp.secs = rospy.get_time() rightRMSG.name.append('rear_right_wheel') rightRMSG.position.append(quadCalcL.position) #publishes message pubFR.publish(rightFMSG) pubRR.publish(rightRMSG)
def task(): """Execute the main program.""" people_count = 0 # Number of people to be displayed button_press_time = 0.0 # Time button was pressed (in seconds) while (1): # Wait for button press while (GPIO.input(BUTTON0) == 1): pass # Record time button_press_time = time.time() # Wait for button release while (GPIO.input(BUTTON0) == 0): pass # Compare time to increment or reset people_count if (time.time() - button_press_time > RESET_TIME): people_count = 0 else: people_count += 1 # Increments the value of peoplecount by 1 # Update the display HT16K33.update_display(people_count)
def inputButtons(): old_switch_state1 = 1 old_switch_state2 = 1 old_switch_state3 = 1 old_switch_state4 = 1 print "***** Benvenuto nel Thread BUTTON ******" while (1): new_switch_state1 = GPIO.input("P9_21") if new_switch_state1 == 0 and old_switch_state1 == 1: print('Do not press this button 1 again!') function1() time.sleep(0.1) old_switch_state1 = new_switch_state1 new_switch_state2 = GPIO.input("P9_22") if new_switch_state2 == 0 and old_switch_state2 == 1: print('Do not press this button 2 again!') function2() time.sleep(0.1) old_switch_state2 = new_switch_state2 new_switch_state3 = GPIO.input("P9_23") if new_switch_state3 == 0 and old_switch_state3 == 1: print('Do not press this button 3 again!') function3() time.sleep(0.1) old_switch_state3 = new_switch_state3 new_switch_state4 = GPIO.input("P9_24") if new_switch_state4 == 0 and old_switch_state4 == 1: print('Do not press this button 4 again!') function4() time.sleep(0.1) old_switch_state4 = new_switch_state4
def read(sid, message): result = '_' sensor = message['sensor'] side = message['side'] # print(side) if (sensor == 'En'): result = 'Encoders do not work for this demo' elif (sensor == 'Bump'): if (side == 'left'): print(GPIO.input(Left_line)) result = str(GPIO.input(Left_line)) else: result = str(GPIO.input(Left_line)) elif (sensor == 'Sonic'): if (side == 'left'): result = str(robo.get_adc_raw(3)) else: result = str(robo.get_adc_raw(2)) elif (sensor == 'Line'): if (side == 'left'): result = str(robo.get_adc_raw(0)) else: result = str(robo.get_adc_raw(1)) sio.emit('read', { 'side': message['side'], 'sensor': sensor, 'value': result })
def readSonar(sensorTrig, sensorEcho): signaloff = 0 signalon = 0 status = 1 while ((signaloff == 0) and status == 1) or (signalon == 0 and status == 1): time.sleep(.01) GPIO.output(sensorTrig, True) time.sleep(0.00001) GPIO.output(sensorTrig, False) signalstart = time.time() while GPIO.input(sensorEcho) == 0 and status == 1: signaloff = time.time() if (signaloff - signalstart) > .35: status = 0 while GPIO.input(sensorEcho) == 1 and status == 1: signalon = time.time() if (signalon - signalstart) > .7: status = 0 if status == 1: timepassed = signalon - signaloff distance = timepassed * 17000 if status == 0: distance = 0 return distance GPIO.cleanup()
def main(): print "Setting up GPIO" accUp = "P8_14" accDown = "P8_15" # Variables GPIO.setup( accUp, GPIO.IN ) GPIO.setup( accDown, GPIO.IN ) # GPIO.add_event_detect( accDown, GPIO.BOTH ) # GPIO.setup( "P9_15", GPIO.OUT ) global running speed = 50 try: print "IN" while True: t.sleep(.1) if GPIO.input( accUp ): speed = speed + 5 print "Speed: %s" % speed elif GPIO.input( accDown ): if (speed > 0): speed = speed - 5 print "Speed: %s" % speed except KeyboardInterrupt: GPIO.cleanup() print "Ending program"
def __sendCommand(self, command): #Transmission start GPIO.setup(self.dataPin, GPIO.OUT) GPIO.setup(self.sckPin, GPIO.OUT) GPIO.output(self.dataPin, GPIO.HIGH) self.__clockTick(GPIO.HIGH) GPIO.output(self.dataPin, GPIO.LOW) self.__clockTick(GPIO.LOW) self.__clockTick(GPIO.HIGH) GPIO.output(self.dataPin, GPIO.HIGH) self.__clockTick(GPIO.LOW) for i in range(8): GPIO.output(self.dataPin, command & (1 << 7 - i)) self.__clockTick(GPIO.HIGH) self.__clockTick(GPIO.LOW) self.__clockTick(GPIO.HIGH) GPIO.setup(self.dataPin, GPIO.IN) ack = GPIO.input(self.dataPin) logger.debug("ack1: %s", ack) if ack != GPIO.LOW: logger.error("nack1") self.__clockTick(GPIO.LOW) ack = GPIO.input(self.dataPin) logger.debug("ack2: %s", ack) if ack != GPIO.HIGH: logger.error("nack2")
def updatePosition(pin): state = GPIO.input(pin) time.sleep(0.05) if state != GPIO.input(pin): return global x, y, y1, x1, screen, quit key = pin if key == 'P9_22': # quit quit = True elif key == 'P9_23': # clear screen print("Clearing screen...") screen = [[" " for x in range(x1)] for x in range(y1)] elif key == 'P9_18': #go right if x < x1: x += 1 elif key == 'P9_19': #go left if x > 0: x -= 1 elif key == 'P9_20': #go up if y > 0: y -= 1 elif key == 'P9_21': #go down if y < y1: y += 1 screen[x][y] = 'X'
def callLeft(data): #reads encoder inputs channelA = GPIO.input("P9_23") channelB = GPIO.input("P9_30") print channelA, channelB
def count(): #Function to count ticks global left_tick global right_tick global flag_left global flag_right global flag_direction_l global flag_direction_r if GPIO.input("P9_26"): flag_left = True if GPIO.input("P9_30"): flag_right = True if (not GPIO.input("P9_26")) and flag_left: flag_left = False left_tick += flag_direction_l #print "counting left ticks", left_tick if (not GPIO.input("P9_30")) and flag_right: flag_right = False right_tick += flag_direction_r #print "counting right ticks", right_tick return
def new_msg(): pygame.display.init() print_echo("new CLP command") screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN) pygame.mouse.set_visible(0) x = 8*GPIO.input("P8_18")+4*GPIO.input("P8_16")+2*GPIO.input("P8_14")+GPIO.input("P8_12") # Tenta carregar a imagem do diretorio compartilhado. Caso nao consiga, carrega do diretorio interno try: directory_shared = "/home/debian/Desktop/shared/" + str(x) + ".png" image = pygame.image.load(directory_shared) print_echo(directory_shared) except: directory_interno = "/home/debian/Desktop/Project_display/images/" + str(x) + ".png" image = pygame.image.load(directory_interno) print_echo(directory_interno) image = pygame.transform.scale(image, (screen.get_size()[0], screen.get_size()[1])) back = pygame.Surface(screen.get_size()) back = back.convert() back.blit(image,(0,0)) screen.blit(back,(0,0)) while GPIO.input("P8_11"): pygame.display.flip() #time.sleep(0.5) print_echo("end of command") pygame.display.quit()
def update_encoders(arg): #Fix indentation encoderr.update(GPIO.input("P9_23"),GPIO.input("P9_24"),rospy.get_rostime().to_sec()) left = JointState() #Add joint name and timestamps print rospy.get_rostime().to_sec() left.header.frame_id = "front_left_wheel_link" left.header.stamp = arg.current_real left.position.append(encoderr.position) left.velocity.append(encoderr.velocity) encoderl.update(GPIO.input("P8_17"),GPIO.input("P8_26"),rospy.get_rostime().to_sec()) right = JointState() right.header.frame_id = "front_right_wheel_link" right.header.stamp = arg.current_real right.position.append(encoderl.position) right.velocity.append(encoderl.velocity) rospy.loginfo(left) publ.publish(left) rospy.loginfo(right) pubr.publish(right) rearleft = JointState() rearleft.header.frame_id = "rear_left_wheel_link" rearleft.header.stamp = arg.current_real rearleft.position.append(encoderr.position) rearleft.velocity.append(encoderr.velocity) rospy.loginfo(rearleft) rearright = JointState() rearright.header.frame_id = "rear_right_wheel_link" rearright.header.stamp = arg.current_real rearright.position.append(encoderl.position) rearright.velocity.append(encoderl.velocity)
def digitalinp(inp): print 'INPUT', inp, 'IS', 'open' if GPIO.input(INPUTS[inp]) else 'close' print print 'Waiting for a state change... (or ctrl+C to exit)' GPIO.wait_for_edge(INPUTS[inp], GPIO.BOTH) time.sleep(.01) # Adafruit library needs a little time to detect right status print 'INPUT', inp, 'IS NOW', 'open' if GPIO.input(INPUTS[inp]) else 'close'
def get_player_sequence(): if (current_round > 1): del player_sequence[:] number_of_plays = 0 play_time_begin = time.time() #Return the number of seconds since epoch play_time_end = time.time() while ((play_time_end - play_time_begin) < current_round + 5): if (GPIO.input(b0)): player_sequence.append(0) number_of_plays += 1 print("B0") time.sleep(0.25) if (GPIO.input(b1)): player_sequence.append(1) number_of_plays += 1 print("B1") time.sleep(0.25) if (GPIO.input(b2)): player_sequence.append(2) number_of_plays += 1 print("B2") time.sleep(0.25) play_time_end = time.time() if (number_of_plays == current_round): break if (number_of_plays < current_round): while True: blink(off, 0.1)
def run(self): alarmState = False settingState = False GPIO.setup("Setting_push", GPIO.IN) GPIO.setup("Alarm_push", GPIO.IN) threadLock = threading.Lock() while(self.running): threadLock.acquire() if GPIO.input("Setting_push") == 1: settingValue = False else: settingValue = True if GPIO.input("Alarm_push") == 1: alarmValue = False else: alarmValue = True threadLock.release() if alarmState != alarmValue: alarmState = alarmValue self.alarmCb(alarmValue) if settingState != settingValue: settingState = settingValue if settingValue: self.setUnsetCb() time.sleep(0.2) GPIO.cleanup()
def monitor(): global enviado #try: #update_id = bot.getUpdates()[0].update_id #except IndexError: #update_id = None #for update in bot.getUpdates(offset=update_id, timeout=10): #chat_id = update.message.chat_id #print chat_id #update_id = update.update_id + 1 #message = update.message.text if GPIO.input(switch) == 1: rmMarker() print "chave ativa, mapa limpo" if not GPIO.input(sens1) and enviado is False: # sensor fechado (ativo) addMarker() print "sensor ativado" sendIotHub() #print "IoT Hub OK" bot.sendMessage(chat_id=73270008, text="Intrusao detectada em sua residencia!") print "Tg chat OK" time.sleep(1) bot.sendMessage(chat_id='@vigiadobairro', text="Atencao! Intrusao detectada em uma residencia do bairro! Visite [Vigia do Bairro](http://vigiadobairro.noip.me)", parse_mode=telegram.ParseMode.MARKDOWN) print "Tg chan OK" enviado = True if GPIO.input(sens1) and enviado is True: # sensor aberto (inativo) print "sensor desativado" enviado = False
def security(): #Please edit the URL given below according to your cluster client = MongoClient( "mongodb://*****:*****@car-e-mainframe-shard-00-00-tppcz.mongodb.net:27017,car-e-mainframe-shard-00-01-tppcz.mongodb.net:27017,car-e-mainframe-shard-00-02-tppcz.mongodb.net:27017/<DATABASE>?ssl=true&replicaSet=Car-E-Mainframe-shard-0&authSource=admin" ) db = client.database print('Initializing security check....') key = "01001101" #Dummy key. car_no = "WB069102" check = db.database.find_one({'car number': 'DL011303'}) current_key = check.get('pass code') while True: val1 = GPIO.input(pad1) val2 = GPIO.input(pad2) val3 = GPIO.input(pad3) val4 = GPIO.input(pad4) current_key += val1 + val2 + val3 + val4 if (len(current_key) == len(key) and current_key != key): print('Sorry! You entered the wrong key! Try again...') current_key = '' elif (len(current_key) == len(key) and current_key == key): #Match key with car number from database. print 'Welcome ', check.get('name'), '!' UID = check.get('uid') threshold_gsr = check.get('GSR Threshold') threshold_alchahol = check.get('Alchahol Threshold')
def run(self): """Execute the main program.""" people_count = 0 # Number of people to be displayed button_press_time = 0.0 # Time button was pressed (in seconds) while (1): # Wait for button press while (GPIO.input(self.button) == 1): pass # Record time button_press_time = time.time() # Wait for button release while (GPIO.input(self.button) == 0): pass # Compare time to increment or reset people_count if ((time.time() - button_press_time) > self.reset_time): people_count = 0 else: people_count += 1 # Update the display self.display.update(people_count)
def calibrateTouch(self, samples): # the idea here is to calibrate for the same number of samples that are specified # but to make sure that the value is over a certain number of powerline cycles to # average out powerline errors GPIO.setup(sendPin, GPIO.OUT) # set Send pin Output start = time.clock() while time.clock() - start is less than calibrateTime: for i in range(samples): # for (i = 0; i < samples; i++): GPIO.setup(receivePin, GPIO.IN) # set receive pin to input GPIO.output(receivePin, GPIO.LOW) # set receive pin low (pullups off ) GPIO.setup(receivePin, GPIO.OUT) # OUTPUT to discharge circuit GPIO.setup(receivePin, GPIO.IN) # set pin to INPUT GPIO.output(sendPin, GPIO.HIGH) # set send pin High while GPIO.input(receivePin) is 0 and total is less than timeoutCount: # while receive pin is LOW AND total is positive value total = total + 1 if total >= timeoutCount: return -2 # total variable over timeout # set receive pin HIGH briefly to charge up fully # because the while loop above will exit when pin is ~ 2.5V GPIO.output(receivePin, GPIO.HIGH) # set receive pin HIGH (pullup on) GPIO.setup(receivePin, GPIO.OUT) # set pin to OUTPUT GPIO.setup(receivePin, GPIO.IN) # set pin to INPUT GPIO.output(receivePin, GPIO.LOW) # turn off pullup GPIO.output(sendPin, GPIO.LOW) # set send Pin LOW while GPIO.input(receivePin) is 1 and total is less than timeoutCount: total = total + 1 j = j + 1
def run(self): # Create new threads self.dialer.start() self.dialer.spawn() print 'Linphone Running: ' + str(self.dialer.isrunning()) self.inUse = False while True: feedback = self.dialer.getLineStatus() if feedback == 'Incoming Call' and self.inUse is False: self.answerIncoming() elif feedback == 'Call ended': self.inUse = False else: pass if gpio.input(self.hook3) and self.dialer.isOnCall() is False and self.inUse is False and self.prevHookState == 'Low': self.inUse = True self.prevHookState = 'High' success = False while not success and gpio.input(self.hook3): success = self.makeCall() elif not gpio.input(self.hook3) and self.prevHookState == 'High': if self.dialer.isOnCall(): self.dialer.terminateCall() else: pass
def monitor(): global enviado try: update_id = bot.getUpdates()[0].update_id except IndexError: update_id = None for update in bot.getUpdates(offset=update_id, timeout=10): chat_id = update.message.chat_id #print chat_id update_id = update.update_id + 1 message = update.message.text if GPIO.input(switch) == 1: rmMarker() print "chave ativa, mapa limpo" if not GPIO.input(sens1) and enviado is False: # sensor fechado (ativo) addMarker() print "sensor ativado" sendIotHub() bot.sendMessage(chat_id=73270008, text="Intrusao detectada em sua residencia!") bot.sendMessage( chat_id='@vigiadobairro', text= "Atencao! Intrusao detectada em uma residencia do bairro! Visite [Vigia do Bairro](http://vigiadobairro.noip.me)", parse_mode=telegram.ParseMode.MARKDOWN) enviado = True if GPIO.input(sens1) and enviado is True: # sensor aberto (inativo) print "sensor desativado" enviado = False
def FindObjectdistance(GPIO_TRIGGER, GPIO_ECHO): timeout = 0 GPIO.output(GPIO_TRIGGER, GPIO.LOW) time.sleep(0.5) GPIO.output(GPIO_TRIGGER, GPIO.HIGH) #trigger to high time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, GPIO.LOW) #trigger to low after 0.01 ms while GPIO.input(GPIO_ECHO) == 0 and timeout < 10000: timeout += 1 StartTime = time.time() while GPIO.input(GPIO_ECHO) == 1 and timeout < 10000: timeout += 1 StopTime = time.time() #time of arrival if timeout < 10000: TimeElapsed = StopTime - StartTime objectdistance = (TimeElapsed * 34300)/ 2 #distance in cm else: objectdistance = 1000 return objectdistance
def taskDial(): # Dial Password Lock global DIAL_CORRECT_VALUE DIAL_CORRECT_VALUE = 0 while (GPIO.input(BUTTON0) == 1): pass # Gets angle from potentiometers angle1 = float(ADC.read(ANALOG_INPUT1)) angle2 = float(ADC.read(ANALOG_INPUT2)) angle3 = float(ADC.read(ANALOG_INPUT3)) if (angle1 < float(0.5) and angle2 < float(0.5) and angle3 < float(0.5)): if (debug): print("Dial: Correct") GPIO.output(CORRECT_OUTPUT, GPIO.HIGH) GPIO.output(INCORRECT_OUTPUT, GPIO.LOW) DIAL_CORRECT_VALUE = 1 else: GPIO.output(CORRECT_OUTPUT, GPIO.LOW) GPIO.output(INCORRECT_OUTPUT, GPIO.HIGH) if (debug): print("Dial: Wrong Combo") time.sleep(1) GPIO.output(INCORRECT_OUTPUT, GPIO.LOW) if (debug): print(DIAL_CORRECT_VALUE) while (GPIO.input(BUTTON0) == 0): pass
def _measure_ultra(self, trigger, echo): GPIO.output(trigger, True) time.sleep(DECPULSETRIGGER) GPIO.output(trigger, False) # Wait for echo to go high (or timeout) intcountdown = INTTIMEOUT while (GPIO.input(echo) == 0 and intcountdown > 0): intcountdown = intcountdown - 1 # If echo is high if intcountdown > 0: # Start timer and init timeout countdown echostart = time.time() intcountdown = INTTIMEOUT # Wait for echo to go low (or timeout) while (GPIO.input(echo) == 1 and intcountdown > 0): intcountdown = intcountdown - 1 # Stop timer echoend = time.time() # Echo duration echoduration = echoend - echostart # Display distance if intcountdown > 0: intdistance = (echoduration * 1000000) / 58 #print "Distance = " + str(intdistance) + "cm" return intdistance
def agilent4uhv(): """ AGILENT 4UHV """ logger.debug("AGILENT 4UHV") if (GPIO.input(PIN_FTDI_PRU) == FTDI and GPIO.input(PIN_RS232_RS485) == RS485 and PRUserial485_address() == 21 and os.path.exists(PORT)): baud = 38400 ser = Serial(port=PORT, baudrate=baud, timeout=0.6) devices = [] for addr in range(0, 32): ser.reset_input_buffer() ser.reset_output_buffer() pl = "" pl += "\x02" pl += chr(addr + 128) pl += "\x38" pl += "\x31" pl += "\x30" pl += "\x30" pl += "\x03" ser.write(Agilent4UHV_CRC(pl).encode("latin-1")) res = ser.read(15).decode("latin-1") if len(res) != 0: devices.append(addr) ser.close() name = "Agilent 4UHV" if len(devices): persist_info(Type.AGILENT4UHV, name, baud, AGILENT4UHV, "AGILENT4UHV connected {}".format(devices))
def action(changePin, action): # Convert the pin from the URL into an integer: changePin = changePin # Get the device name for the pin being changed: deviceName = pins[changePin]['name'] # If the action part of the URL is "on," execute the code indented below: if action == "on": # Set the pin high: GPIO.output(changePin, GPIO.HIGH) # Save the status message to be passed into the template: message = "Turned " + deviceName + " on." if action == "off": GPIO.output(changePin, GPIO.LOW) message = "Turned " + deviceName + " off." if action == "toggle": # Read the pin and set it to whatever it isn't (that is, toggle it): GPIO.output(changePin, not GPIO.input(changePin)) message = "Toggled " + deviceName + "." # For each pin, read the pin state and store it in the pins dictionary: for pin in pins: pins[pin]['state'] = GPIO.input(pin) # Along with the pin dictionary, put the message into the template data dictionary: templateData = {'message': message, 'pins': pins} return render_template('main.html', **templateData)
def distanceMeasurement(TRIG, ECHO): #Define una funcion que depende del trigg$ GPIO.output(TRIG, True) #Inicio del pulso time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO) == 0: pulseStart = time.time() while GPIO.input(ECHO) == 1: pulseEnd = time.time() pulseDuration = pulseEnd - pulseStart #dt distance = pulseDuration * 17150 #dx=dt*vs/2 distance = round(distance, 2) #Redondea el valor de la distancia $ return (distance) pulseStart = time.time() while GPIO.input(ECHO) == 1: pulseEnd = time.time() pulseDuration = pulseEnd - pulseStart #dt distance = pulseDuration * 17150 #dx=dt*vs/2 distance = round(distance, 2) #Redondea el valor de la distancia $ return (distance)
def agilent4uhv(): """ AGILENT 4UHV """ logger.debug('AGILENT 4UHV') if GPIO.input(PIN_FTDI_PRU) == FTDI and GPIO.input( PIN_RS232_RS485) == RS485 and PRUserial485_address() == 21: baud = 38400 ser = Serial(port=PORT, baudrate=baud, timeout=.6) devices = [] for addr in range(0, 32): ser.reset_input_buffer() ser.reset_output_buffer() pl = "" pl += "\x02" pl += chr(addr + 128) pl += "\x38" pl += "\x31" pl += "\x30" pl += "\x30" pl += "\x03" ser.write(Agilent4UHV_CRC(pl)) res = ser.read(15) if len(res) != 0: devices.append(addr) ser.close() if len(devices): persist_info(Type.AGILENT4UHV, baud, AGILENT4UHV, 'AGILENT4UHV connected {}'.format(devices))
def get_onoff(self, pinname=None): if pinname is None: ret = [ GPIO.input(self.pinDict[pinname0]) for pinname0 in self.pinnames ] elif isinstance(pinname, list): if not all([(pinname0 in self.pinnames) for pinname0 in pinname]): print( 'Stopper:get_onoff(): ERROR! There is no GPIO pin names.') print( 'Stopper:get_onoff(): Assigned pin names = {}'.format( self.pinnames)) print( 'Stopper:get_onoff(): Asked pin names = {}'.format( pinname)) return -1 ret = [GPIO.input(self.pinDict[pinname0]) for pinname0 in pinname] else: if not (pinname in self.pinnames): print( 'Stopper:get_onoff(): ERROR! There is no GPIO pin name of {}.' .format(pinname)) print( 'Stopper:get_onoff(): Assigned pin names = {}'.format( self.pinnames)) return -1 ret = GPIO.input(self.pinDict[pinname]) pass return ret
def _measure_ultra(self, trigger, echo): GPIO.output(trigger, True) time.sleep(DECPULSETRIGGER) GPIO.output(trigger, False) # Wait for echo to go high (or timeout) intcountdown = INTTIMEOUT while (GPIO.input(echo) == 0 and intcountdown > 0): intcountdown = intcountdown - 1 # If echo is high if intcountdown > 0: # Start timer and init timeout countdown echostart = time.time() intcountdown = INTTIMEOUT # Wait for echo to go low (or timeout) while (GPIO.input(echo) == 1 and intcountdown > 0): intcountdown = intcountdown - 1 # Stop timer echoend = time.time() # Echo duration echoduration = echoend - echostart # Display distance if intcountdown > 0: intdistance = (echoduration*1000000)/58 #print "Distance = " + str(intdistance) + "cm" return intdistance
def button_press(self, function=None): """Button press - Optional function to execute while waiting for the button to be pressed - Returns the last value of the function when the button was pressed - Waits for a full button press - Returns the time the button was pressed """ button_press_time = 0.0 # Time button was pressed (in seconds) ret_val = None # Optional return value for provided function # Wait for button press while (GPIO.input(self.button) == 1): # Optionally execute function pointer that is provided if function is not None: ret_val = function() # Sleep for a short period of time to reduce CPU load time.sleep(0.1) # Record time button_press_time = time.time() # Wait for button release while (GPIO.input(self.button) == 0): # Sleep for a short period of time to reduce CPU load time.sleep(0.1) # Compute button press time button_press_time = time.time() - button_press_time # Return button press time and optionally ret_val if function is not None: return (button_press_time, ret_val) else: return button_press_time
def activated(yellowSeconds): global LED_status yellowOff = True baseTime = time.time() GPIO.output(greenLED, GPIO.HIGH) if yellowSeconds == WARNTIME: print getTime() + "Ammy is going out" while GPIO.input(actCircuit): timePassed = int(time.time() - baseTime) if yellowOff and (timePassed > yellowSeconds): yellowOff = False GPIO.output(yellowLED, GPIO.HIGH) print getTime() + "Ammy has been out for " + str(WARNTIME/60) + " minutes" #IR sensor drops to 0V when activated if GPIO.input(irSensor): GPIO.output(redLED, GPIO.LOW) else: GPIO.output(redLED, GPIO.HIGH) #opening the door triggers the proximity sensor, so wait a bit if timePassed > 20: print getTime() + "Ammy is waiting to come in" #determine color to send over network if not GPIO.input(irSensor) and timePassed > 20: #red LED takes precedence LED_status = 'red' elif timePassed > yellowSeconds: LED_status = 'yellow' else: LED_status = 'green' time.sleep(1) return int(time.time() - baseTime)
def new_msg(): #print_echo(str(GPIO.input("P8_17"))) x = GPIO.input("P8_18")*32+GPIO.input("P8_12")*16+GPIO.input("P8_11")*8+GPIO.input("P8_17")*4+GPIO.input("P8_15")*2+GPIO.input("P8_13") image_file=str(x)+".png" display_image(image_file) print_echo("Event P8_14 - new PLC command: " + image_file) if flag_connected: client.publish("RAIS/"+client_name+"/clp-message",image_file,qos=2,retain=True)
def readHall(): # Read hall effect sensors. This is just for testing. It's not really useful # for testing in the system because it does not account for the ballast moving past the sensors hallPort = GPIO.input(hallPortPin) hallStbd = GPIO.input(hallStbdPin) print("port:" + str(hallPort)) print("stbd:" + str(hallStbd))
def handler(self, x): #print x + ': ' + str(GPIO.input(x)) + ' : ' + str(time.time() - self.lastEventTime) self.stateLock.acquire() if self.state == 0 and GPIO.input(x) == 1: #print x + " was pressed" self.callback() self.state = GPIO.input(x) self.stateLock.release()
def callback2(var): while GPIO.input(button2): if GPIO.input(button1): GPIO.output(led2, GPIO.LOW) GPIO.cleanup() exit() GPIO.output(led2, GPIO.HIGH) GPIO.output(led2, GPIO.LOW)
def main(stdscr): stdscr = curses.initscr() curses.noecho() parser = argparse.ArgumentParser() parser.add_argument('--size') args = parser.parse_args() stdscr.clear() GPIO.setup("P8_8", GPIO.IN) GPIO.setup("P8_10", GPIO.IN) GPIO.setup("P8_12", GPIO.IN) GPIO.setup("P8_14", GPIO.IN) GPIO.setup("P8_26", GPIO.IN) #add the numbers of the grid on the x and y axis for i in range(0, int(args.size)): stdscr.addstr(0, 2 * i + 1, (str(i) + " ")) for i in range(0, int(args.size)): stdscr.addstr(i + 1, 0, str(i)) x = 1 y = 1 stdscr.addstr(y, x, 'X') stdscr.refresh() while True: # key_input = stdscr.getkey() # print("HelloWorld") if GPIO.input("P8_12"): y -= 1 if y < 1: y = 1 stdscr.addstr(y, x, 'X') sleep(.3) if GPIO.input("P8_8"): y += 1 if y > int(args.size): y = int(args.size) stdscr.addstr(y, x, 'X') sleep(.3) if GPIO.input("P8_10"): x -= 2 if x < 1: x = 1 stdscr.addstr(y, x, 'X') sleep(.3) if GPIO.input("P8_14"): x += 2 if x > (int(args.size) * 2): x = int(args.size) * 2 - 1 stdscr.addstr(y, x, 'X') sleep(.3) if GPIO.input("P8_26"): stdscr.clear() main(stdscr) stdscr.refresh()
def alertTriggered(pin): # read temperatures and convert them to farienheit temp1 = bus.read_byte_data(adress1, 0) temp1 = temp1 * 9 / 5 + 32 temp2 = bus.read_byte_data(adress2, 0) temp2 = temp2 * 9 / 5 + 32 print("temp1: ", temp1, " temp2: ", temp2, " alert1: ", GPIO.input(alert1), " alert2: ", GPIO.input(alert2))
def verify_state(self, state): if state == GPIO.input(self._pin): self.log.debug('Pin state changed successfully.') return True else: self.log.error('State change FAILED on pin: {pin}', pin=self._pin) self.log.debug('Requested state: {reqst}, current state: {curst}}', reqst=state, curst=GPIO.input(self._pin)) return False
def my_callback(inputbutton): if inputbutton == "P8_8": GPIO.output("P8_16", GPIO.input("P8_8")) if inputbutton == "P8_10": GPIO.output("P8_18", GPIO.input("P8_10")) if inputbutton == "P8_12": GPIO.output("P8_15", GPIO.input("P8_12")) if inputbutton == "P8_14": GPIO.output("P8_17", GPIO.input("P8_14"))
def initialize(self): self.logger.info("Beginning initialization") self.__configureGPIO() time.sleep(0.1) pinStateA = GPIO.input(self.gpioPins[EncoderChannel.A]) pinStateB = GPIO.input(self.gpioPins[EncoderChannel.B]) pinStateClick = GPIO.input(self.gpioPins[Click.CLICK]) self.logger.info("initial pin states: A: %s, B: %s, Click: %s", pinStateA, pinStateB, pinStateClick) self.logger.info("Initialization complete.")
def player_turn(): global score time_start = time.time() time_end = time.time() bad_move = False good_move = 0 index = 0 while ((time_end - time_start) < current_round + 3) and (not bad_move) and good_move < current_round: if GPIO.input(button0): if game_array[index] != 0: bad_move = True else: good_move += 1 index += 1 PWM.start(BUZZER, 50, NOTES[0]) time.sleep(0.5) PWM.stop(BUZZER) if GPIO.input(button1): if game_array[index] != 1: bad_move = True else: good_move += 1 index += 1 PWM.start(BUZZER, 50, NOTES[1]) time.sleep(0.5) PWM.stop(BUZZER) if GPIO.input(button2): if game_array[index] != 2: bad_move = True else: good_move += 1 index += 1 PWM.start(BUZZER, 50, NOTES[2]) time.sleep(0.5) PWM.stop(BUZZER) if GPIO.input(button3): if game_array[index] != 3: bad_move = True else: good_move += 1 index += 1 PWM.start(BUZZER, 50, NOTES[3]) time.sleep(0.5) PWM.stop(BUZZER) time_end = time.time() if good_move == current_round: score += 1 lcd.lcd_display_string("Current Score: " + str(score), 1) return True else: return False
def index(): # Read GPIO Status buttonSts = GPIO.input(button) ledRedSts = GPIO.input(ledRed) templateData = { 'button' : buttonSts, 'ledRed' : ledRedSts, } return render_template('index.html', **templateData)
def digitalinp(inp): print 'INPUT', inp, 'IS', 'open' if GPIO.input(INPUTS[inp]) else 'close' print print 'Waiting for a state change... (or ctrl+C to exit)' GPIO.wait_for_edge(INPUTS[inp], GPIO.BOTH) time.sleep( .01) # Adafruit library needs a little time to detect right status print 'INPUT', inp, 'IS NOW', 'open' if GPIO.input( INPUTS[inp]) else 'close'
def play(): if (current_round > 1): del player_sequence[:] number_of_plays = 0 time_begin = time.time() # Retorna o tempo em segundos time_end = time.time() # O jogador tem // segundo para fazer a sequencia while ((time_end - time_begin) < current_round + 1): if (GPIO.input(button0)): player_sequence.append(0) number_of_plays += 1 PWM.start(buzzer, 50, 262, 1) #DO time.sleep(0.3) PWM.stop(buzzer) print("button0") time.sleep(0.25) if (GPIO.input(button1)): player_sequence.append(1) number_of_plays += 1 PWM.start(buzzer, 50, 294, 1) #RE time.sleep(0.3) PWM.stop(buzzer) print("button1") time.sleep(0.25) if (GPIO.input(button2)): player_sequence.append(2) number_of_plays += 1 PWM.start(buzzer, 50, 330, 1) #MI time.sleep(0.3) PWM.stop(buzzer) print("button2") time.sleep(0.25) if (GPIO.input(button3)): player_sequence.append(3) number_of_plays += 1 PWM.start(buzzer, 50, 300, 1) #FA time.sleep(0.3) PWM.stop(buzzer) print("button3") time.sleep(0.25) time_end = time.time() if (number_of_plays == current_round): break if (number_of_plays < current_round): blinkAll(0.1) PWM.start(buzzer, 50, 262, 1) #DO time.sleep(1) PWM.stop(buzzer) print("GAME OVER - TEMPO ESGOTADO") game_started = False gameOver()
def timeResponse(accel,speed,delay,totalTime): if(totalTime < 2): print "Hey totalTime must be greater than 2!" return while GPIO.input("P8_9"): pass t0 = time() t = [0] ultrasonic.updateDistances() us = [ultrasonic.calculateAngle()] rps = [tuple(motor.readEncoderSpeeds())] motor.moveForward(speed,speed) sleep(delay) #takes readings for 2 seconds before responding to button to stop it while (t[-1] < 2): #take readings has access to variables inside timeResponse? t,rps,us = takeReadings(t,rps,t0,us) #now does same thing but checks for button to stop while GPIO.input("P8_9") and ((t[-1] - t0) < 10): t,rps,us = takeReadings(t,rps,t0,us) motor.moveForward(0,0) sleep(3) #unzip rps so we have time response of each motor lf,rf,lb,rb = zip(*rps) rpsData = [lf,rf,lb,rb] tFile = open('timedata.txt','w') for point in t: tFile.write("%s\n" % point) tFile.close() fileString = "RPS_TimeResponse" count = 1 for data in rpsData: f = open(fileString + str(count) + ".txt",'w') for point in data: f.write("%s\n"%point) f.close() count += 1 fileString ="UltrasonicAngleData.txt" f = open(fileString, 'w') for point in us: for angle in point: angle = angle * 180 / math.pi f.write("%s "%angle) f.write("\n") f.close()
def initialize(self): self.logger.info("Beginning initialization") self.__configureGPIO() time.sleep(0.1) self.pinStates[SwitchPosition.UP] = GPIO.input(self.gpioPins[SwitchPosition.UP]) self.pinStates[SwitchPosition.DOWN] = GPIO.input(self.gpioPins[SwitchPosition.DOWN]) self.pinStates[SwitchPosition.LEFT] = GPIO.input(self.gpioPins[SwitchPosition.LEFT]) self.pinStates[SwitchPosition.RIGHT] = GPIO.input(self.gpioPins[SwitchPosition.RIGHT]) self.pinStates[SwitchPosition.CENTER] = GPIO.input(self.gpioPins[SwitchPosition.CENTER]) self.logger.info("initial pin states: %s", self.pinStates) self.logger.info("Initialization complete.")
def Count(channel): # Get time when Echo line goes high (ie: RISING edge) if GPIO.input("P8_15") == GPIO.HIGH and not Count.counting: Count.startTime = datetime.now() Count.counting = True # Get time when Echo line goes low (ie: FALLING edge) elif GPIO.input("P8_15") == GPIO.LOW and Count.counting: Count.endTime = datetime.now() # delta is the period of the echo (roughly) Count.delta = Count.endTime - Count.startTime Count.counting = False return
def __measureEcho(self, channel): # Get time when Echo line goes high (ie: RISING edge) if GPIO.input(self.ECHO_RETURN) == GPIO.HIGH and not self.COUNTING: self.startTime = datetime.now() self.COUNTING = True # Get time when Echo line goes low (ie: FALLING edge) elif GPIO.input(self.ECHO_RETURN) == GPIO.LOW and self.COUNTING: self.endTime = datetime.now() # delta is the period of the echo (roughly) self.delta = self.endTime - self.startTime self.COUNTING = False return
def handshake(self): if self.debug: print "Starting handshake..." pause = 0.02 self.setupHandshake() if not GPIO.input(self.slaveSelect): if self.debug: print "slave low" GPIO.output(self.mosi, GPIO.LOW) GPIO.output(self.spiClock, GPIO.LOW) else: if self.debug: print "wait for slave low" while GPIO.input(self.slaveSelect): pass GPIO.output(self.mosi, GPIO.LOW) GPIO.output(self.spiClock, GPIO.LOW) if self.debug: print "START" while not GPIO.input(self.slaveSelect): pass GPIO.output(self.mosi, GPIO.HIGH) GPIO.output(self.spiClock, GPIO.HIGH) if self.debug: print "A" while GPIO.input(self.slaveSelect): pass GPIO.output(self.mosi, GPIO.LOW) GPIO.output(self.spiClock, GPIO.LOW) if self.debug: print "B" while not GPIO.input(self.slaveSelect): pass GPIO.setup(self.slaveSelect, GPIO.OUT) GPIO.output(self.slaveSelect, GPIO.LOW) if self.debug: print "C" sleep(pause) GPIO.output(self.spiClock, GPIO.HIGH) if self.debug: print "END" sleep(pause) GPIO.output(self.spiClock, GPIO.LOW) if self.debug: print "Handshake completed."
def check_io(): IO_GROUP1 = ['P8_7','P8_9','P8_12','P8_13','P8_15','P8_18','P8_26','P8_27','P8_29', 'P8_35','P8_36','P8_37','P8_40','P8_45','P9_13','P9_16','P9_18', 'P9_23','P9_26','P9_27','P9_30'] IO_GROUP2 = ['P8_8','P8_10','P8_11','P8_14','P8_16','P8_17','P8_19','P8_28','P8_30', 'P8_32','P8_33','P8_34','P8_38','P8_39','P8_46','P9_11','P9_12', 'P9_14','P9_15','P9_17','P9_24','P9_28','P9_29','P9_41','P9_42'] IO_GROUP3 = ['P8_31','P8_42','P8_43'] IO_GROUP4 = ['P8_41','P8_44'] badio = [] GPIO.setup(IO_GROUP1[0], GPIO.OUT) for pin in IO_GROUP1[1:]: GPIO.setup(pin, GPIO.IN) GPIO.output(IO_GROUP1[0], GPIO.HIGH) GPIO.setup(IO_GROUP2[0], GPIO.OUT) for pin in IO_GROUP2[1:]: GPIO.setup(pin, GPIO.IN) GPIO.output(IO_GROUP2[0], GPIO.LOW) GPIO.setup(IO_GROUP3[0], GPIO.OUT) for pin in IO_GROUP3[1:]: GPIO.setup(pin, GPIO.IN) GPIO.output(IO_GROUP3[0], GPIO.HIGH) GPIO.setup(IO_GROUP4[0], GPIO.OUT) for pin in IO_GROUP4[1:]: GPIO.setup(pin, GPIO.IN) GPIO.output(IO_GROUP4[0], GPIO.LOW) for pin in IO_GROUP1[1:]: if GPIO.input(pin) != GPIO.HIGH: badio.append(pin) for pin in IO_GROUP2[1:]: if GPIO.input(pin) != GPIO.LOW: badio.append(pin) for pin in IO_GROUP3[1:]: if GPIO.input(pin) != GPIO.HIGH: badio.append(pin) for pin in IO_GROUP4[1:]: if GPIO.input(pin) != GPIO.LOW: badio.append(pin) return badio
def get_encoder_turn(): # return -1, 0, or +1 global old_a, old_b result = 0 new_a = GPIO.input(input_A) new_b = GPIO.input(input_B) if new_a != old_a or new_b != old_b : if old_a == 0 and new_a == 1 : result = (old_b * 2 - 1) elif old_b == 0 and new_b == 1 : result = -(old_a * 2 - 1) old_a, old_b = new_a, new_b time.sleep(0.001) return result
def _sonar_once(self, trig, echo): GPIO.output(trig, GPIO.HIGH) time.sleep(0.00015) GPIO.output(trig, GPIO.LOW) while not GPIO.input(echo): pass _st = time.time() while GPIO.input(echo): pass _et = time.time() return (_et - _st) * self.velocityofsound / 2
def distanceMeasurement(TRIG,ECHO): GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) pulseStart = time.time() while GPIO.input(ECHO) == 0: pulseStart = time.time() while GPIO.input(ECHO) == 1: pulseEnd = time.time() pulseDuration = pulseEnd - pulseStart distance = pulseDuration * 17150 distance = round(distance, 2) return distance
def GetAlt(self): GPIO.output(self.TRIG, GPIO.LOW) GPIO.output(self.TRIG, GPIO.HIGH) time.sleep(0.00001) GPIO.output(self.TRIG, GPIO.LOW) while GPIO.input(self.ECHO)== 0: pulse_start = time.time() while GPIO.input(self.ECHO)== 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance= (pulse_duration/2) /29.1; distance = pulse_duration * 17150 distance = distance*0.39370 return distance
def getKey(self): # Set all columns as output low for j in range(len(self.COLUMN)): GPIO.setup(self.COLUMN[j], GPIO.OUT) GPIO.output(self.COLUMN[j], GPIO.LOW) # Set all rows as input for i in range(len(self.ROW)): GPIO.setup(self.ROW[i], GPIO.IN, GPIO.PUD_DOWN) # Scan rows for pushed key/button # A valid key press should set "rowVal" between 0 and 3. rowVal = -1 for i in range(len(self.ROW)): tmpRead = GPIO.input(self.ROW[i]) if tmpRead == 0: rowVal = i # if rowVal is not 0 thru 3 then no button was pressed and we can exit if rowVal <0 or rowVal >3: self.exit() return # Convert columns to input for j in range(len(self.COLUMN)): GPIO.setup(self.COLUMN[j], GPIO.IN, GPIO.PUD_DOWN) # Switch the i-th row found from scan to output GPIO.setup(self.ROW[rowVal], GPIO.OUT) GPIO.output(self.ROW[rowVal], GPIO.HIGH) # Scan columns for still-pushed key/button # A valid key press should set "colVal" between 0 and 2. colVal = -1 for j in range(len(self.COLUMN)): tmpRead = GPIO.input(self.COLUMN[j]) if tmpRead == 1: colVal=j # if colVal is not 0 thru 2 then no button was pressed and we can exit if colVal <0 or colVal >2: self.exit() return # Return the value of the key pressed self.exit() return self.KEYPAD[rowVal][colVal]
def getKey(): KEYPAD = [ [1,2,3], [4,5,6], [7,8,9], ["*",0,"#"] ] ROW = [pin7, pin6, pin5, pin4] COLUMN = [pin3, pin2, pin1] # Set all columns as output low for j in range(0,3): GPIO.setup(COLUMN[j], GPIO.OUT) GPIO.output(COLUMN[j], GPIO.LOW) # Set all rows as input for i in range(0,4): GPIO.setup(ROW[i], GPIO.IN, pull_up_down=GPIO.PUD_UP) # Scan rows for pushed key/button # A valid key press should set "rowVal" between 0 and 3. rowVal = -1 while rowVal == -1: for i in range(0,4): tmpRead = GPIO.input(ROW[i]) if tmpRead == 0: rowVal = i # Convert columns to input for j in range(0,3): GPIO.setup(COLUMN[j], GPIO.IN, pull_up_down=GPIO.PUD_UP) # Switch the i-th row found from scan to output GPIO.setup(ROW[rowVal], GPIO.OUT) GPIO.output(ROW[rowVal], GPIO.HIGH) # Scan columns for still-pushed key/button # A valid key press should set "colVal" between 0 and 2. colVal = -1 while colVal == -1: for j in range(0,3): tmpRead = GPIO.input(COLUMN[j]) if tmpRead == 1: colVal=j return KEYPAD[rowVal][colVal]
def irqWait(self): # A race condition may occur here. # TODO: Should set a timeout if GPIO.input(self.irq_pin) == 0: return GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING)
def spi_transfer(number): print "Writing " + number + "..." GPIO.output(slaveSelect, GPIO.LOW) num = int(number) dataIn = 0 for i in xrange(7, -1, -1): level = (num & (1 << i)) >> i print "Bit " + str(i) + ": " + str(level) if (level == 1): GPIO.output(MOSI, GPIO.HIGH) else: GPIO.output(MOSI, GPIO.LOW) GPIO.output(spiClock, GPIO.HIGH) if GPIO.input(MISO): dataIn |= (1 << i) else: dataIn &= (255 ^ (1 << i)) GPIO.output(spiClock, GPIO.LOW) # time.sleep(pause) # print str(count) + " messages" GPIO.output(slaveSelect, GPIO.HIGH) print "Wrote " + number + "!" return dataIn