Beispiel #1
0
 def control(self):
     if GPIO.digitalRead(pinReset) == 0:
         global STEP
         global coins
         STEP = 0
         coins = 0
         initCommunicationPins()
         pygame.mixer.music.stop()
     #    server.shutdown()
     #    print("about to exit")
     #    os.system("sleep 10 && sudo python /home/pi/DEV/pivaders/pivaders/pivaders.py &")
     #    print("reboot sequence executed! good bye")
     #    sys.exit(0)
     self.keys = pygame.key.get_pressed()
     if self.keys[pygame.K_LEFT] or GPIO.digitalRead(pinLeft) == 0:
         self.animate_left = True
         self.animate_right = False
         if STEP != 9:
             GameState.vector = -1
         else:
             GameState.vector = -2
     elif self.keys[pygame.K_RIGHT] or GPIO.digitalRead(pinRight) == 0:
         self.animate_right = True
         self.animate_left = False
         if STEP != 9:
             GameState.vector = 1
         else:
             GameState.vector = 2
     else:
         GameState.vector = 0
         self.animate_right = False
         self.animate_left = False
     if (STEP == 5 or STEP == 9) and GPIO.digitalRead(pinShoot) == 0:
         GameState.shoot_bullet = True
Beispiel #2
0
    def cheat_code_input_screen(self):
        digit_values = [0, 0, 0, 0]
        digit_solution = [1, 3, 8, 0]
        selected_digit = 0
        code_entered = False

        while code_entered == False:
            if GPIO.digitalRead(pinRight) == 0 and selected_digit < 4:
                selected_digit += 1
            elif GPIO.digitalRead(pinLeft) == 0 and selected_digit > 0:
                selected_digit += -1
            elif selected_digit == 4:
                if GPIO.digitalRead(pinShoot) == 0:
                    code_entered = True
            elif GPIO.digitalRead(
                    pinUp) == 0 and digit_values[selected_digit] < 9:
                digit_values[selected_digit] += 1
            elif GPIO.digitalRead(
                    pinDown) == 0 and digit_values[selected_digit] > 0:
                digit_values[selected_digit] += -1
            self.draw_joystick_digit_selector(digit_values, selected_digit)
            pygame.time.delay(100)

        if digit_values == digit_solution:
            for i in range(0, 5):
                # delete bottom part of the screen
                pygame.draw.rect(self.screen, BLACK,
                                 pygame.Rect(0, 470, 2000, 2000))
                pygame.display.flip()
                pygame.time.delay(200)

                font = pygame.font.Font(
                    '/home/pi/DEV/pivaders/pivaders/data/Orbitracer.ttf', 60)
                text = font.render("GOD MODE ACTIVATED!", 1, YELLOW)
                self.screen.blit(text, (text.get_rect(
                    centerx=self.screen.get_width() / 2).x, 500))
                pygame.display.flip()
                pygame.time.delay(600)
            global STEP
            STEP = 8
            print("step=" + str(STEP))

        else:
            for i in range(0, 2):
                # delete central part of the screen
                pygame.draw.rect(self.screen, BLACK,
                                 pygame.Rect(0, 470, 2000, 2000))
                pygame.display.flip()
                pygame.time.delay(200)

                font = pygame.font.Font(
                    '/home/pi/DEV/pivaders/pivaders/data/Orbitracer.ttf', 48)
                text = font.render("INVALID CODE", 1, YELLOW)
                self.screen.blit(text, (text.get_rect(
                    centerx=self.screen.get_width() / 2).x, 500))
                pygame.display.flip()
                pygame.time.delay(1000)
            global STEP
            STEP = 6
            print("step=" + str(STEP))
Beispiel #3
0
def distance_8():  # LEFT
    TRIG = 21  #Associate pin 23 to TRIG
    ECHO = 22  #Associate pin 24 to ECHO

    GPIO.pinMode(TRIG, 1)  #Set pin as GPIO out
    GPIO.pinMode(ECHO, 0)  #Set pin as GPIO in

    while True:
        GPIO.digitalWrite(TRIG, 0)  #Set TRIG as LOW
        time.sleep(0.2)

        GPIO.digitalWrite(TRIG, 1)  #Set TRIG as HIGH
        time.sleep(0.00001)  #Delay of 0.00001 seconds
        GPIO.digitalWrite(TRIG, 0)  #Set TRIG as LOW

        while GPIO.digitalRead(ECHO) == 0:  #Check whether the ECHO is LOW
            pulse_start = time.time()  #Saves the last known time of LOW pulse

        while GPIO.digitalRead(ECHO) == 1:  #Check whether the ECHO is HIGH
            pulse_end = time.time()  #Saves the last known time of HIGH pulse

        pulse_duration = pulse_end - pulse_start  #Get pulse duration to a variable

        distance = pulse_duration * 17150  #Multiply pulse duration by 17150 to get distance
        distance = round(distance, 2)  #Round to two decimal points
        distance = distance - 1

        if distance > 2 and distance < 400:  #Check whether the distance is within range
            #print ("Distance:",distance - 0.5,"cm")  #Print distance with 0.5 cm calibration
            return distance
def get_data(channel):
    tl = []
    gpio.digitalWrite(channel, gpio.HIGH)  # 输出高电平
    gpio.delay(1)
    ###发开始指令,要求DHT11传输数据
    gpio.digitalWrite(channel, gpio.LOW)  # 拉低25ms开始指令
    gpio.delay(25)
    gpio.digitalWrite(channel, gpio.HIGH)  # 输出高电平,开始指令结束
    gpio.pinMode(channel, gpio.INPUT)  # 设针脚为输入状态
    ###开始指令发送完毕,把管脚设置为高电平,并等待DHT11拉低管脚。传输数据
    while (gpio.digitalRead(channel) == gpio.HIGH):
        pass  # 如果管脚一直是1,则一直等待。
    ###若被拉低,说明传输开始,应答信号+40位数据+结束标志共42位
    ###下边共循环45次,故意多循环几次看结果。
    ###开始接受数据,50us低 + 26-28us高=0,50us低 + 70us高 = 1
    for i in range(45):  # 测试每个数据周期的时间(包括40bit数据加一个发送开始标志
        tc = gpio.micros()  # 记下当前us数(从初始化开始算起,必要时重新初始化)
        '''
        一个数据周期,包括一个低电平,一个高电平,从DHT11第一次拉低信号线开始
        到DHT11发送最后一个50us的低电平结束(然后被拉高,一直维持高电平,所以
        最后的完成标志是一直为高,超过500us)
        '''
        while (gpio.digitalRead(channel) == gpio.LOW):
            pass  # 一位数据由一个低电平
        while (gpio.digitalRead(channel) == gpio.HIGH):  # 加一个高电平组成
            if gpio.micros() - tc > 500:  # 如果超过500us就结束了本次循环,传输结束后
                break  # 会被上拉电阻拉成高电平,防止进入死循环
        tl.append(gpio.micros() - tc)  # 记录每个周期时间的us数,存到tl这个列表
    print(tl)
    return tl
Beispiel #5
0
def readData(pin):
    hum = 0
    temp = 0
    crc = 0
    GPIO.pinMode(pin, 1)
    GPIO.digitalWrite(pin, 1)
    GPIO.digitalWrite(pin, 0)
    GPIO.delay(20)
    GPIO.digitalWrite(pin, 1)
    GPIO.pinMode(pin, 0)
    GPIO.delayMicroseconds(40)
    if GPIO.digitalRead(pin) == 0:
        untilHigh(pin)
        for i in range(16):
            hum <<= 1
            untilLow(pin)
            untilHigh(pin)
            GPIO.delayMicroseconds(28)
            hum += GPIO.digitalRead(pin)
        for i in range(16):
            temp <<= 1
            untilLow(pin)
            untilHigh(pin)
            GPIO.delayMicroseconds(28)
            temp += GPIO.digitalRead(pin)
        for i in range(8):
            crc <<= 1
            untilLow(pin)
            untilHigh(pin)
            GPIO.delayMicroseconds(28)
            crc += GPIO.digitalRead(pin)
        return [True, hum, temp, crc]
    else:
        return [False, hum, temp, crc]
Beispiel #6
0
def get_white_sw():
    if(wiringpi2.digitalRead(0) == 0):
        wiringpi2.delay(50)
        if(wiringpi2.digitalRead(0) == 1):
            return True
        elif(wiringpi2.digitalRead(0) == 0):
            return False
Beispiel #7
0
def main():
    global clip, stop, pendingStop, mode, clipShift, nextPhase, stepTime
    initGPIO()
    print "Get A Grip - sequencer"
    clip = 0
    clipShift = 0
    stop = False
    mode = False
    pendingStop = False
    while True:
        if io.digitalRead(modePush) == 0 and io.digitalRead(startPush) == 0:
            terminate()
        if not stop:
            stepTime = 0.004 + (io.analogRead(71) / 2000.0)
            nextStep = time.time() + stepTime
            setMux(clip)
            #print clip, clipShift
            while time.time() <= nextStep:
                readStart()
                readMode()
                if mode and time.time() > nextPhase:
                    echoSequence()
            readAD(clip)
            incrementClip()
        else:
            readStart()
Beispiel #8
0
def get_black_sw():
    if(wiringpi2.digitalRead(2) == 0):
        wiringpi2.delay(50)
        if(wiringpi2.digitalRead(2) == 1):
            return True
        elif(wiringpi2.digitalRead(2) == 0):
            return False
Beispiel #9
0
def measure():

	wiringpi2.digitalWrite(TRIG, 1)
	time.sleep(0.00001)
	wiringpi2.digitalWrite(TRIG, 0)

	pulse_start = time.time()
	while wiringpi2.digitalRead(ECHO)==0:
		pulse_start = time.time()
	
	# Once a signal is received, the value changes from low (0) to high (1),
	# and the signal will remain high for the duration of the echo pulse.
	# We therefore also need the last high timestamp for ECHO (pulse_end).

	pulse_end = time.time()      
	while wiringpi2.digitalRead(ECHO) == 1:
		pulse_end = time.time()      
	
	# We can now calculate the difference between the two recorded 
	# timestamps, and hence the duration of pulse (pulse_duration).

	pulse_duration = pulse_end - pulse_start
	
	distance = pulse_duration * 17150

	return distance
Beispiel #10
0
def readData(pin):
    hum = 0
    temp = 0
    crc = 0
    GPIO.pinMode(pin, 1)
    GPIO.digitalWrite(pin, 1)
    GPIO.digitalWrite(pin, 0)
    GPIO.delay(20)
    GPIO.digitalWrite(pin, 1)
    GPIO.pinMode(pin, 0)
    GPIO.delayMicroseconds(40)
    if GPIO.digitalRead(pin) == 0:
        untilHigh(pin)
        for i in range(16):
            hum <<= 1
            untilLow(pin)
            untilHigh(pin)
            GPIO.delayMicroseconds(28)
            hum += GPIO.digitalRead(pin)
        for i in range(16):
            temp <<= 1
            untilLow(pin)
            untilHigh(pin)
            GPIO.delayMicroseconds(28)
            temp += GPIO.digitalRead(pin)
        for i in range(8):
            crc <<= 1
            untilLow(pin)
            untilHigh(pin)
            GPIO.delayMicroseconds(28)
            crc += GPIO.digitalRead(pin)
        return [True, hum, temp, crc]
    else:
        return [False, hum, temp, crc]
Beispiel #11
0
  def set(self,newState):
    
    newState = int(newState)

    # FIXME need to catch error
    print "Switching relay " + `self.relayA` + " to " + `newState`

    wiringpi.pinMode(self.relayA,self.OUTPUT_MODE)
    
    initialState = wiringpi.digitalRead(self.relayA)
    wiringpi.digitalWrite(self.relayA, newState)
    currentState = wiringpi.digitalRead(self.relayA)
    
    result = None
    if(initialState == currentState):
    	result = "Target state was already set. No action taken"
    else:
    	result = "Switched"
    
    errors = None
    
    return {
        "controller": self.name,
        "timestamp": datetime.datetime.now().isoformat(' '),
        "result": result,
        "errors": errors,
    }
Beispiel #12
0
def gpio_status(pc):
    power_status = wiringpi.digitalRead(settings.PCS[pc]['gpio']['power'])
    mains_power = wiringpi.digitalRead(settings.PCS[pc]['gpio']['mains_power'])
    power_led = wiringpi.digitalRead(settings.PCS[pc]['gpio']['power_led'])
    if settings.PCS[pc]['mains_normally_closed']:
        mains_power = mains_power ^ 1
    return bool(power_status), bool(mains_power), bool(power_led)
Beispiel #13
0
    def get_distance(self, sensor):
        #wiringpi.digitalWrite(30,HIGH)
        wiringpi.digitalWrite(sensor.echo, LOW)
        wiringpi.delay(1000)
        wiringpi.digitalWrite(sensor.trigger, HIGH)
        wiringpi.delay(1)
        wiringpi.digitalWrite(sensor.trigger, LOW)
        #start = time.time()
	print "Trying to get distance of sensor " , sensor.position, "Trig: ", sensor.trigger, " Echo:", sensor.echo
	status = LOW
	while(wiringpi.digitalRead(sensor.echo) == LOW):
		status = LOW
	start = time.time()
	while(wiringpi.digitalRead(sensor.echo) == HIGH):
		status = LOW
	end = time.time()	

#	while status == LOW:
#	    feedback = wiringpi.digitalRead(sensor.echo)
#	    if(feedback == HIGH):
#		while(feedback == HIGH):
#		    status = LOW
#		end = time.time()
#		print("Time Elapsed: ", end-start)
#		status = HIGH
#	    if((time.time() - start) > 1):
#		end = time.time()
#		status = HIGH

        # Below divide by 340.29 for air distance, or divide by 1484 for water distance
        return (end - start)*(340.29/2)
Beispiel #14
0
def writeMorseCode():
    car = ''
    while 1:
        myInput = wpi.digitalRead(PIN)
        debut = datetime.now()

        if (myInput):
            while myInput == 1:
                myInput = wpi.digitalRead(PIN)

            temps = datetime.now() - debut

            if (temps.seconds < 0.5):
                car = car + '.'
            else:
                car = car + '-'

        else:
            while myInput == 0:
                myInput = wpi.digitalRead(PIN)

                temps = datetime.now() - debut

                if (temps.seconds > 1 and car != ''):
                    return fromMorse(car)
Beispiel #15
0
def main():
   global clip, stop, pendingStop, mode
   initGPIO()
   print"Statues hardware test"
   print" Ctrl C to quit"
   leftMovement = False
   rightMovement = False
   while True:

      if io.digitalRead(pirPins[0]) == 1 and not(leftMovement):
         print"left movement detected"
         io.digitalWrite(ledPins[0],0) # turn Red on
         io.digitalWrite(ledPins[1],1) # turn Green off
         moveSound[0].play(0)
         leftMovement = True
      elif  io.digitalRead(pirPins[0]) == 0 and leftMovement:
         io.digitalWrite(ledPins[0],1) # turn Red off
         io.digitalWrite(ledPins[1],0) # turn Green on
         leftMovement = False
         
      if io.digitalRead(pirPins[1]) == 1 and not(rightMovement):
         print"right movement detected"
         io.digitalWrite(ledPins[2],0) # turn Red on
         io.digitalWrite(ledPins[3],1) # turn Green off
         moveSound[4].play(0)
         rightMovement = True
      elif io.digitalRead(pirPins[1]) == 0 and rightMovement:
         io.digitalWrite(ledPins[2],1) # turn Red off
         io.digitalWrite(ledPins[3],0) # turn Green on
         rightMovement = False
Beispiel #16
0
def d7():
    pulse_start = 0
    pulse_end = 0

    TRIG = 6
    ECHO = 11

    GPIO.pinMode(TRIG, 1)
    GPIO.pinMode(ECHO, 0)

    GPIO.digitalWrite(TRIG, 0)
    time.sleep(0.1)

    GPIO.digitalWrite(TRIG, 1)
    time.sleep(0.0001)
    GPIO.digitalWrite(TRIG, 0)

    while GPIO.digitalRead(ECHO) == 0:
        pulse_start = time.time()

    while GPIO.digitalRead(ECHO) == 1:
        pulse_end = time.time()

    pulse_duration = pulse_end - pulse_start

    distance = pulse_duration * 17150
    distance = round(distance, 3)

    return distance
def checkPins():
	global pinStates, holeStates, buffer, escapeFlag
	while True:
		if wiringpi2.digitalRead(shutdownPin) == 0:
			pass
			#sayGoodbyeAndExit(shutdown=True)
		
		for (i, pin) in enumerate(inputPins):
			pinStates[i] = wiringpi2.digitalRead(pin)
			holeStates[i] = holeStates[i] or not pinStates[i]

		if sum(pinStates) == 5:
			if sum(holeStates) > 0 and sum(holeStates) < 5:
				# calculate current input
				value = 0
				for place, digit in enumerate(holeStates):
					value += pow(2, len(holeStates)-place-1) * digit
					
				# decode it and append it to the buffer
				if escapeFlag:
					buffer += str(value)
					escapeFlag = False
				else:
					if value in bonusChars:
						buffer += bonusChars[value]
					elif value == 30:
						escapeFlag = True
					else:
						buffer += chr(value + ord('a') - 1)
					
				# reset hole buffer
			holeStates = [ 0 ] * len(inputPins)
			time.sleep(0.01)
Beispiel #18
0
def getSwitch():
    resetSwitch()
    binary = str(1-wpi.digitalRead(switchPin[0])) +\
             str(1-wpi.digitalRead(switchPin[1])) +\
             str(1-wpi.digitalRead(switchPin[2]))
    switch = int(binary, 2)
#    print switch
    return float(switch)
def main():
    initGPIO()
    print "Amaze sensor switch test"
    while True:
        for i in range(0, 4):
            print io.digitalRead(pinList[i]), " ",
        print " "
        time.sleep(1)
Beispiel #20
0
def checkSensors():
    global leftMovement, rightMovement
    if io.digitalRead(pirPins[0]) == 1 and not (leftMovement):
        leftMovement = True
    elif io.digitalRead(pirPins[0]) == 0 and leftMovement:
        leftMovement = False
    if io.digitalRead(pirPins[1]) == 1 and not (rightMovement):
        rightMovement = True
    elif io.digitalRead(pirPins[1]) == 0 and rightMovement:
        rightMovement = False
Beispiel #21
0
def checkForDistance():
    if io.digitalRead(sensorPins[0]) == 1:
        print "nothing in range"
    else:
        close = 0
        for n in range(1, 4):
            if io.digitalRead(sensorPins[n]) == 0:
                close = n
        print " distance sensor ", n, "triggered"
        print "closer than", distance[n]
Beispiel #22
0
def ushiro(radian):
    com.dSPIN_Move(hd.REV, int(radian))

    while (wp.digitalRead(hd.dSPIN_BUSYN) == wp.GPIO.LOW):
        pass
    com.dSPIN_SoftStop()

    while (wp.digitalRead(hd.dSPIN_BUSYN) == wp.GPIO.LOW):
        pass
    wp.delay(500)
Beispiel #23
0
        def updateData(self):
#                print "i value"
                for i in range(len(self.words)):                        
                        if wiringPi.digitalRead(ACK) != 0:
                                wiringPi.digitalWrite(ACK, 0)
                        wiringPi.digitalWrite(CLOCK, 1)

                        self.time1 = time.time()-self.time0
                        while self.time1-self.time2 < CLKSPD:
                                self.time1 = time.time()-self.time0
#                       print round((self.time1-self.time2)*1000,2)

                        wiringPi.digitalWrite(CLOCK, 0)

                        for j in range(len(self.bits)):
                                self.bits[j] = wiringPi.digitalRead(PINS[j])
			"""  
			#dummy data
                        if i == 0:
                                self.bits = [1,1,1,1,1,1,1,1,1,1]
                        elif i == 1:
                                self.bits = [0,0,1,1,0,0,1,0,0,0]
                        elif i == 2:
                                self.bits = [0,0,0,1,1,0,0,1,0,0]
                        elif i == 3:
                                self.bits = [0,1,1,1,1,1,0,1,0,0]
                        elif i == 4:
                                self.bits = [0,0,0,0,1,1,0,0,1,0]
                        elif i == 5:
                                self.bits = [0,0,0,0,0,1,0,1,0,1]
                        elif i == 6:
                                self.bits = [0,0,1,1,0,0,1,0,0,0]
                        elif i == 7:
                                self.bits = [0,0,0,1,1,0,0,1,0,0]
                        elif i == 8:
                                self.bits = [1,1,1,1,1,1,1,1,1,1] # [1,1,1,0,1,0,0,1,1,0]
                        elif i == 9:
                                self.bits = [0,1,0,0,1,1,1,0,0,1]
 			"""
 #                       print i, self.bits
                        
			if (i != 0 and self.bits == [1 for k in range(len(self.bits))]) or (i == 0 and self.bits != [1 for k in range(len(self.bits))]) or i == max(range(len(self.words))):
				wiringPi.digitalWrite(ACK, 1)
			else:
				self.words[i] = list(self.bits)
#			print i, self.words[i]

                        self.time2 = time.time()-self.time0                        
                        while self.time2-self.time1 < CLKSPD:
                                self.time2 = time.time()-self.time0
#                       print round((self.time2-self.time1)*1000,2)

			if (i != 0 and self.bits == [1 for k in range(len(self.bits))]) or (i == 0 and self.bits != [1 for k in range(len(self.bits))]):
				break                        
def main():   
   initGPIO()

   while True:
     if io.digitalRead(shutDownPin) == 0 :
        #os.system("sudo shutdown -h now")
        print"shutdown",
        print io.digitalRead(shutDownPin)
     checkForDistance()
     advancePattern()
     time.sleep(patternTimeSteps[pattern])
Beispiel #25
0
def checkButtons():

    sw1 = not wiringpi.digitalRead(switch_1)  # Read switch
    if sw1: print 'switch 1'
    sw2 = not wiringpi.digitalRead(switch_2)  # Read switch
    if sw2: print 'switch 2'
    sw3 = not wiringpi.digitalRead(switch_3)  # Read switch
    if sw3: print 'switch 3'
    sw4 = not wiringpi.digitalRead(switch_4)  # Read switch
    if sw4: print 'switch 4'

    return False
Beispiel #26
0
def checkButtons():

    sw1 = not wiringpi.digitalRead(switch_1) # Read switch
    if sw1: print 'switch 1'
    sw2 = not wiringpi.digitalRead(switch_2) # Read switch
    if sw2: print 'switch 2'
    sw3 = not wiringpi.digitalRead(switch_3) # Read switch
    if sw3: print 'switch 3'
    sw4 = not wiringpi.digitalRead(switch_4) # Read switch
    if sw4: print 'switch 4'

    return False
Beispiel #27
0
def scanButtons():
  button = 0x0
  for x in range(0,8):
    if not wiringpi.digitalRead(pin_base+x):
      button = (button | (1 << x))
  LSB = button
  button = 0x0
  for x in range(8,16):
    if not wiringpi.digitalRead(pin_base+x):
      button = (button | (1 << (x-8)))
  MSB = button
  return LSB,MSB
Beispiel #28
0
def checkBtn(idx, size):
    global run
    if wiringpi2.digitalRead(AF_LEFT):
        idx -= 1
        printLCD()
    elif wiringpi2.digitalRead(AF_RIGHT):
        idx += 1
        printLCD()
    if wiringpi2.digitalRead(AF_SELECT):
        printLCD("Exit Display")
        run = False
    return idx % size
	def Poll(self):
		iters = 0
		while not wiringpi.digitalRead(addrPins[self.addr-1]):
			iters += 1
			if iters > 10000: 
				self.isOn = False
				return

		if not wiringpi.digitalRead(dataPins[self.data-1]):	# data is low = segment is lit
			self.isOn = True
		else:
			self.isOn = False
Beispiel #30
0
 def measure_bit_changes(self, maxtime=1.0):
     """Counts the bit flips corisponding to half sycle of the
     water wheel"""
     now = wp.digitalRead(0)
     counter = 0
     t0 = time.time()
     while maxtime > time.time() - t0:
         new = wp.digitalRead(0)
         if now != new:
             counter += 1
             now = new
         time.sleep(0.0001)
     freq = 0.5 * counter / (time.time() - t0)
     return freq
Beispiel #31
0
def lcd_check_buttons(delay):
	lbutton = 0
	rbutton = 0

	wiringpi2.delay(delay)
	if wiringpi2.digitalRead(5) == 0: # Left button
		print("left button pressed")
		lbutton = 1

	if wiringpi2.digitalRead(6) == 0: # Right button
		print("right button pressed")
		rbutton = 1

	return (lbutton, rbutton)
Beispiel #32
0
 def measure_bit_changes(self, maxtime=1.0):
     """Counts the bit flips corisponding to half sycle of the
     water wheel"""
     now = wp.digitalRead(0)
     counter = 0
     t0 = time.time()
     while maxtime > time.time()-t0:
         new = wp.digitalRead(0)
         if now != new:
             counter += 1
             now = new
         time.sleep(0.0001)
     freq = 0.5 * counter / (time.time() - t0)
     return freq
Beispiel #33
0
    def RCTime(self,pin=11,wiring=True,short=False):
        duration=0
        #not sure if the GPIO version of this translation works,
        #so keep using Wiringpi version
        if wiring==True:
            #initQTI()
            #make pin output
            wp.pinMode(pin,1)
            #set pin to high to discharge capacitor
            wp.digitalWrite(pin,1)
            #wait 1 ms
            time.sleep(0.001)
            #make pin Input
            wp.pinMode(pin,0)
            #turn off internal pullups
            #wp.digitalWrite(pin,0)
            wp.pullUpDnControl(pin,1)
	    #print "here"
            if short == True:
                while wp.digitalRead(pin)==1 and duration < self.rightTail:
                    #wait for the pin to go Low
                    #print pin,    wp.digitalRead(pin)
                    #print 'not yet'
                    duration+=1
            else:
                while wp.digitalRead(pin)==1 and duration <self.cap:
		#           	while wp.digitalRead(pin)==1:
			#print "here"
			duration+=1
            #print duration
	    #wp.pinMode(pin,1)
            #wp.digitalWrite(pin,1)
        else:
            GPIO.setup(pin,GPIO.OUT)
            #set pin to high to discharge capacitor

            GPIO.output(pin,GPIO.LOW)
            #wait 1 ms
            time.sleep(0.1)
            #make pin Input
            GPIO.setup(pin,GPIO.IN)
            #GPIO.setup(pin,GPIO.IN,GPIO.PUD_DOWN)
            #turn off internal pullups
            while GPIO.input(pin)== GPIO.LOW:
                #wait for the pin to go Low
                #print GPIO.input(sensorIn)
                duration+=1
	#print duration, pin
        return duration
Beispiel #34
0
    def WaitDRDY(self):
        """
        Delays until DRDY line goes low, allowing for automatic calibration
        """
        start = time.time()
        elapsed = time.time() - start

        # Waits for DRDY to go to zero or TIMEOUT seconds to pass
        drdy_level = wp.digitalRead(self.DRDY_PIN)
        while (drdy_level == wp.HIGH) and (elapsed < self.DRDY_TIMEOUT):
            elapsed = time.time() - start
            drdy_level = wp.digitalRead(self.DRDY_PIN)

        if elapsed >= self.DRDY_TIMEOUT:
            print("WaitDRDY() Timeout\r\n")
Beispiel #35
0
def main_loop():
  global current
  display_main_screen()
  while 1:
    key = wiringpi.digitalRead(BUTTON_OK)
    fkey = wiringpi.digitalRead(BUTTON_FKEY)
    if key == 1:
      #photo.take_sync_photo(comm_server, lcd)
      actions.run_command(current, comm_server, lcd)
      display_main_screen()
    if fkey == 1:
      print('fkey')
      current=(current+1)%actions.get_count()
      display_main_screen()
    time.sleep(0.2)
def pulse():
  wiringpi2.digitalWrite(TRIGGER,ON)
  time.sleep(PULSE)
  wiringpi2.digitalWrite(TRIGGER,OFF)
  starttime=time.time()
  stop=starttime
  start=starttime
  while wiringpi2.digitalRead(ECHO)==0 and start<starttime+2:
    start=time.time()
  while wiringpi2.digitalRead(ECHO)==1 and stop<starttime+2:
    stop=time.time()
  delta=stop-start
  print("Start:%f Stop:%f Delta:%f"%(start,stop,delta))
  distance=delta*SPEEDOFSOUND
  return distance/2.0
Beispiel #37
0
    def get(self):
        response = {}

        # Make sure sensor pin is set to input mode
        try:
            wpi.pinMode(config['SENSOR_PIN_NUM'],0)
        except:
            response['status'] = "error"
            response['errorCode'] = "GPIO pin input mode error."
            response['message'] = "Cannot {} garage door.".format(config['MODE'])
            resp = jsonify(response)
            resp.status_code = 500
            return resp

        try:
            if wpi.digitalRead(config['SENSOR_PIN_NUM']):
                response['doorStatus'] = 'open'
            else:
                response['doorStatus'] = 'closed'
        except:
            response['status'] = "error"
            response['errorCode'] = "GPIO pin read error."
            response['message'] = "Cannot determine garage door status."
            resp = jsonify(response)
            resp.status_code = 500
            return resp


        response['status'] = "success"
        response['errorCode'] = None
        response['message'] = "Garage door is {}.".format(response['doorStatus'])
        resp = jsonify(response)
        resp.status_code = 200
        return resp
Beispiel #38
0
def action(changePin, action):
   # Convert the pin from the URL into an integer:
   changePin = int(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 low:
      wiringpi.digitalWrite(changePin, 0)
      # Save the status message to be passed into the template:
      #message = "Turned " + deviceName + "on."
   if action == "off":
      wiringpi.digitalWrite(changePin, 1)
      #message = "Turned " + deviceName + " off."
   if action == "toggle":
      # Read the pin and set it to whatever it isn't (that is, toggle it):
      wiringpi.digitalWrite(changePin, not wiringpi.digitalWrite(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'] = wiringpi.digitalRead(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 dSPIN_Xfer(data):
    wp.digitalWrite(hd.dSPIN_CS, wp.GPIO.LOW);

    for i in range(8):
        wp.digitalWrite(hd.dSPIN_CLK, wp.GPIO.LOW);

        if(data & 0x80):
            wp.digitalWrite(hd.dSPIN_MOSI, wp.GPIO.HIGH);
        else:
            wp.digitalWrite(hd.dSPIN_MOSI, wp.GPIO.LOW);
        wp.delayMicroseconds( hd.dSPIN_SPI_CLOCK_DELAY);

        data <<= 1;

        if(wp.digitalRead(hd.dSPIN_MISO)):
            data |= 1;

        wp.digitalWrite(hd.dSPIN_CLK, wp.GPIO.HIGH);

        wp.delayMicroseconds( hd.dSPIN_SPI_CLOCK_DELAY);

    wp.digitalWrite(hd.dSPIN_CS, wp.GPIO.HIGH);
    wp.delayMicroseconds( hd.dSPIN_SPI_CLOCK_DELAY );

    return data
Beispiel #40
0
    def get_status(self, port_name):
        pin = self.PINS[port_name]
        if pin is None:
            self.log.error('Provided port "%s" not found.', port_name)
            return -1

        return wiringpi2.digitalRead(pin)
Beispiel #41
0
    def get_status(self, port_name):
        pin = self.PINS[port_name]
        if pin is None:
            self.log.error('Provided port "%s" not found.', port_name)
            return -1

        return wiringpi2.digitalRead(pin)
Beispiel #42
0
 def read(self, toread):
     if toread == 'switch':
         if (tm.time() - self.timeread[0]) > 0.01:
             self.timeread[0] = tm.time()
             self.switch = int(wpi.digitalRead(self.pin_b))
         return self.switch
     if toread == 'pushbutton':
         if (tm.time() - self.timeread[1]) > 0.01:
             self.timeread[1] = tm.time()
             self.pushbutton = int(wpi.digitalRead(self.pin_p))
         return self.pushbutton
     if toread == 'valve':
         if (tm.time() - self.timeread[2]) > 0.01:
             self.timeread[2] = tm.time()
             self.valve = int(wpi.digitalRead(self.pin_r))
         return self.valve
Beispiel #43
0
def test():
    pin = 0
    gpio.wiringPiSetup()  #初始化
    gpio.wiringPiSetupSys()  #初始化
    gpio.pinMode(pin, GPIO.OUTPUT) # 把pin25设置为输出模式
    gpio.digitalWrite(pin, GPIO.HIGH) #pin25输出为高电平
    print(gpio.digitalRead(pin)) #打印pin25的状态
Beispiel #44
0
def readadc(adcnum, clockpin, mosipin, misopin, cspin, count):
	if((adcnum > 7) or (adcnum < 0)):
		return -1
	
	wp.digitalWrite(cspin, 1)
	wp.digitalWrite(clockpin, 0) 	# start clock low
	wp.digitalWrite(cspin, 0)		# bring CS low
	
	commandout = adcnum
	commandout |= 0x18	# start bit + single-ended bit
	commandout <<= 3	# we only need to send 5 bits here
	
	for i in range(5):
		if(commandout & 0x80):
			wp.digitalWrite(mosipin, 1)
		else:
			wp.digitalWrite(mosipin, 0)
			
		commandout <<= 1
		wp.digitalWrite(clockpin, 1)
		wp.digitalWrite(clockpin, 0)
	
	adcout = 0
	# read in one empty bit, one null bit and 10 adc bits
	for i in range (12):
		wp.digitalWrite(clockpin, 1)
		wp.digitalWrite(clockpin, 0)
		adcout <<= 1
		if(wp.digitalRead(misopin)):
			adcout |= 0x1
			
	wp.digitalWrite(cspin, 1)
	
	adcout /= 2
	values[count] = adcout
Beispiel #45
0
def getSensor():
    global move
    sensor = 0
    checkForEvent()
    for pin in range(0, 4):
        sensor = (sensor << 1) | (io.digitalRead(tiltPins[pin]))
    return sensor
def button_raw_press():
    # simple debounce with busy-waiting
    time.sleep(DEBOUNCE_MS // 1000)
    if not wiringpi2.digitalRead(BUTTON_PIN):
        global count
        count += 1
        print("BUTTON PRESS: %d" % (count))
Beispiel #47
0
def checkForDistance():  # select pattern based on distance
    global pattern, patternStep
    if io.digitalRead(sensorPins[0]) == 1:
        if pattern != 0:  # if something showing
            wipe()
            pixels.show()
            pattern = 0  # stop any display
            patternStep = 0  # put to start of a pattern
    else:
        close = 0
        for n in range(1, 4):
            if io.digitalRead(sensorPins[n]) == 0:
                close = n
        if pattern != close + 1:  # has pattern changed
            pattern = close + 1
            patternStep = 0  # stage in pattern
Beispiel #48
0
    def handle(self):
        received_data = self.request[0].strip()
        data = "test"
        socket = self.request[1]

        if received_data == "read":
            print "read_all"
            data = ''
            for i in range(0, 20):
                data += str(wp.digitalRead(i))

        for i in range(0, 9):
            if (received_data[0:11] == "set_state_" + str(i + 1)):
                val = received_data[11:].strip()
                if val == '0':
                    wp.digitalWrite(i, 0)
                    data = "ok"
                if val == '1':
                    wp.digitalWrite(i, 1)
                    data = "ok"

        for i in range(9, 20):
            if (received_data[0:12] == "set_state_" + str(i + 1)):
                val = received_data[12:].strip()
                if val == '0':
                    wp.digitalWrite(i, 0)
                    data = "ok"
                if val == '1':
                    wp.digitalWrite(i, 1)
                    data = "ok"

        socket.sendto(data, self.client_address)
	def Update(self):
		data = wiringpi.digitalRead(self.pin)
		if data:
#			print self.pin

			if not self.isMidPulse:
				self.isMidPulse = True
				self.lastPulseStart = wiringpi.micros()

		if not data:
			if self.isMidPulse:
				self.isMidPulse = False
				pulseEnd = wiringpi.micros()

				thisPulseLen = pulseEnd - self.lastPulseStart
				self.pulses.append(thisPulseLen)
				numElements = len(self.pulses)
				if numElements > numSamplesForAvg: self.pulses.pop(0) # remove oldest sample if have enough
				averagedPulseLen = 0
				for el in self.pulses: averagedPulseLen += el
				averagedPulseLen /= numElements

				self.currentAvgLen = averagedPulseLen

				if self.isPrintData and numElements >= numSamplesForAvg:
					currTime = time.time()
					if currTime - self.lastOutput > outputPeriod or self.lastOutput == 0.0:
						self.lastOutput = time.time()
						procComms.PrintData(self.name + ', ' + str(self.InPercent()))
Beispiel #50
0
def getValue():
    wiringpi.digitalWrite(TRIG, ON)
    sleep(0.00001)
    wiringpi.digitalWrite(TRIG, OFF)

    while (not (wiringpi.digitalRead(ECHO))):
        pass

    start = time()

    while (wiringpi.digitalRead(ECHO)):
        pass

    stop = time()

    return((stop-start)*17000)
Beispiel #51
0
def updateSensors():  # see if the sliders have changed
    for i in range(0, 4):
        sensor = bool(io.digitalRead(pinList[i]))
        if sliderState[i] != sensor:
            toggleSlider(i, True)
            time.sleep(2.0)
    return
Beispiel #52
0
  def run(self):
    while self.__running:
      state = wiringpi2.digitalRead(self.pinNumber)
      if state != self.__previousState:
        self.onStateChange(state)

      self.__previousState = state
      time.sleep(self.__RESOLUTION / 1000.0)
Beispiel #53
0
def ledsBlink():
    for times in range(20):
        for bitPos in range(3):
            wpi.digitalWrite(ledPin[bitPos], 1-wpi.digitalRead(switchPin[bitPos]))
        time.sleep(0.25)
        resetLeds()
        resetSwitch()
        time.sleep(0.25)
Beispiel #54
0
 def read(self, pin):
   """Read the status of the specified pin."""
   if pin in self._pins:
     hwstatus = wiringpi2.digitalRead(pin)
     if hwstatus == LEVEL_LO:
       return rh.Relay.OPEN
     elif hwstatus == LEVEL_HI:
       return rh.Relay.CLOSED
     return rh.Relay.UNKNOWN
Beispiel #55
0
    def button_raw_press(self):
        if not self.button_callback:
            return

        time.sleep(self.DEBOUNCE_MS // 1000)
        if not wiringpi2.digitalRead(self.BUTTON_PIN):
            logger.info("button press detected!")
            self.button_pressed = time.time()
            self.button_callback()
Beispiel #56
0
 def update_state(self):
     if self.button_pressed > 0:
         if not wiringpi2.digitalRead(self.BUTTON_PIN):
             # button is still pressed
             if time.time() - self.button_pressed > self.LONGPRESS_SEC:
                 logger.info("LONG BUTTON PRESS - POWEROFF")
                 platform_poweroff()
         else: # button is released
             self.button_pressed = -1
Beispiel #57
0
	def gpioCallback(self):
		if bool(wiringpi.digitalRead(self._watchPin)) == self._triggerOnHigh:
			with self._dataLock:
				self._lastStatus = True
		else:
			with self._dataLock:
				if self._lastStatus:
					self._lastStatus = False
					self._triggerEnded = datetime.today()
Beispiel #58
0
 def run(self):
     while True:
         time.sleep(0.01)
         if wiringpi.digitalRead(17) > 0:
             self.cursor.set_to_shoot()
             self.shot = True
         elif self.shot == True:
             self.cursor.set_released()
             self.shot = False