예제 #1
0
    def _GetRawMessageOld(self):
        """
        DEPRECATED
        REQUIRES ReceiveMorse() TO BE UPDATED TO REUSE
        Private Function
        Description: On edge trigger, reads the value of channel_in one time every
            count seconds and adds that value to a buffer. End of message is 
            determined when 10 counts of low ('0') have been consecutively read.
            Beginning of message should contain 6 garage values used to stabilize
            output stream. Low is recorded as '0' and high as '1'
        Return: (string) buffer of values on channel_in once edge triggered. First
            six (6) items and last ten (10) items have been removed before return.
        """
        receiving = True
        s = ''
        # Start at edge trigger
        while pfio.digital_read(self.channel_in) == 1:
            pfio.digital_read(self.channel_in)

        # Check every count if hi or low
        while receiving:
            # Write state to string
            if pfio.digital_read(self.channel_in) == 0:
                s += '1'
            else:
                s += '0'

            # exit if last 10 counts l
            if s[-10:] == "0000000000":
                receiving = False
                break

            time.sleep(self.count)  # sleep rest of count
        # remove last 10 items and return
        return s[6:-10]
예제 #2
0
def r():
    while True:
        print dio.digital_read(0)
        #print dio.digital_read(1)
        #print dio.digital_read(2)
        #print dio.digital_read(3)
        #print dio.digital_read(4)
        #print dio.digital_read(5)
        #print dio.digital_read(6)
        #print dio.digital_read(7)
        sleep(1)
예제 #3
0
def main():
    piface.init()
    global screen
    pygame.init()
    if (not os.path.isdir(logo_path)):
        print "ERROR: tweetmachine dir not found in"
        print logo_path
        sys.exit(2)
    size = width, height = 600, 400
    screen = pygame.display.set_mode(size)
    pygame.mouse.set_visible(0)

    parser = OptionParser()
    parser.add_option("-t", "--twitter", dest="twitter", action="store_true",\
default=False, help= "start monitoring twitter feed")
    parser.add_option("-l", "--logo", dest="logo", action ="store_true",\
default=False, help= "display LowellMakes Logo")
    parser.add_option("-w", "--write",dest="text", default ='', help = "display\
text on the screen")
    parser.add_option("-a", "--auto", dest="loop", default =False, action ="store_true",\
help = "runs a loop, accepts input from the std_in")
    parser.add_option("-b", "--btn", dest="btn", default =False, action ="store_true", help = "polls the coin return button")
    (options,args)=parser.parse_args()

    if(options.twitter == True):
        displayTwitter()
    elif(options.logo == True):
        displayLogo()
    elif(not(options.text is '')):
        displayText(options.text, 100, 30, (200,200,1), True )
    elif(options.btn == True):
        while(True):
            if piface.digital_read(0):
                displayTwitter()
                displayLogo()
            elif piface.digital_read(2):
                break;
    elif(options.loop == True):
        end = True
        while(end):
            usr_input=raw_input("enter choice l=logo,t=twitter,e=exit\n")
            if usr_input is "t":
                displayTwitter()
            elif usr_input is "l":
                displayLogo()
            elif usr_input is "e":
                break;
            time.sleep(1)
    time.sleep(1)
예제 #4
0
    def receive(self, sequence, command, *av):
        if command == "DigitalWrite":
            pin, value = av[0], av[1]
            pifacedigitalio.digital_write(pin, value and 1 or 0, self.board)
        elif command == "DigitalRead":
            pin = av[0]
            return pifacedigitalio.digital_read(pin, self.board)
        elif command == "DigitalListen":
            pin = av[0]
            self.listensd.setdefault(pin, set()).add(sequence)

            if self.listener:
                self.listener.deactivate()

            self.listener = pifacedigitalio.InputEventListener(chip=self.pfd)

            for pin in self.listensd.keys():
                self.listener.register(pin, pifacedigitalio.IODIR_ON, self._event)
                self.listener.register(pin, pifacedigitalio.IODIR_OFF, self._event)

            self.listener.activate()
            return ""
        else:
            raise KeyError("unknown command: %s" % command)
            
        print ("comm_piface.receive: seq=%s comm=%s" % ( sequence, command ), file=sys.stderr)
예제 #5
0
 def test_big_digital_read_write(self):
     pin = 0
     for i in range(1000):
         for test_value in (1, 0):
             pifacedigitalio.digital_write(pin, test_value)
             v = pifacedigitalio.digital_read(7 - pin)
             self.assertEqual(test_value, v)
예제 #6
0
    def test_switches(self):
        global pifacedigitals
        for pfd in pifacedigitals:
            for a, b in ((0, 2), (1, 3)):
                # user input
                # input(
                #     "Hold switch {a} and {b} on board {board} and then "
                #     "press enter.".format(a=a, b=b, board=pfd.hardware_addr))
                # test rig input
                pfd.output_pins[7 - a].turn_on()
                pfd.output_pins[7 - b].turn_on()

                self.assertEqual(pfd.switches[a].value, 1)
                self.assertEqual(pfd.switches[b].value, 1)

                # while we're here, test the input pins
                self.assertEqual(pfd.input_pins[a].value, 1)
                self.assertEqual(pifacedigitalio.digital_read(a, pfd.hardware_addr), 1)
                self.assertEqual(pfd.input_pins[b].value, 1)

                # and the input port
                bit_pattern = (1 << a) ^ (1 << b)
                self.assertEqual(pfd.input_port.value, bit_pattern)

                # test rig input
                pfd.output_pins[7 - a].turn_off()
                pfd.output_pins[7 - b].turn_off()
def poll():
    """
    The main loop in which we monitor the state of the PINs
    and publish any changes.
    """
    while True:
        for PIN in PINS:
            index = [y[0] for y in PINS].index(PIN[0])
            pin = PINS[index][0]
            oldstate = PINS[index][1]

            if PFIO_MODULE:
                newstate = PFIO.digital_read(pin)

            if GPIO_MODULE:
                newstate = GPIO.input(pin)

            if newstate != oldstate:
                logging.debug("Pin %d changed from %d to %d" %
                              (pin, oldstate, newstate))
                mqttc.publish(MQTT_TOPIC_OUT % pin,
                              payload=newstate,
                              qos=MQTT_QOS,
                              retain=MQTT_RETAIN)
                PINS[index][1] = newstate

        time.sleep(MONITOR_POLL)
예제 #8
0
 def do_POST(self):
     # Doesn't do anything with posted data
     self._set_headers()
     # Read the current state of the Door
     state = p.digital_read(0)
     # Prepare Pushbullet Response
     text = "[Garage Door] "
     if state is DOOR_CLOSED:
         # We are Opening the door
         text += "Opened"
         # Toggle the Relay
         toggle_door()
         # Since it was closed, only wait a second to see if it opened.
         time.sleep(1)
         # Read the state of the door again
         state = p.digital_read(0)
         # Check the state
         if state is DOOR_OPEN:
             # Push a Note on the state Change
             push = pb.push_note(text, "")
             # Reply to the HTTP packet.
             self.wfile.write("Door Closed!\n")
         else:
             # Push a Note on the state Change
             push = pb.push_note(
                 "[Garage Door] Error",
                 "Could Not tell if the door is open or not!")
             # Reply to the HTTP packet.
             self.wfile.write("ERROR\n")
     else:
         # We are Closing the door
         text += "Closed"
         toggle_door()
         time.sleep(10)
         state = p.digital_read(0)
         if state is DOOR_CLOSED:
             # Push a Note on the state Change
             push = pb.push_note(text, "")
             # Reply to the HTTP packet.
             self.wfile.write("Door Closed!\n")
         else:
             # Push a Note on the state Change
             push = pb.push_note(
                 "[Garage Door] Error",
                 "Could Not tell if the door is open or not!")
             # Reply to the HTTP packet.
             self.wfile.write("ERROR\n")
예제 #9
0
 def print_input(event):
     global input
     # print(event.pin_num)
     mapthing = [3, 6, 2, 5, 8, 1, 4, 7]
     # debounce for 50ms
     time.sleep(0.05)
     if p.digital_read(event.pin_num):
         input = mapthing[event.pin_num]
예제 #10
0
파일: garagemon.py 프로젝트: vinojai/Gmon
    def run(self):
        print "begin"
        conn = sqlite3.connect('/var/sqlite/garagemon.db')
        ## I'm alive! Determine the last known door position
        c.execute('SELECT current_position FROM position')
        status = c.fetchone()
        doorState = "unknown"
        doorOpenCtr = 0
        piface.init()
        while True:
            ## Ping the router to keep the wifi alive
            response = os.system("ping -c 1 " + "10.0.0.1")

            if doorState is "open" and doorOpenCtr is 10:
                curl.setopt(curl.URL, 'http://localhost/evaluatestillopen')
                curl.perform()                            

            piface.digital_write_pullup(0, 1)
            ## Door open state
            if (piface.digital_read(0) == 0 and doorState is "closed") or doorState is "unknown":
                curl.setopt(curl.URL, 'http://localhost/evaluateopen')
                curl.perform() 
                doorState = "open";
                ## Set the little led lights
                # piface.digital_write(1, 0)
                # piface.digital_write(0, 1)
                doorOpenCtr = 0;
            ## Door closed state
            elif (piface.digital_read(0) > 0  and doorState is "open") or doorState is "unknown":
                curl.setopt(curl.URL, 'http://localhost/evaluateclosed')
                curl.perform()
                doorState = "closed";
                # Set the little led lights
                # piface.digital_write(0, 0)
                # piface.digital_write(1, 1)
            piface.digital_write_pullup(0, 0)
            # logger.debug("Debug message")
            # logger.info("Info message")
            # logger.warn("Warning message")
            # logger.error("Error message")
            # logger.info("Info message")
            # logger.info ('Memory usage: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
            time.sleep(10)
            ## Increment the door open counter so we can be reminded once. 
            if doorState is "open":
                doorOpenCtr = doorOpenCtr + 1
예제 #11
0
    def _event(self, event):
        pin = event.pin_num

        listens = self.listensd.get(pin)
        if not listens:
            return

        for sequence in listens:
            value = pifacedigitalio.digital_read(pin, self.board)
            self.send(sequence,value)
예제 #12
0
 def do_POST(self):
     # Doesn't do anything with posted data
     self._set_headers()
     # Read the current state of the Door
     state = p.digital_read(0)
     # Prepare Pushbullet Response
     text = "[Garage Door] "
     if state is DOOR_CLOSED:
         # We are Opening the door
         text += "Opened"
         # Toggle the Relay
         toggle_door()
         # Since it was closed, only wait a second to see if it opened.
         time.sleep(1)
         # Read the state of the door again
         state = p.digital_read(0)
         # Check the state
         if state is DOOR_OPEN:
             # Push a Note on the state Change
             push = pb.push_note(text, "")
             # Reply to the HTTP packet.
             self.wfile.write("Door Closed!\n")
         else:
             # Push a Note on the state Change
             push = pb.push_note("[Garage Door] Error", "Could Not tell if the door is open or not!")
             # Reply to the HTTP packet.
             self.wfile.write("ERROR\n")
     else:
         # We are Closing the door
         text += "Closed"
         toggle_door()
         time.sleep(10)
         state = p.digital_read(0)
         if state is DOOR_CLOSED:
             # Push a Note on the state Change
             push = pb.push_note(text, "")
             # Reply to the HTTP packet.
             self.wfile.write("Door Closed!\n")
         else:
             # Push a Note on the state Change
             push = pb.push_note("[Garage Door] Error", "Could Not tell if the door is open or not!")
             # Reply to the HTTP packet.
             self.wfile.write("ERROR\n")
예제 #13
0
 def do_GET(self):
     self._set_headers()
     # Get the state of the door
     state = p.digital_read(0)
     if state is DOOR_OPEN:
         # Reply to the HTTP
         self.wfile.write("Open\n")
     else:
         # Reply to the HTTP
         self.wfile.write("Closed\n")
예제 #14
0
    def read(self):
        """Read current state from the controller and return info"""
        # Initalize piface digital and list to store inputs
        p.init()
        values = [0, 0, 0, 0, 0]

        for i in range(5):
            values[i] = p.digital_read(i)

        return values
예제 #15
0
 def do_GET(self):
     self._set_headers()
     # Get the state of the door
     state = p.digital_read(0)
     if state is DOOR_OPEN:
         # Reply to the HTTP
         self.wfile.write("Open\n")
     else:
         # Reply to the HTTP
         self.wfile.write("Closed\n")
예제 #16
0
  def read(self):
      """Read current state from the controller and return info"""
      # Initalize piface digital and list to store inputs
      p.init()    
      values = [0,0,0,0,0]
  
 
      for i in range(5):
          values[i] = p.digital_read(i)
               
      return values    
예제 #17
0
def pin_read(pin):
	state = -1
	if PFIO_MODULE:
		state = PFIO.digital_read(pin)
	
	if GPIO_MODULE:
		state = GPIO.input(pin)
		
	if PIGPIO_MODULE:
		state = pi.read(pin)
		
	return state
def read_pin(pin):
    state = -1
    if PFIO_MODULE:
        state = PFIO.digital_read(pin)

    if GPIO_MODULE:
        state = GPIO.input(pin)

    if MONITOR_OUT_INVERT:
        if state == 0:
            state = 1
        elif state == 1:
            state = 0
    return (state)
def read_pin(pin):
    state = -1
    if PFIO_MODULE:
        state = PFIO.digital_read(pin)
        
    if GPIO_MODULE:
        state = GPIO.input(pin)

    if MONITOR_OUT_INVERT:
        if state == 0:
            state = 1
        elif state == 1:
            state = 0
    return(state)
예제 #20
0
def main():
	from time import sleep
	import pifacedigitalio as p
	p.init()
	speed = 1

	while(True):
		if p.digital_read(0):
			speed = 0.7
		elif p.digital_read(1):
			speed = 0.5
		elif p.digital_read(2):
			speed = 0.4
		elif p.digital_read(3):
			speed = 0.2
		elif p.digital_read(4):
			speed = 0.05
		
		print("Speed:" + str(speed))
		
		p.digital_write(0,1) #turn 0 on (green)
		p.digital_write(3,1) #turn 3 on (buzzer)
		sleep(speed)
		p.digital_write(3,0) #turn 3 off (buzzer)
		p.digital_write(0,0) #turn 0 off (green)
		p.digital_write(1,1) #turn 1 on (yellow)
		p.digital_write(3,1) #turn 3 on (buzzer)
		sleep(speed)
		p.digital_write(3,0) #turn 3 off (buzzer)
		p.digital_write(1,0) #turn 1 off (yellow)
		p.digital_write(2,1) #turn 2 on (red)
		p.digital_write(3,1) #turn 3 on (buzzer)
		sleep(speed)
		p.digital_write(3,0) #turn 3 off (buzzer)
		p.digital_write(2,0) #turn 2 off (red)
	
	return 0
예제 #21
0
    def play(self):
        working = True
        p.init()

        while working:
            S1 = p.digital_read(0)
            S2 = p.digital_read(3)

            if S1 == 1:
                # Send -1 to move player to the left
                msg = '-1'
                self.sock.sendto(msg, (self.UDP_IP, self.UDP_PORT))

                # Turn on the LED while the button is pressed
                p.digital_write(0, 1)

                # Wait until the button is let go before reading a new bit
                while p.digital_read(0) == 1:
                    pass

                # Turn off the LED
                p.digital_write(0, 0)

            if S2 == 1:
                # Send 1 to move player to the right
                msg = '1'
                self.sock.sendto(msg, (self.UDP_IP, self.UDP_PORT))

                # Turn on the LED while the button is pressed
                p.digital_write(3, 1)

                # Wait until the button is let go before reading a new bit
                while p.digital_read(3) == 1:
                    pass

                # Turn off the LED
                p.digital_write(3, 0)
def refresh():
    """
    Refresh the state of all pins we are monitoring
    """
    for PIN in PINS:
        index = [y[0] for y in PINS].index(PIN[0])
        pin = PINS[index][0]

        if PFIO_MODULE:
            state = PFIO.digital_read(pin)
        
        if GPIO_MODULE:
            state = GPIO.input(pin)

        logging.debug("Refreshing pin %d state -> %d" % (pin, state))
        mqttc.publish(MQTT_TOPIC_OUT % pin, payload=state, qos=MQTT_QOS, retain=MQTT_RETAIN)
def refresh():
    """
    Refresh the state of all pins we are monitoring
    """
    for PIN in PINS:
        index = [y[0] for y in PINS].index(PIN[0])
        pin = PINS[index][0]

        if PFIO_MODULE:
            state = PFIO.digital_read(pin)

        if GPIO_MODULE:
            state = GPIO.input(pin)

        logging.debug("Refreshing pin %d state -> %d" % (pin, state))
        mqttc.publish(MQTT_TOPIC_OUT % pin,
                      payload=state,
                      qos=MQTT_QOS,
                      retain=MQTT_RETAIN)
예제 #24
0
def check_input():  # check-function for reading input-ports
    if io.digital_read(0) == 1:
        return 'Havarie'
    elif io.digital_read(1) == 1:
        return 'Studio 1'
    elif io.digital_read(2) == 1:
        return 'Studio 2'
    elif io.digital_read(3) == 1:
        return 'Studio Geislingen'
    elif io.digital_read(4) == 1:
        return 'Studio Mobil/FW'
    elif io.digital_read(5) == 1:
        return 'Loop / Zara'
    else:
        return 'Keine Rueckmeldung von der Kreuzschiene'
def poll():
    """
    The main loop in which we monitor the state of the PINs
    and publish any changes.
    """
    while True:
        for PIN in PINS:
            index = [y[0] for y in PINS].index(PIN[0])
            pin = PINS[index][0]
            oldstate = PINS[index][1]

            if PFIO_MODULE:
                newstate = PFIO.digital_read(pin)
            
            if GPIO_MODULE:
                newstate = GPIO.input(pin)

            if newstate != oldstate:
                logging.debug("Pin %d changed from %d to %d" % (pin, oldstate, newstate))
                mqttc.publish(MQTT_TOPIC_OUT % pin, payload=newstate, qos=MQTT_QOS, retain=MQTT_RETAIN)
                PINS[index][1] = newstate

        time.sleep(MONITOR_POLL)
def poll():
    """
    The main loop in which we monitor the state of the PINs
    and publish any changes.
    """
    while True:
        for PIN in PINS:
            index = [y[0] for y in PINS].index(PIN[0])
            pin = PINS[index][0]
            oldstate = PINS[index][1]

            if PFIO_MODULE:
                newstate = PFIO.digital_read(pin)
            
            if GPIO_MODULE:
                newstate = GPIO.input(pin)

            if newstate != oldstate:
                logging.debug("Pin %d changed from %d to %d" % (pin, oldstate, newstate))
                mqttc.publish(MQTT_TOPIC_OUT % pin, payload=newstate, qos=MQTT_QOS, retain=MQTT_RETAIN)
                PINS[index][1] = newstate

        for ADC in ADCS:
            index = [y[0] for y in ADCS].index(ADC[0])
            adc = ADCS[index][0] - 1

            oldvalue = ADCS[index][1]
            newvalue = readadc(adc)

            if newvalue != -1:
                if abs(newvalue - oldvalue) > 50:
                    logging.debug("Adc %d changed from %d to %d" % (adc, oldvalue, newvalue))
                    mqttc.publish(MQTT_TOPIC_ADC % adc, payload=newvalue, qos=MQTT_QOS, retain=MQTT_RETAIN)
                    ADCS[index][1] = newvalue


        time.sleep(MONITOR_POLL)
예제 #27
0
    def _GetRawMessage(self):
        """
        Private Function
        Description: On initial edge trigger, measures how many counts channel_in 
            is high or low
        Return: (string) buffer of values (low = '0', high = '1') from channel_in 
            once edge triggered. 
        """
        s = ''
        dur = 0
        # Start at edge trigger
        while pfio.digital_read(self.channel_in) == 1:
            pfio.digital_read(self.channel_in)

        # This makes this class more coupled but I like the feature
        print("Receiving message...")

        # set current state (1 if hi, 0 if low)
        state = 0

        # Start high timer
        hiTimeStart = time.time()

        while (dur < 10 * self.count):
            # Main loop timer
            start = time.time()
            if state == 0:  # state is high
                # edge trigger to low
                # edge trigger loop timer
                eT = time.time()
                while pfio.digital_read(self.channel_in) == 0:
                    pfio.digital_read(self.channel_in)
                    if (time.time() - eT > 10 * self.count):
                        break
                # Start low timer, end high timer
                lowTimeStart = hiTimeEnd = time.time()
                # Switch state
                state = 1
                # Add values
                for i in range(round((hiTimeEnd - hiTimeStart) / self.count)):
                    s += '1'
            else:
                # edge trigger to hi
                # edge trigger loop timer
                eT = time.time()
                while pfio.digital_read(self.channel_in) == 1:
                    pfio.digital_read(self.channel_in)
                    if (time.time() - eT > 10 * self.count):
                        break
                # Start high timer, end low timer
                hiTimeStart = lowTimeEnd = time.time()
                # Switch state
                state = 0
                # Add values
                for i in range(round(
                    (lowTimeEnd - lowTimeStart) / self.count)):
                    s += '0'
            # exit if too long pause
            dur = time.time() - start
        # remove last 10 items (excess zeros) and return
        return s[:-10]
예제 #28
0
 def test_flip_bit(self):
     # digital_read should flip 0 to 1
     self.assertEqual(pifacedigitalio.digital_read(0, 0), 1)
    def process_config(self,configno,speed):
        """ Process the next configuration. """

        self.timeout = 0
        self.Switch_pressed = False
        
        # whilst not timed out and no column switch has been pressed
        while self.timeout < speed and self.Switch_pressed== False :
            # update the timeout counter 
            self.timeout = self.timeout +10
            # get current state of the 4 column choice switches
            self.ColumnSwitch1 = pfio.digital_read (CLEDCOL1_BUTTON, CBOARDwithBUTTONS);
            self.ColumnSwitch2 = pfio.digital_read (CLEDCOL2_BUTTON, CBOARDwithBUTTONS);
            self.ColumnSwitch3 = pfio.digital_read (CLEDCOL3_BUTTON, CBOARDwithBUTTONS);
            self.ColumnSwitch4 = pfio.digital_read (CLEDCOL4_BUTTON, CBOARDwithBUTTONS);
            # and get current state of the STOP switche
            self.StopSwitch = pfio.digital_read (CSTOPBUTTON, CBOARDwithBUTTONS);

            # check which column was chosen
            if self.StopSwitch == True :
                self.Switch_pressed = True               
            else:
                if (self.ColumnSwitch1 ==True or self.ColumnSwitch2 ==True or
                    self.ColumnSwitch3 ==True or self.ColumnSwitch4 == True ):
                    # check which button and hence which column chosen
                    if self.ColumnSwitch1:
                        # put the chosen column no in the players stats table
                        self.player_results[configno][C_player_answer] = 1
                    elif self.ColumnSwitch2:          
                       # put the chosen column no in the players stats table
                        self.player_results[configno][C_player_answer] = 2
                    elif self.ColumnSwitch3 :          
                      # put the chosen column no in the players stats table
                        self.player_results[configno][C_player_answer] = 3
                    elif self.ColumnSwitch4:          
                       # put the chosen column no in the players stats table
                        self.player_results[configno][C_player_answer] = 4

                    # set button pressed to show that a column has been chosen
                    self.Switch_pressed = True
                    # put the time taken in the players stats table
                    self.player_results[configno][C_player_time] = self.timeout
                    # check if the chosen column is correct and update the players stats table
                    if self.player_results[configno][C_player_answer] == self.player_results[configno][C_correct_column]:
                        self.player_results[configno][C_player_correct] = True
                    else:
                        self.player_results[configno][C_player_correct] = False
                # update the timeout counter 
                self.timeout = self.timeout +10
                # sleep for 0.01s before testing again
                sleep(0.01)
                
        # if the player has not pressed a button before the timeout then
        # the player stats need to be updated to show Timeout.
        if self.StopSwitch == True or self.Switch_pressed == False :
            # put the column no  0 in the players stats table to indicate Timeout
            self.player_results[configno][C_player_answer] = 0
            # set the player correct indicator to False
            self.player_results[configno][C_player_correct] = False
            # set the players time to speed to indicate timeout
            self.player_results[configno][C_player_time] = speed + 1
        
        if self.StopSwitch == True:
            self.stop_game()
            
        self.turnall_off()        
예제 #30
0
    def process_config(self, configno, speed):
        """ Process the next configuration. """

        self.timeout = 0
        self.Switch_pressed = False

        # whilst not timed out and no column switch has been pressed
        while self.timeout < speed and self.Switch_pressed == False:
            # update the timeout counter
            self.timeout = self.timeout + 10
            # get current state of the 4 column choice switches
            self.ColumnSwitch1 = pfio.digital_read(CLEDCOL1_BUTTON,
                                                   CBOARDwithBUTTONS)
            self.ColumnSwitch2 = pfio.digital_read(CLEDCOL2_BUTTON,
                                                   CBOARDwithBUTTONS)
            self.ColumnSwitch3 = pfio.digital_read(CLEDCOL3_BUTTON,
                                                   CBOARDwithBUTTONS)
            self.ColumnSwitch4 = pfio.digital_read(CLEDCOL4_BUTTON,
                                                   CBOARDwithBUTTONS)
            # and get current state of the STOP switche
            self.StopSwitch = pfio.digital_read(CSTOPBUTTON, CBOARDwithBUTTONS)

            # check which column was chosen
            if self.StopSwitch == True:
                self.Switch_pressed = True
            else:
                if (self.ColumnSwitch1 == True or self.ColumnSwitch2 == True
                        or self.ColumnSwitch3 == True
                        or self.ColumnSwitch4 == True):
                    # check which button and hence which column chosen
                    if self.ColumnSwitch1:
                        # put the chosen column no in the players stats table
                        self.player_results[configno][C_player_answer] = 1
                    elif self.ColumnSwitch2:
                        # put the chosen column no in the players stats table
                        self.player_results[configno][C_player_answer] = 2
                    elif self.ColumnSwitch3:
                        # put the chosen column no in the players stats table
                        self.player_results[configno][C_player_answer] = 3
                    elif self.ColumnSwitch4:
                        # put the chosen column no in the players stats table
                        self.player_results[configno][C_player_answer] = 4

                    # set button pressed to show that a column has been chosen
                    self.Switch_pressed = True
                    # put the time taken in the players stats table
                    self.player_results[configno][C_player_time] = self.timeout
                    # check if the chosen column is correct and update the players stats table
                    if self.player_results[configno][
                            C_player_answer] == self.player_results[configno][
                                C_correct_column]:
                        self.player_results[configno][C_player_correct] = True
                    else:
                        self.player_results[configno][C_player_correct] = False
                # update the timeout counter
                self.timeout = self.timeout + 10
                # sleep for 0.01s before testing again
                sleep(0.01)

        # if the player has not pressed a button before the timeout then
        # the player stats need to be updated to show Timeout.
        if self.StopSwitch == True or self.Switch_pressed == False:
            # put the column no  0 in the players stats table to indicate Timeout
            self.player_results[configno][C_player_answer] = 0
            # set the player correct indicator to False
            self.player_results[configno][C_player_correct] = False
            # set the players time to speed to indicate timeout
            self.player_results[configno][C_player_time] = speed + 1

        if self.StopSwitch == True:
            self.stop_game()

        self.turnall_off()
#!/usr/bin/python

import pifacedigitalio as p
p.init()

#keep track of state of the inputs of previous run
prevports = -1

while 1:
    #mask will indicate which bit to set in the bitfield
    mask = 1
    #bitfield to record state of all ports
    ports = 0
    
    for x in range(0,8):
        #read port state of port x
        i = p.digital_read(x)
        #if port is high, add it to the bitfield
        if (i == 1):
            ports = ports | mask
        #set mask for next port
        mask = mask << 1
    #only output a line if a change since last check has been detected and save the new state
    if (ports != prevports):
        print "ports: %s" % bin(ports)[2:].zfill(8)
        prevports = ports
예제 #32
0
            pfio.digital_write(led, 1)
      sleep(interval)
      for led in leds:
         if led % 2:
            pfio.digital_write(led, 0)
      i += 1

catepillarWalk(rounds, sleepTime)
pingpong(rounds, sleepTime)
evenOddAlternate(rounds, sleepTime)

print("Meny:")
print("=====")
print("Button 0: Catepillar walk LED show.")
print("Button 1: Pingpong LED show.")
print("Button 2: Even-Odd alternating LED show.")
print("Button 3: Exit the program.")
print()
print("Please press one of the buttons to continue.")

while True:
   if pfio.digital_read(0):
      catepillarWalk(1, sleepTime)
   elif pfio.digital_read(1):
      pingpong(1, sleepTime)
   elif pfio.digital_read(2):
      evenOddAlternate(1, sleepTime)
   elif pfio.digital_read(3):
      break

예제 #33
0
 def is_raining(self, relay_no):
     print "PiFace.is_raining()..."
     result = pifacedigitalio.digital_read(relay_no)
     if result == 1:
         return True
     return False
예제 #34
0
파일: test.py 프로젝트: ndebras/raspberrypi
    PFIO_TRIGGER = 2
    PFIO_ECHO = 0
    
    # Set trigger to False (Low)
    pfio.digital_write(PFIO_TRIGGER,0)
    
    # Allow module to settle
    time.sleep(1)
    os.system('clear')
    # Send 10us pulse to trigger
#    pfio.digital_write(PFIO_TRIGGER, 1)
    time.sleep(0.0001)
    pfio.digital_write(PFIO_TRIGGER, 0)
    start = time.time()

    print (pfio.digital_read(PFIO_ECHO))
    
    while pfio.digital_read(PFIO_ECHO)==0:
      pfio.digital_write(4,1)
      pfio.digital_write(4,0)
    print ("START : %.10f" % start)
    
#    while pfio.digital_read(PFIO_ECHO)==0:
    while(True):
        pfio.digital_write(6,1)
        stop = time.time()
	print("STOP : %.10f" % stop)
	print(pfio.digital_read(PFIO_ECHO))
        pfio.digital_write(6,0)
	time.sleep(.3)
    
예제 #35
0
#PWM PiFace Motor Speed Controller

import pifacedigitalio as p
import datetime, time
from datetime import timedelta

p.init()
t1=datetime.datetime.now()
previous=0
teller=0

while True:
	if (p.digital_read(0) == 1) and (previous == 0):
   		teller=teller+1
	previous=p.digital_read(0)
	t2=datetime.datetime.now()    
	delta=t2-t1
	if delta.seconds == 60:
		print"rpm = %d\n\r"%teller
		teller=0
		t1=datetime.datetime.now()

예제 #36
0
def get_val(pin):
    global pifacedigitalio
    return pifacedigitalio.digital_read(pin)
예제 #37
0
 def status_inputpin(self, pin):
     return p.digital_read(pin) == 1
print ("PiFace Digital ONBOARD Switch Test Start");
print ("");
print ("You will be asked to press each of the on-board switches (4 per PiFace Digital).");
print ("If you do not press the switch OR the PiFace Digital board is not present then");
print ("the test will proceed to the next switch.  One of three reports will be printed:");
print ("1) The button was pressed;");
print ("2) A timeout occurred;");
print ("3) No PiFace Digital Board is not present.");


for loopBoard in range (0,4,1):
    for loopSwitch in range (0,4,1):
        count = 0;
        print("");
        print ("Press Onboard Button " + str(loopSwitch) + " on PiFace Board " + str(loopBoard));
        input_value = pfio.digital_read (loopSwitch, loopBoard);
        if input_value == False:
            while input_value == False and count < CMAXCOUNT:
                input_value = pfio.digital_read (loopSwitch, loopBoard);
                count = count + 1;
        
        if count == 0:
            print ("No PiFace Digital Board")
        elif count < CMAXCOUNT:
            print ("Button Pressed");
        else:
            print ("*** TIMEOUT");

print ("");
print ("Individual Onboard Switch Tests Complete");
print ("");
예제 #39
0
from time import sleep
import pygame
pygame.init()
import pifacedigitalio as p

p.init()

start = True

Stopper = 0
Stop = False

while start:
    DI4 = p.digital_read(4)
    DI5 = p.digital_read(5)
    DI6 = p.digital_read(6)
    Stopper = 0

    while DI4 and not DI6:
        Stopper = 0
        
        p.digital_write(0,1)
        p.digital_write(1,0)
        p.digital_write(2,0)
        p.digital_write(3,0)
        p.digital_write(4,0)
        p.digital_write(5,0)
        p.digital_write(6,0)
        p.digital_write(7,0)
        
        sleep(0.75)
예제 #40
0
    def start_game(self):
        status = ""
        self.choices_txt.delete(CSTARTED_ROW, END)
        self.choices_txt.insert(CSTARTED_ROW, status)
        self.timeout = 0
        self.quadrant_circuit = 0
        self.quadrant_timer = 0
        self.StartButton_pressed = False  # True if START button on screen is pressed
        self.StopSwitch = False  # True if STOP switch on game is pressed
        self.Switch_pressed = False  # True if STOP button or Stop Switch or any column button is pressed
        count = 1
        #first empty the results table ready for new results
        for config in range(1, 255):
            self.player_results[config][C_correct_column] = 0
            self.player_results[config][C_player_answer] = 0
            self.player_results[config][C_player_correct] = 0
            self.player_results[config][C_player_time] = -1

        # next make sure all LEDs are off
        self.turnall_off()
        # clear the statistics and results tables ready for new stats and results
        self.stats_txt.delete(0.0, END)
        self.results_txt.delete(0.0, END)

        #then start the quadrant pattern
        # whilst not timed out and start switch not pressed
        while (self.timeout < 1050  # Player hasn't timedout
               and self.StartButton_pressed ==
               False  # player hasn't pressed Start Switch
               and self.StopSwitch
               == False):  # player hasn't pressed Stop Switch
            # get current state of switches
            self.StartButton_pressed = pfio.digital_read(
                CSTARTBUTTON, CBOARDwithBUTTONS)
            self.StopSwitch = pfio.digital_read(CSTOPBUTTON, CBOARDwithBUTTONS)
            if self.StartButton_pressed == False and self.StopSwitch == False:
                if self.quadrant_timer == 0:
                    self.quadrant_on_off(4, CLEDOFF)
                    self.quadrant_on_off(1, CLEDON)
                    self.quadrant_circuit = 2
                elif self.quadrant_timer == 50:
                    self.quadrant_on_off(1, CLEDOFF)
                    self.quadrant_on_off(2, CLEDON)
                    self.quadrant_circuit = 3

                elif self.quadrant_timer == 100:
                    self.quadrant_on_off(2, CLEDOFF)
                    self.quadrant_on_off(3, CLEDON)
                    self.quadrant_circuit = 4

                elif self.quadrant_timer == 150:
                    self.quadrant_on_off(3, CLEDOFF)
                    self.quadrant_on_off(4, CLEDON)
                    self.quadrant_circuit = 1

                elif self.quadrant_timer == 199:
                    self.quadrant_timer = -1

            self.timeout = self.timeout + 1
            self.quadrant_timer = self.quadrant_timer + 1
            sleep(0.01)

        if self.timeout == 1050:  # player hasn't pressed start quick enough
            status = status + "\nGame Start Timeout"
            status = status + " - press the Game board start button quicker!"
            self.choices_txt.delete(CSTARTED_ROW, END)
            self.choices_txt.insert(CSTARTED_ROW, status)
            self.turnall_off()
        elif self.StopSwitch == True:  # player has pressed Stop Switch
            self.stop_game()
            status = "\nGame stopped"
            self.choices_txt.delete(CSTOPPED_ROW, END)
            self.choices_txt.insert(CSTOPPED_ROW, status)
            self.stats_txt.delete(0.0, END)
            self.results_txt.delete(0.0, END)
        else:  # player has pressed start switch
            status = "\nGame started"
            self.choices_txt.delete(CSTARTED_ROW, END)
            self.choices_txt.insert(CSTARTED_ROW, status)
            self.stats_txt.delete(0.0, END)
            self.results_txt.delete(0.0, END)
            while self.StopSwitch == False and count < self.configs + 1:
                self.generate_random_LEDs(count)
                self.process_config(count, self.speed)
                count = count + 1
            self.calculate_results(count - 1, self.speed)
            self.calculate_statistics(count - 1, self.speed)
예제 #41
0
		tempstr += "#%.1f" % float(adSensor.sensor1.value)
		print (tempstr)

		logWrite(tempstr)

		# can no longer see these anyway...
		#if aaFound == 'a' or acFound == 'c':
		#	p.digital_write(LED_WARN2, 1)
		#else:
		#	p.digital_write(LED_WARN2, 0)

		if (utcDT.second == 0): # once a minute, too often?] #if 1:
			netWrite(netfilepathS, piNetfilename, tempstr) # copy log to sdrive 
			netWrite(netfilepathW, piNetfilename, tempstr)

		pb1 = p.digital_read(PB1)	# this is the nearest button to the USB port, old piface
		#t#pb1 = 0	#t#
		if (pb1 == 1):
			print ("Quitting program")
			resetAllOutputs()
			exit(0)
		p.digital_write(LED_BLINK,0)

	time.sleep(1)

	if utcDT.hour > lastHourlyRun:
		readFromIni(0); # read ini to pick up changes, ignore failure
		lastHourlyRun = utcDT.hour
		# use 'M' temporarily
		logstr = "M#%04u-%02u-%02uT%02u:%02u:%02uZ" % \
			(utcDT.year, utcDT.month, utcDT.day, utcDT.hour, utcDT.minute, utcDT.second)
예제 #42
0
def update_rds():
    if io.digital_read(0) == 1:
        filedest = open(nowplaying, "r+")
        if filedest.read() == "FIPS ;-)":
            filedest.close()
        else:
            filedest.truncate(0)
            filedest.seek(0, 0)
            filedest.write("FIPS ;-)")
            write_logfile("TITEL: ", "Notprogramm")
            filedest.close()
    if io.digital_read(1) == 1:  # Studio 1 check
        filesrc = open(path_studio1, "r")  # open Source and Dest Files
        filedest = open(nowplaying, "r+")
        if filesrc.read() == filedest.read(
        ):  # if source didn't change, don't write dest-file
            filesrc.close()
            filedest.close()
        else:  # if source changed...
            filedest.truncate(0)  # Empty file before writing new info
            filedest.seek(0, 0)  # Set position in file on very first position
            filesrc.seek(
                0, 0)  # Set position in sourcefile on very first position
            try:  # Catch IOError when file can't be written
                filedest.write(replace_umlaute(
                    filesrc.read()))  # write filecontent from source to dest
            except IOError:
                write_logfile("FEHLER: ", "Kann now-onair.txt nicht schreiben!"
                              )  # Catch IO-Error, write log
                return  #exit funktion
            filesrc.seek(
                0, 0)  # Set position in sourcefile on very first position
            write_logfile("TITEL: ", filesrc.read())
            filesrc.close()
            filedest.close()
    elif io.digital_read(2) == 1:  # Studio 2 check
        filesrc = open(path_studio2, "r")
        filedest = open(nowplaying, "r+")
        if filesrc.read() == filedest.read():
            filesrc.close()
            filedest.close()
        else:
            filedest.truncate(0)
            filedest.seek(0, 0)
            filesrc.seek(0, 0)
            try:
                filedest.write(replace_umlaute(filesrc.read()))
            except IOError:
                write_logfile("FEHLER: ",
                              "Kann now-onair.txt nicht schreiben!")
                return
            filesrc.seek(0, 0)
            write_logfile("TITEL: ", filesrc.read())
            filesrc.close()
            filedest.close()
    elif io.digital_read(3) == 1:  # Studio Geislingen check
        filesrc = open(path_geis, "r")
        filedest = open(nowplaying, "r+")
        if filesrc.read() == filedest.read():
            filesrc.close()
            filedest.close()
        else:
            filedest.truncate(0)
            filedest.seek(0, 0)
            filesrc.seek(0, 0)
            try:
                filedest.write(replace_umlaute(filesrc.read()))
            except IOError:
                write_logfile("FEHLER: ",
                              "Kann now-onair.txt nicht schreiben!")
                return
            filesrc.seek(0, 0)
            write_logfile("TITEL: ", filesrc.read())
            filesrc.close()
            filedest.close()
    elif io.digital_read(4) == 1:  # Studio Mobil / FW check
        filesrc = open(path_mobfw, "r")
        filedest = open(nowplaying, "r+")
        if filesrc.read() == filedest.read():
            filesrc.close()
            filedest.close()
        else:
            filedest.truncate(0)
            filedest.seek(0, 0)
            filesrc.seek(0, 0)
            try:
                filedest.write(replace_umlaute(filesrc.read()))
            except IOError:
                write_logfile("FEHLER: ",
                              "Kann now-onair.txt nicht schreiben!")
                return
            filesrc.seek(0, 0)
            write_logfile("TITEL: ", filesrc.read())
            filesrc.close()
            filedest.close()
    elif io.digital_read(5) == 1:  # Zara / Loop check
        filesrc = open(path_zara, "r")
        try:
            filedest = open(nowplaying, "r+")
        except IOError:
            write_logfile("FEHLER: ", "Kann now-onair.txt nicht öffnen!")
            return
        if filesrc.read() == filedest.read():
            filesrc.close()
            filedest.close()
        else:
            filedest.truncate(0)
            filedest.seek(0, 0)
            filesrc.seek(0, 0)
            try:
                filedest.write(replace_umlaute(filesrc.read()))
            except IOError:
                write_logfile("FEHLER: ",
                              "Kann now-onair.txt nicht schreiben!")
                return
            filesrc.seek(0, 0)
            write_logfile("TITEL: ", filesrc.read())
            filesrc.close()
            filedest.close()
    else:
        filedest = open(nowplaying, "r+")
        filedest.truncate(0)
        filedest.seek(0, 0)
        try:
            filedest.write("Irgendwas stimmt hier garnicht...")
        except IOError:
            write_logfile("FEHLER: ", "Kann now-onair.txt nicht schreiben!")
            return
        write_logfile("ERROR: ", "PiFace-Quelle unbekannt!")
        filedest.close()
예제 #43
0
def read_input(port):
    """Read a value from a PFIO."""
    import pifacedigitalio as PFIO
    return PFIO.digital_read(port)
예제 #44
0
def eingang_auslesen(eingang):
    wert = p.digital_read(eingang)
    if wert:
       return 'Eingang ist: EIN.'
    else:
       return 'Eingang ist: AUS.'
예제 #45
0
 def test_flip_bit(self):
     self.assertEqual(pfdio.digital_read(0, 0), 0)  # should return 0
예제 #46
0
#!/usr/bin/python

import time
import pifacedigitalio as p

pfio = p.PiFaceDigital()

p.init()

pfio.leds[7].turn_on()

while True:
    print p.digital_read(0)
    time.sleep(1)
예제 #47
0
from espeak import espeak
import pifacedigitalio as piface

piface.init()

import os

statements = ("Close this door now", "You will regret it tomorrow",
              "A moment on the lips you know the rest")
numberOfStatements = len(statements)
currentStatement = 0

inputPin = 0

while True:
    if piface.digital_read(inputPin):
        statement = statements[currentStatement % numberOfStatements]
        print statement
        speakCall = "espeak '" + statement + "' 2>/dev/null"
        os.system(speakCall)
        currentStatement += 1

        while piface.digital_read(inputPin):
            pass
예제 #48
0
   #camera.awb_gains=(1,1.9)
   # Camera warm-up time
   pose(1)
   time.sleep(1)
   print("1")
   camera.capture(file_name)
   pose(0)
   photolight(0)

p.init()
print ("Ready")
test_lights()
ready(1)
while(True):
 try:
  button0 = p.digital_read(0)
  button1 = p.digital_read(1)
  button3 = p.digital_read(3)

  if button3 == 1:
   print ("Button 4 gedrueckt!")  
   print ("shutdown in 7 Sekunden...")
   test_lights()
   subprocess.check_output("/sbin/shutdown -h now", stderr=subprocess.STDOUT, shell=True)
   sys.exit(0)
   time.sleep(1) 
  if ( button0 == 1 ) or ( button1 == 1):
   ready(0)
   if (button0 == 1):
    cam=0 # USB
    cam_name="usb"
예제 #49
0
            except IOError:
                write_logfile("FEHLER: ",
                              "Kann now-onair.txt nicht schreiben!")
                return
            filesrc.seek(0, 0)
            write_logfile("TITEL: ", filesrc.read())
            filesrc.close()
            filedest.close()
    else:
        filedest = open(nowplaying, "r+")
        filedest.truncate(0)
        filedest.seek(0, 0)
        try:
            filedest.write("Irgendwas stimmt hier garnicht...")
        except IOError:
            write_logfile("FEHLER: ", "Kann now-onair.txt nicht schreiben!")
            return
        write_logfile("ERROR: ", "PiFace-Quelle unbekannt!")
        filedest.close()


while True:  # main program-loop

    write_source_onair()
    update_rds()
    time.sleep(1)

    if io.digital_read(7) == 1:  # exit condition
        io.deinit()  # deinitialize piface-board
        break  # exit program
예제 #50
0
from time import sleep
import pifacedigitalio as pfd
pin0 = pin1 = pin2 = pin3 = 0
pfd.init()

p = pfd.digital_read(0)
q = pfd.digital_read(1)
r = pfd.digital_read(2)
s = pfd.digital_read(3)
t = pfd.digital_read(4)
u = pfd.digital_read(5)
v = pfd.digital_read(6)
mode = pfd.digital_read(7)
pintu = stop
auto = 1
man = 0
while (True):

    p = pfd.digital_read(0)
    q = pfd.digital_read(1)
    r = pfd.digital_read(2)
    s = pfd.digital_read(3)
    t = pfd.digital_read(4)
    u = pfd.digital_read(5)
    v = pfd.digital_read(6)
    mode = pfd.digital_read(7)  #READ NILAI SENSOR KE VARIABLE

    if (pintu == buka):  #MEMBUKA & MENUTUP PINTU
        pfd.digital_write(0, 1)
    else:
        if (pintu == tutup):
예제 #51
0
#!/usr/bin/python
#
# Status script for INDI Dome Scripting Gateway
#
# Arguments: file name to save current state and coordinates (parked ra dec)
# Exit code: 0 for success, 1 for failure
#

import sys
import pifacedigitalio as p

script, path = sys.argv

p.init()
roof_status = p.digital_read(0)
dome_status = str(roof_status) + ' 0 0'

status = open(path, 'w')
status.truncate()
status.write(dome_status)
status.close()

sys.exit(0)

예제 #52
0
effects = ['solarize','oilpaint','hatch','gpen','pastel','washedout','posterise','negative','sketch','emboss','colorswap','cartoon','none']
effectnumber = 0
initcamera()
# BUILD A SCREEN
pygame.init()
pygame.mouse.set_visible(0)
screen = pygame.display.set_mode((WIDTH,HEIGHT))
black = pygame.Color(0, 0, 0)
textcol = pygame.Color(255, 255, 255)
#screen.fill(black)
p.digital_write(3,1) #turn on
p.digital_write(4,1) #turn on

while True:
# my_input = wiringpi.digitalRead(25)
 my_input = p.digital_read(0)
 effect = p.digital_read(1)
# shutoff = wiringpi.digitalRead(24)
 shutoff = p.digital_read(2)
# effect = wiringpi.digitalRead(22)
 if shutoff == 1:
#  restart = "service shutterpi stop" 	 
#  subprocess.call(restart)
  pygame.quit()
  break
 if effect == 1:
  effect = effects[effectnumber] 
  effectnumber = (effectnumber + 1) % len(effects)
 # dotext('', 150, 150)
  changeeffect(effect)
  dotext(effect, 100, 150)
    def start_game(self):
        status= ""
        self.choices_txt.delete(CSTARTED_ROW, END)
        self.choices_txt.insert(CSTARTED_ROW, status)
        self.timeout = 0
        self.quadrant_circuit =0
        self.quadrant_timer = 0
        self.StartButton_pressed = False  # True if START button on screen is pressed
        self.StopSwitch  = False          # True if STOP switch on game is pressed
        self.Switch_pressed = False       # True if STOP button or Stop Switch or any column button is pressed
        count = 1
        #first empty the results table ready for new results
        for config in range (1,255):
            self.player_results[config][C_correct_column] = 0
            self.player_results[config][C_player_answer] = 0
            self.player_results[config][C_player_correct] = 0
            self.player_results[config][C_player_time] = -1

        # next make sure all LEDs are off
        self.turnall_off()
        # clear the statistics and results tables ready for new stats and results
        self.stats_txt.delete(0.0, END)
        self.results_txt.delete(0.0, END)

        #then start the quadrant pattern
        # whilst not timed out and start switch not pressed
        while (self.timeout < 1050                      # Player hasn't timedout
               and self.StartButton_pressed== False     # player hasn't pressed Start Switch
               and self.StopSwitch == False):           # player hasn't pressed Stop Switch
            # get current state of switches
            self.StartButton_pressed = pfio.digital_read (CSTARTBUTTON, CBOARDwithBUTTONS);
            self.StopSwitch  = pfio.digital_read (CSTOPBUTTON , CBOARDwithBUTTONS);
            if self.StartButton_pressed == False and self.StopSwitch ==False :
                if self.quadrant_timer == 0:
                   self.quadrant_on_off ( 4 , CLEDOFF )
                   self.quadrant_on_off ( 1 , CLEDON )
                   self.quadrant_circuit = 2
                elif self.quadrant_timer == 50:
                    self.quadrant_on_off ( 1 , CLEDOFF )
                    self.quadrant_on_off ( 2 , CLEDON )
                    self.quadrant_circuit = 3

                elif self.quadrant_timer == 100:
                    self.quadrant_on_off ( 2 , CLEDOFF )
                    self.quadrant_on_off ( 3 , CLEDON )
                    self.quadrant_circuit = 4

                elif self.quadrant_timer == 150:
                    self.quadrant_on_off ( 3 , CLEDOFF )
                    self.quadrant_on_off ( 4 , CLEDON )
                    self.quadrant_circuit = 1
                    
                elif self.quadrant_timer == 199 :
                    self.quadrant_timer = -1
                
            self.timeout = self.timeout +1
            self.quadrant_timer = self.quadrant_timer +1
            sleep(0.01)

        if self.timeout == 1050: # player hasn't pressed start quick enough
            status = status + "\nGame Start Timeout"
            status = status + " - press the Game board start button quicker!"
            self.choices_txt.delete(CSTARTED_ROW, END)
            self.choices_txt.insert(CSTARTED_ROW, status)
            self.turnall_off()
        elif self.StopSwitch == True : # player has pressed Stop Switch
            self.stop_game()
            status = "\nGame stopped"
            self.choices_txt.delete(CSTOPPED_ROW, END)
            self.choices_txt.insert(CSTOPPED_ROW, status)
            self.stats_txt.delete(0.0, END)
            self.results_txt.delete(0.0, END)
        else: # player has pressed start switch
            status = "\nGame started"
            self.choices_txt.delete(CSTARTED_ROW, END)
            self.choices_txt.insert(CSTARTED_ROW, status)
            self.stats_txt.delete(0.0, END)
            self.results_txt.delete(0.0, END)
            while self.StopSwitch == False and count <self.configs+1:
                self.generate_random_LEDs(count)
                self.process_config(count, self.speed)
                count = count +1
            self.calculate_results(count-1, self.speed)
            self.calculate_statistics(count-1, self.speed)
예제 #54
0
 def status_input(self, pin):
     if self._polarity is 0:
         return str(p.digital_read(int(pin))).lower() in HIGH_LEVEL
     else:
         return str(p.digital_read(int(pin))).lower() in LOW_LEVEL
예제 #55
0
 def status_input(self, pin):
     if self._polarity is 0:
         return str(p.digital_read(int(pin))).lower() in HIGH_LEVEL
     else:
         return str(p.digital_read(int(pin))).lower() in LOW_LEVEL
예제 #56
0
def read_input(port):
    """Read a value from a PFIO."""
    return PFIO.digital_read(port)
예제 #57
0
            # Camera warm-up time
            pose(1)
            time.sleep(1)
            print("1")
            camera.capture(file_name)
            pose(0)
            photolight(0)


p.init()
print("Ready")
test_lights()
ready(1)
while (True):
    try:
        button0 = p.digital_read(0)
        button1 = p.digital_read(1)
        button3 = p.digital_read(3)

        if button3 == 1:
            print("Button 4 gedrueckt!")
            print("shutdown in 7 Sekunden...")
            test_lights()
            subprocess.check_output("/sbin/shutdown -h now",
                                    stderr=subprocess.STDOUT,
                                    shell=True)
            sys.exit(0)
            time.sleep(1)
        if (button0 == 1) or (button1 == 1):
            ready(0)
            if (button0 == 1):
예제 #58
0
runonce=0
DebounceTeller=0

# status 1 = verwerkt
# status 2 = bezig met verwerken. 
# status 3 = nog te verwerken. 
# status 4 = prioriteit 
 
con = mdb.connect('localhost', 'pi', '', 'baaskarrendb'); 
cur = con.cursor() 


 
while True:

   if p.digital_read(0)== True: 
		time.sleep(0.5)
		DebounceTeller += 1
		if runonce ==0 and DebounceTeller ==2 :
			runonce =1
			DebounceTeller =0
			print "teller is hoog "
			with con: 
				p.digital_write(7,1)
				cur.execute("SELECT verwerkt FROM opdrachten WHERE status='2'  LIMIT 1") #waarde van de verwerkte aantallen uit de Database halen 
				try:
					teller = cur.fetchone()[0] # casten naar int 
					teller +=1		# er een bij optellen
					print teller
					cur.execute("UPDATE opdrachten SET verwerkt=%s WHERE status='2' LIMIT 1 " % (teller)) # waarde wegschrijven naar de Database
					
예제 #59
0
def event_interrupt(event):
	Pin_Value = pifacedigitalio.digital_read(event.pin_num, event.chip.hardware_addr)
	logging("Event Interrupt: Board: %d Pin: %d Value: %d Direction: %d" % (event.chip.hardware_addr,event.pin_num,Pin_Value,event.direction))
	event_process(int(event.chip.hardware_addr),int(event.pin_num),Pin_Value)
	return
 def test_flip_bit(self):
     # digital_read should flip 0 to 1
     self.assertEqual(pifacedigitalio.digital_read(0, 0), 1)