def getKey(self):
        for j in range(len(self.COLUMN)):
            RPIO.setup(self.COLUMN[j], RPIO.OUT)
            RPIO.output(self.COLUMN[j], RPIO.LOW)
         
        RPIO.setup(self.ROW, RPIO.IN, pull_up_down=RPIO.PUD_UP)
         
        rowVal = -1
        tmpRead = RPIO.input(self.ROW)
        if tmpRead == 0:
            rowVal = i

        if rowVal < 0 or rowVal > 3:
            self.exit()
            return
         
        for j in range(len(self.COLUMN)):
                RPIO.setup(self.COLUMN[j], RPIO.IN, pull_up_down=RPIO.PUD_DOWN)
         
        RPIO.setup(self.ROW, RPIO.OUT)
        RPIO.output(self.ROW, RPIO.HIGH)

        colVal = -1
        for j in range(len(self.COLUMN)):
            tmpRead = RPIO.input(self.COLUMN[j])
            if tmpRead == 1:
                colVal=j
                 
        if colVal < 0 or colVal > 3:
            self.exit()
            return
 
        self.exit()
        return self.KEYPAD[colVal]
Beispiel #2
0
    def read_gpio(self, dt):
        self.ready_timer -= dt
        if int(self.ready_timer) > 0:
            return

        self.win_text = ''
        p1 = RPIO.input(PIN_P1)
        p2 = RPIO.input(PIN_P2)

        if p1 and self.p1_state == 0:
            self.p1_state = 1
            self.p1 += 1
        elif not p1 and self.p1_state == 1:
            self.p1_state = 0

        if p2 and self.p2_state == 0:
            self.p2_state = 1
            self.p2 += 1
        elif not p2 and self.p2_state == 1:
            self.p2_state = 0
            
        if self.p1 >= self.score:
            self.win_text = 'Player 1 win !'
            self.ready_timer = 5.
            self.p1 = self.p2 = 0
        elif self.p2 >= self.score:
            self.win_text = 'Player 2 win !'
            self.ready_timer = 5.
            self.p1 = self.p2 = 0
Beispiel #3
0
    def getKey(self):
        for j in range(len(self.COLUMN)):
            RPIO.setup(self.COLUMN[j], RPIO.OUT)
            RPIO.output(self.COLUMN[j], RPIO.LOW)

        RPIO.setup(self.ROW, RPIO.IN, pull_up_down=RPIO.PUD_UP)

        rowVal = -1
        tmpRead = RPIO.input(self.ROW)
        if tmpRead == 0:
            rowVal = i

        if rowVal < 0 or rowVal > 3:
            self.exit()
            return

        for j in range(len(self.COLUMN)):
            RPIO.setup(self.COLUMN[j], RPIO.IN, pull_up_down=RPIO.PUD_DOWN)

        RPIO.setup(self.ROW, RPIO.OUT)
        RPIO.output(self.ROW, RPIO.HIGH)

        colVal = -1
        for j in range(len(self.COLUMN)):
            tmpRead = RPIO.input(self.COLUMN[j])
            if tmpRead == 1:
                colVal = j

        if colVal < 0 or colVal > 3:
            self.exit()
            return

        self.exit()
        return self.KEYPAD[colVal]
Beispiel #4
0
    def read_gpio(self, dt):
        self.ready_timer -= dt
        if int(self.ready_timer) > 0:
            return

        self.win_text = ''
        p1 = RPIO.input(PIN_P1)
        p2 = RPIO.input(PIN_P2)

        if p1 and self.p1_state == 0:
            self.p1_state = 1
            self.p1 += 1
        elif not p1 and self.p1_state == 1:
            self.p1_state = 0

        if p2 and self.p2_state == 0:
            self.p2_state = 1
            self.p2 += 1
        elif not p2 and self.p2_state == 1:
            self.p2_state = 0

        if self.p1 >= self.score:
            self.win_text = 'Player 1 win !'
            self.ready_timer = 5.
            self.p1 = self.p2 = 0
        elif self.p2 >= self.score:
            self.win_text = 'Player 2 win !'
            self.ready_timer = 5.
            self.p1 = self.p2 = 0
Beispiel #5
0
def measure():
    """Get a measurement."""
    
    # Set trigger to False (Low)
    RPIO.output(_RPIO_TRIGGER, False)
    
    # Allow module to settle
    time.sleep(0.5)
    
    # Send 10us pulse to trigger
    RPIO.output(_RPIO_TRIGGER, True)
    time.sleep(0.00001)
    RPIO.output(_RPIO_TRIGGER, False)
    start = time.time()
            
    while RPIO.input(_RPIO_ECHO)==0:
        start = time.time()
    
    while RPIO.input(_RPIO_ECHO)==1:
        stop = time.time()
    
    # Calculate pulse length
    elapsed = stop-start
    
    # Distance pulse travelled in that time is time
    # multiplied by the speed of sound (cm/s)
    # That was the distance there and back so halve the value
    distance = (elapsed * 34300) / 2
    
    return distance
def reading():
    # found that the sensor can crash if there isn't a delay here
    # no idea why. If you have odd crashing issues, increase delay
    time.sleep(START_DELAY)

    RPIO.output(TRIG, True)
    time.sleep(PING_DELAY)
    RPIO.output(TRIG, False)

    before_signal = None
    after_signal = None

    while not RPIO.input(ECHO):
        before_signal = time.time()

    while RPIO.input(ECHO):
        after_signal = time.time()

    if not before_signal or not after_signal:
        return None

    time_passed = after_signal - before_signal
    distance = time_passed * SOUND_SPEED_Q

    return distance
Beispiel #7
0
    def test3_input(self):
        logging.info(" ")
        logging.info(" ")
        logging.info("=== INPUT TESTS ===")
        with self.assertRaises(RPIO._GPIO.InvalidChannelException):
            RPIO.setup(5, RPIO.IN)
        with self.assertRaises(RPIO._GPIO.InvalidChannelException):
            RPIO.setup(0, RPIO.IN)
        with self.assertRaises(RPIO._GPIO.InvalidChannelException):
            RPIO.setup(32, RPIO.IN)

        RPIO.setup(GPIO_IN, RPIO.IN)
        logging.info(" ")
        logging.info("--------------------------------------")
        logging.info("Input from GPIO-%s w/ PULLOFF:  %s", \
                GPIO_IN, RPIO.input(GPIO_IN))
        RPIO.set_pullupdn(GPIO_IN, RPIO.PUD_UP)
        logging.info("Input from GPIO-%s w/ PULLUP:   %s", \
                GPIO_IN, RPIO.input(GPIO_IN))
        RPIO.set_pullupdn(GPIO_IN, RPIO.PUD_DOWN)
        logging.info("Input from GPIO-%s w/ PULLDOWN: %s", \
                GPIO_IN, RPIO.input(GPIO_IN))
        logging.info("--------------------------------------")
        logging.info(" ")
        RPIO.set_pullupdn(GPIO_IN, RPIO.PUD_OFF)
Beispiel #8
0
    def test3_input(self):
        logging.info(" ")
        logging.info(" ")
        logging.info("=== INPUT TESTS ===")
        with self.assertRaises(RPIO._GPIO.InvalidChannelException):
            RPIO.setup(5, RPIO.IN)
        with self.assertRaises(RPIO._GPIO.InvalidChannelException):
            RPIO.setup(0, RPIO.IN)
        with self.assertRaises(RPIO._GPIO.InvalidChannelException):
            RPIO.setup(32, RPIO.IN)

        RPIO.setup(GPIO_IN, RPIO.IN)
        logging.info(" ")
        logging.info("--------------------------------------")
        logging.info("Input from GPIO-%s w/ PULLOFF:  %s", \
                GPIO_IN, RPIO.input(GPIO_IN))
        RPIO.set_pullupdn(GPIO_IN, RPIO.PUD_UP)
        logging.info("Input from GPIO-%s w/ PULLUP:   %s", \
                GPIO_IN, RPIO.input(GPIO_IN))
        RPIO.set_pullupdn(GPIO_IN, RPIO.PUD_DOWN)
        logging.info("Input from GPIO-%s w/ PULLDOWN: %s", \
                GPIO_IN, RPIO.input(GPIO_IN))
        logging.info("--------------------------------------")
        logging.info(" ")
        RPIO.set_pullupdn(GPIO_IN, RPIO.PUD_OFF)
Beispiel #9
0
def front_reject():
    """
    Reject routine that diverts the paper path so that the ballot
    comes out front in accordance with the STAR-Vote specifications.
    """
    # Move the servo
    divert_servo()
    time.sleep(0.015)

    # Rotate the motor
    t0 = int(round(time.time() * 1000))
    t = t0
    while (t - t0 < fullFeed):
        # read digital input from either of the sensors
        t = int(round(time.time() * 1000))
        opt1 = RPIO.input(OptInt1)
        opt2 = RPIO.input(OptInt2)
        if (opt1 or opt2):
            # if paper is still on the way, keep running the loop
            t0 = int(round(time.time() * 1000))
        
        RPIO.output(MotorOut, True)
    
    # fully fed -> stop the motor
    RPIO.output(MotorOut, False)
    time.sleep(1.5) # sleep to ignore spurious input
    
    # straighten servo before jumping into main loop again
    straighten_servo()
Beispiel #10
0
def accept_ballot():
    """
    Accept routine that runs the motor until the paper is completely put into the box
    """
    
    # move servo
    straighten_servo()
    time.sleep(0.015)
    
    # run motor for fullFeed seconds
    t0 = int(round(time.time() * 1000))
    t = t0
    while (t - t0 < fullFeed):
        # read digital input from either of the sensors
        t = int(round(time.time() * 1000))
        opt1 = RPIO.input(OptInt1)
        opt2 = RPIO.input(OptInt2)
        if (opt1 or opt2):
            # if paper is still on the way, keep running the loop
            t0 = int(round(time.time() * 1000))
        
        RPIO.output(MotorOut, True)
    
    # fully fed -> stop the motor
    RPIO.output(MotorOut, False)
    time.sleep(2) # sleep to ignore spurious input
Beispiel #11
0
 def reset_state(self):
     """ Determines the proper state when the motor is stopped"""
     if GPIO.input(inputs['upper']):
         self.state = OPEN
     elif GPIO.input(inputs['lower']):
         self.state = CLOSED
     else: 
         self.state = STOPPED
 def check_distance(self):
     RPIO.output(TRIG, 1)
     time.sleep(0.00001)
     RPIO.output(TRIG, 0)
     while RPIO.input(ECHO) == 0:
         start = time.time()
     while RPIO.input(ECHO) == 1:
         stop = time.time()
     # Print distance to object in santimeters. Sound speed = 340 m/s
     return (stop - start) * 17000
Beispiel #13
0
 def on_collision(self, gpio_id, value):
     """"""
     result = value 
     if gpio_id == self.SW1_PIN and RPIO.input(self.SW2_PIN):
            result +=2
     elif gpio_id == self.SW2_PIN:
         result *= 2
         if RPIO.input(self.SW1_PIN):
            result +=1
     self.send(encode(common.ID_BUMPER, result))
def main():
    RPIO.setup(6, RPIO.IN)
    RPIO.setup(13, RPIO.IN)
    RPIO.setup(26, RPIO.IN)
    while True:
        if RPIO.input(6):
            ResetPins()
        if RPIO.input(13):
            QuickPins()
        if RPIO.input(26):
            break
Beispiel #15
0
def receiveBit(pin):
	GPIO.setup(pin, GPIO.IN);
	assert GPIO.input(pin) == False, "Sensor did not pull line low before bit transmission";
	
	time.sleep(0.000077);

	if GPIO.input(pin):
		time.sleep(0.000041);
		return "1";
	else:
		return "0";
Beispiel #16
0
def selftest():
	RPIO.output(outPin, False)
	r1 = RPIO.input(inPin)

	RPIO.output(outPin, True)
	r2 = RPIO.input(inPin)

	if r1 != False or r2 != True:
		raise Exception("Selftest failed. Readout should have been (False, True), but was (", r1, ", ", r2, ").")
	else:
		print("Selftest ok.")
Beispiel #17
0
	def __init__(self,pinC):
		self.c = pinC #write pin
		print encoders.a,encoders.b
		RPIO.setup(encoders.a, RPIO.IN, pull_up_down=RPIO.PUD_DOWN)
		RPIO.setup(encoders.b, RPIO.IN, pull_up_down=RPIO.PUD_DOWN)
		self.S1 = RPIO.input(encoders.a)
		self.S2 = RPIO.input(encoders.b)
		self.state = self.S1 + 2*self.S2
		self.start_time = time.clock()
		self.steps_for_speed = 0
		self.distance = 0
		encoders.connected_encoders.append(self)
Beispiel #18
0
    def is_button_up(self):
        """Return True when the box button has transitioned from down to up (i.e.
		the button was pressed)."""
        old_state = self.button_state
        self.button_state = RPIO.input(config.BUTTON_PIN)
        # Check if transition from down to up
        if old_state == config.BUTTON_DOWN and self.button_state == config.BUTTON_UP:
            # Wait 20 milliseconds and measure again to debounce switch.
            time.sleep(20.0 / 1000.0)
            self.button_state = RPIO.input(config.BUTTON_PIN)
            if self.button_state == config.BUTTON_UP:
                return True
        return False
Beispiel #19
0
def selftest():
	RPIO.output(outPin, False)
	r1 = RPIO.input(inPin)

	RPIO.output(outPin, True)
	r2 = RPIO.input(inPin)

	if r1 != False or r2 != True:
		msg = "Selftest failed. Readout should have been (False, True), but was (", r1, ", ", r2, ")."
		logging.error(msg)
		raise Exception(msg)
	else:
		logging.info("Selftest ok.")
Beispiel #20
0
def init(pin):
	GPIO.setup(pin, GPIO.OUT);
	GPIO.output(pin, GPIO.LOW);
	time.sleep(0.002);
	GPIO.output(pin, GPIO.HIGH);
	time.sleep(0.000030);
	GPIO.setup(pin, GPIO.IN);
	time.sleep(0.000020);
	assert GPIO.input(pin) == True, "Sensor did not pull line low after host start signal";
	time.sleep(0.000080);
	assert GPIO.input(pin) == False, "Sensor did not pull line high after host start signal";
	time.sleep(0.000060);
	return;
	def is_button_up(self):
		"""Return True when the box button has transitioned from down to up (i.e.
		the button was pressed)."""
		old_state = self.button_state
		self.button_state = RPIO.input(config.BUTTON_PIN)
		# Check if transition from down to up
		if old_state == config.BUTTON_DOWN and self.button_state == config.BUTTON_UP:
			# Wait 20 milliseconds and measure again to debounce switch.
			time.sleep(20.0/1000.0)
			self.button_state = RPIO.input(config.BUTTON_PIN)
			if self.button_state == config.BUTTON_UP:
				return True
		return False
Beispiel #22
0
    def read_gpio(self, dt):
        p1 = RPIO.input(PIN_P1)
        p2 = RPIO.input(PIN_P2)

        self.player1.update(dt, p1)
        self.player2.update(dt, p2)

        for bonus in self.bonus[:]:
            for player in self.players:
                if bonus.collide_player(player):
                    bonus.use(player)
                    self.bonus.remove(bonus)
                    self.remove_widget(bonus)
                    break
    def __init__( self, firstPin, secondPin ):

        self.firstPin = firstPin
        self.secondPin = secondPin
        RPIO.setup( self.firstPin, RPIO.IN )
        RPIO.setup( self.secondPin, RPIO.IN )
        self.firstPinState = RPIO.input( self.firstPin )
        self.secondPinState = RPIO.input( self.secondPin )
        
        RPIO.add_interrupt_callback( self.firstPin, self.encoderCallback )
        RPIO.add_interrupt_callback( self.secondPin, self.encoderCallback )
        
        self.tickCount = 0
        self.edgeMissed = False
Beispiel #24
0
    def measure_distance(self):
        """Returns the distance (in meters) to the object being looked at.

        Probably should only happen in a thread due to all the sleeping
        """
        if not self._rangefinder_settled:
            # let the sensor settle
            GPIO.output(self._gpios['echo_trigger'], False)
            time.sleep(2)
            self._rangefinder_settled = True

        # 10 us pulse
        GPIO.output(self._gpios['echo_trigger'], True)
        time.sleep(0.00001)
        GPIO.output(self._gpios['echo_trigger'], False)
        # interrupt might be better?
        pulse_start = time.time()
        cnt = 0
        while not GPIO.input(self._gpios['echo']):
            pulse_start = time.time() # maybe pass would be better? might actually more cpu though...
            cnt += 1
            if cnt > 20000:
                return 999999999
        # we got a pulse, measure it's width by polling until it goes low
        # again.
        cnt = 0
        pulse_end = time.time()
        while GPIO.input(self._gpios['echo']):
            pulse_end = time.time()
            cnt += 1
            if cnt > 20000:
                return 999999999

        pulse_duration = pulse_end - pulse_start
        sound_mps = 343.0         # speed of sound: 343 m/s
        distance = sound_mps * pulse_duration
        # and the pulse width is actually the time it takes to get to the
        # object *and back*, so we need to divide by two to get just the
        # distance:
        distance /= 2.0
        # Because the datasheet says:
        #
        #   we suggest to use over 60ms measurement cycle, in order to
        #   prevent trigger signal to the echo signal.
        #
        # We'll use 80ms to be safe
        time.sleep(.08)
        return distance
Beispiel #25
0
 def fn(pin, *args, **kwargs):
     dbg("ifhigh %s "% (pin))
     if GPIO.input(pin):
         dbg("pin %s high, calling callback" %pin)
         return cb(pin, *args, **kwargs)
     dbg("pin %s low, not calling" %pin)
     self.notify_enrolled(self.status())
Beispiel #26
0
 def get_noise(self):
     self.cnt += 1
     self.noise = RPIO.input(self.PIN)
     print(self.noise, "noise dal sensore")
     if self.noise == False:
         self.cnt = 0
     return self.noise
Beispiel #27
0
def main_loop():
    global count, motor_on

    import RPIO as GPIO
    GPIO.add_interrupt_callback(BUTTON_GPIO, button_trigger, edge='both', threaded_callback=True)
    GPIO.wait_for_interrupts(threaded=True)  # , epoll_timeout=.25)

    try:

        while True:
            GPIO.output(LED_GPIO, not GPIO.input(LED_GPIO))
            time.sleep(.5)
            count += 1

            # log.debug("button val: {}".format(GPIO.input(BUTTON_GPIO)))

            if not motor_on:
                if runtime.runtime.is_feed_time(set_next_run=True):  # this WILL bump the next feed time
                    log.debug("feed time and not motor")
                    count = 1
                    motor_on = True
                    GPIO.output(RELAY_GPIO, True)

    except Exception as e:
        log.exception("Exception during run loop? {}".format(e))
	def __init__(self):
		# Initialize lock servo and button.
		self.servo = PWM.Servo()
		RPIO.setup(config.BUTTON_PIN, RPIO.IN)
		# Set initial box state.
		self.button_state = RPIO.input(config.BUTTON_PIN)
		self.is_locked = None
Beispiel #29
0
 def __init__(self):
     # Initialize lock servo and button.
     self.servo = PWM.Servo()
     RPIO.setup(config.BUTTON_PIN, RPIO.IN)
     # Set initial box state.
     self.button_state = RPIO.input(config.BUTTON_PIN)
     self.is_locked = None
Beispiel #30
0
    def run(self):
        """
        This is where the work happens.
        """
        time_base = time.time()
        self.keep_running = True

        while self.keep_running:
            time.sleep(self.time_pause)

            time_now = time.time()

            if self.time_interval <= 0:
                # Off.
                RPIO.output(self.pin, False)

            elif time_now - time_base > self.time_interval:
                time_base = time_now

                # Reverse LED state.
                value = RPIO.input(self.pin)
                RPIO.output(self.pin, not value)

            # Repeat loop.

        print('Blinker exit: %d' % self.pin)
        RPIO.output(self.pin, False)
Beispiel #31
0
def gpio_callback_1(gpio_id, val):
    #   global lastTime1, dMax1, dMin1, dSum1, dCount1, dFirst1
    #   now1 = datetime.datetime.now()
    #   dstr1 = str(now1.strftime("%H:%M:%S.%f"))
    #   nowTime1 = time.time()
    #   if (dFirst1 == 1):
    #      dFirst1 = 0;
    #      lastTime1 = nowTime1;
    #   else:
    #      dTime1 = nowTime1 - lastTime1
    #      lastTime1 = nowTime1
    #      if (dTime1 > dMax1):
    #         dMax1 = dTime1
    #      if (dTime1 < dMin1):
    #         dMin1 = dTime1
    #      dCount1 += 1
    #      dSum1 += dTime1
    #stampa ogni tic in uscita da (3) su 555
    input_value_7 = RPIO.input(INTfirst)
    if input_value_7 == True:
        print "ALTO--->1"
        RPIO.output(LedColored, True)
    else:
        print "BASSO--->0"
        RPIO.output(LedColored, False)
    print(
        "INTfotores: ---------------> GPIO"
    ), gpio_id  #: %s at %s delta: %08.6f" % (gpio_id, val, dstr1, dTime1))
Beispiel #32
0
def pulse_tdo(tck, tdo):
    if(DELAY):
        sleep(0.000005)
    RPIO.output(tck, 0)
    tdo_read = RPIO.input(tdo)
    RPIO.output(tck, 1)
    return tdo_read
Beispiel #33
0
def input_loop():
    """
    The main loop for checking the optical interrupters and
    controlling motors
    """

    # read in the values
    while (True):
        opt1 = RPIO.input(OptInt1)
        opt2 = RPIO.input(OptInt2)
        exp = RPIO.input(ExpButton)
        if (opt1 or opt2):
            if (exp):
                front_reject()
            else:
                accept_ballot()
def gpio_callback_1(gpio_id, val):
#   global lastTime1, dMax1, dMin1, dSum1, dCount1, dFirst1
#   now1 = datetime.datetime.now()
#   dstr1 = str(now1.strftime("%H:%M:%S.%f"))
#   nowTime1 = time.time()
#   if (dFirst1 == 1):
#      dFirst1 = 0;
#      lastTime1 = nowTime1;
#   else:
#      dTime1 = nowTime1 - lastTime1
#      lastTime1 = nowTime1      
#      if (dTime1 > dMax1):
#         dMax1 = dTime1
#      if (dTime1 < dMin1):
#         dMin1 = dTime1
#      dCount1 += 1
#      dSum1 += dTime1
      #stampa ogni tic in uscita da (3) su 555
      input_value_7 = RPIO.input(INTfirst)
      if input_value_7==True:
      	print "ALTO--->1"
      	RPIO.output(LedColored,True)
      else:
      	print "BASSO--->0"
      	RPIO.output(LedColored,False)
      print("INTfotores: ---------------> GPIO"), gpio_id#: %s at %s delta: %08.6f" % (gpio_id, val, dstr1, dTime1))
Beispiel #35
0
    def run(self):
        """
        This is where the work happens.
        """
        time_base = time.time()
        self.keep_running = True

        while self.keep_running:
            time.sleep(self.time_pause)

            time_now = time.time()

            if self.time_interval <= 0:
                # Off.
                RPIO.output(self.pin, False)

            elif time_now - time_base > self.time_interval:
                time_base = time_now

                # Reverse LED state.
                value = RPIO.input(self.pin)
                RPIO.output(self.pin, not value)

            # Repeat loop.

        print('Blinker exit: %d' % self.pin)
        RPIO.output(self.pin, False)
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
    if ((adcnum > 7) or (adcnum < 0)):
        return -1
    RPIO.output(cspin, True)

    RPIO.output(clockpin, False)  # start clock low
    RPIO.output(cspin, False)  # 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):
            RPIO.output(mosipin, True)
        else:
            RPIO.output(mosipin, False)
        commandout <<= 1
        RPIO.output(clockpin, True)
        RPIO.output(clockpin, False)

    adcout = 0
    # read in one empty bit, one  null bit, and 10 ADC bits
    for i in range(12):
        RPIO.output(clockpin, True)
        RPIO.output(clockpin, False)
        adcout <<= 1
        if (RPIO.input(misopin)):
            adcout |= 0x1

    RPIO.output(cspin, True)
    adcout >>= 1  # first bit is 'null' and gets dropped
    return adcout
Beispiel #37
0
def collision():
	global distance
	time.sleep(0.055)
	RPIO.output(7, True)
	time.sleep(0.0001)
	RPIO.output(7, False)
	start = time.time()
	while not RPIO.input(8):
	        start = time.time()
	while RPIO.input(8):
	        stop = time.time()
	distance = ((stop - start) * 34000) / 2
	if distance >= 16:
		return False
	else:
		return True
Beispiel #38
0
def on_q7_both(gpio_id, value):
	# we get called here for both rise & fall
	# so figure out if we're falling and if so dish it off
	if (RPIO.input(gpio_id) == 0):
		# we're falling so call falling method
		on_q7_falling(gpio_id, value)
	else:
		on_q7_rising(gpio_id, value)
Beispiel #39
0
def charge_time():
    GPIO.setup(b_pin, GPIO.IN)
    GPIO.setup(a_pin, GPIO.OUT)
    count = 0
    GPIO.output(a_pin, True)
    while not GPIO.input(b_pin):
        count = count + 1
    return count
Beispiel #40
0
	def on_q7_rising(self, gpio_id, value):
		
		# we could get called after we're done counting, so ignore that data
		if (self.ctrRising < 1000):
			# we need to scan for the led data
			for e in self.indx:
				self.dataq7[e] = self.dataq7[e] + RPIO.input(e)
				if (e == 23):
					self.dataq7[e] = 0
Beispiel #41
0
def RCtime (RCpin):
	reading = 0
	RPIO.setup(RCpin, RPIO.OUT)
	RPIO.output(RCpin, RPIO.LOW)
	time.sleep(0.1)

	RPIO.setup(RCpin, RPIO.IN)
	while (RPIO.input(RCpin) == RPIO.LOW):
		reading += 1
	return reading
Beispiel #42
0
 def get_range(self):
     mean = 10
     distance = 0
     for i in range(mean):
         RPIO.setup(self.TRIGGER_PIN, RPIO.OUT)
         RPIO.output(self.TRIGGER_PIN, True)
         time.sleep(0.0001)
         RPIO.output(self.TRIGGER_PIN, False)
         RPIO.setup(self.TRIGGER_PIN, RPIO.IN)
         timeout = 10000
         while RPIO.input(self.TRIGGER_PIN) != True and timeout > 0:
             timeout = timeout - 1
         start = time.time()
         timeout = 10000
         while RPIO.input(self.TRIGGER_PIN) != False and timeout > 0:
             timeout = timeout - 1
         pulse_len = time.time() - start
         distance += pulse_len / 0.000058
     return distance/mean
Beispiel #43
0
	def update(self):
		#correponding C pin to output
		#corresponding C pin to HIGH
		RPIO.setup(self.c, RPIO.OUT)
		RPIO.output(self.c, True)
		time.sleep(0.005)
		self.newS1 = RPIO.input(encoders.a)
		self.newS2 = RPIO.input(encoders.b)
		RPIO.setup(self.c, RPIO.IN)
		#after reading, go back to high impedance, should check if this is pull-down or at least floating
		self.new_state = self.newS1 + 2*self.newS2 		
		self.rotation = self.fsm(self.state,self.new_state) #checks if the state is different from before
		self.distance+=self.rotation
		if time.clock()-encoder.DEL_TIME>self.start_time:
			self.speed = self.steps_for_speed/encoder.DEL_TIME
			self.steps_for_speed = 0
			self.start_time = time.clock()
		else: 
			self.steps_for_speed += self.rotation
def track_sensors(channels):
    activated = []
    for channel in channels:
        old_time = datetime.now().microsecond
        GPIO.setup(channel, GPIO.IN)
        while GPIO.input(channel) == GPIO.HIGH:
            datetime.delay(0.001)
        new_time = datetime.now().microsecond
        elapsed = new_time - old_time
        if elapsed < upper_time and elapsed > lower_time:
            activated.append(channel)

    return activated
Beispiel #45
0
    def encoderHandler_callback(self, port_channel, newChannelAValue):
        # handler routine of LOW to HIGH transition on channel A
        #global encoderCounter
        #global lastEncoded

        # read input from channel A
        newChannelAValue = RPIO.input(self.port_channelA)
        # read input from channel B
        newChannelBValue = RPIO.input(self.port_channelB)

        encoded = (newChannelAValue << 1) | newChannelBValue
        sumEncoded = (self.lastEncoded << 2) | encoded

        if sumEncoded == 0b1101 or sumEncoded == 0b0100 or sumEncoded == 0b0010 or sumEncoded == 0b1011:
            self.encoderCounter += 1  # increment the counter value of the encoder

        if sumEncoded == 0b1110 or sumEncoded == 0b0111 or sumEncoded == 0b0001 or sumEncoded == 0b1000:
            self.encoderCounter -= 1  # decrement the counter value of the encoder

        self.lastEncoded = encoded

        return True
Beispiel #46
0
    def __gpio_callback(self, gpio_id, val):

        a = RPIO.input(self.channel_a)
        b = RPIO.input(self.channel_b)

        current = (a << 1) + b

        val = ((self.last_val << 2) + current) & 0b1111

        delta = RotaryEncoder.lut[val]
        if delta:
            s_time = time.time()
            if not self.last:
                self.last = s_time
                self.step(delta)
            elif (s_time - self.last) * 1000 > self.debounce:
                # print "\nA: %d B: %d\tState: %s\t%s\tDelta: %d\t%5f" % (
                #     a, b, "{0:b}".format(val), val, delta, (s_time - self.last) * 1000)
                self.last = s_time
                self.step(delta)

        self.last_val = current
Beispiel #47
0
 def json_data(self):
     ret = {'version': PIO_VERSION}
     j = []
     for i in range(0, len(RELAYS)):
         j.append(1)
         if GPIO.input(RELAYS[i]):
             j[i] = 0
         else:
             j[i] = 1
     if len(RELAYS):
         ret['relays'] = j
     ret['pwm'] = channels
     self.request.send(json.dumps(ret) + "\n")
Beispiel #48
0
    def medir(self):
        #disparar
        GPIO.output(self.TRIG_PIN, 1)
        time.sleep(0.00001)
        GPIO.output(self.TRIG_PIN, 0)
        #medir el tiempo
        pulse_start = time.time()
        while GPIO.input(self.ECHO_PIN) == 1:
            pulse_end = time.time()

        #duracion
        pulse_duration = pulse_end - pulse_start
        distance = round(pulse_duration * 17150, 2)

        return distance
Beispiel #49
0
    def _wscb_sample(self, port, message):
        """ Request a single sample

        :param channel: The websocket channel containing the port to sample (io0-3)
        :type channel: str
        :param message: The message received over the wire
        :type message: dict -- should be empty

        """
        port = port.split('.')[2]
        logging.debug("sample request in port %s" % port)

        boolval = RPIO.input(self.PORTS[port]['bcm'])

        self.send_event(port + ".sample",
                        { 'value' : boolval, 'raw_value': int(boolval) } )
 def run(self):
     CloudLog.log(self._component, "Running.")
     while self.state == "READY":
         try:
             previous_doorOpen = self._doorOpen
             import RPIO
             RPIO.setup(23, RPIO.IN, pull_up_down=RPIO.PUD_UP)
             self._doorOpen = RPIO.input(23)
             if previous_doorOpen != self._doorOpen:
                 if self._doorOpen is True:
                     self._announce("OPEN")
                 else:
                     self._announce("CLOSED")
             interval = 0.2
         except Exception, e:
             CloudLog.error(self._component, "Error in run loop", e)
             if interval < 10:
                 interval += interval
         time.sleep(interval)
Beispiel #51
0
def getgpio(pin):
	if (str(pin) in callbacks):
		return False
	if (pin < 32 and pin in goodgpios):
		if (pin not in gpiostate):
			GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
		try:
			state = GPIO.input(pin)
		except Exception as e:
			state = gpiostate[pin]
	elif (pin >= 32):
		mcpi = int(pin / 32) - 1
		pin = pin % 16
		if(mcpi in mcps and type(mcps[mcpi][3]).__name__=="MCP23017" and mcps[mcpi][3].connected == 1):
			state = mcps[mcpi][3].input(pin)
		else:
			return -1
	else:
		return -1
	gpiostate[pin] = state
	return state
Beispiel #52
0
 def _runLoop(self, params):
     CloudLog.log(self._component, "Running.")
     while self.running:
         try:
             previous_doorOpen = self._doorOpen
             import RPIO
             RPIO.setup(23, RPIO.IN, pull_up_down=RPIO.PUD_UP)
             self._doorOpen = RPIO.input(23)
             if previous_doorOpen != self._doorOpen:
                 if self._doorOpen is True:
                     self.state = "OPEN"
                     if self._controller.state == "AWAY":
                         self._controller.executeCommandByName("HOME")
                 else:
                     self.state = "CLOSED"
                 CloudLog.track("FRONT_DOOR", self.state)
                 # self._component.status(key="door", value=self.state)
             interval = 0.5
         except Exception, e:
             CloudLog.error(self._component, "Error in run loop", e)
             if interval < 10:
                 interval += interval
         time.sleep(interval)
Beispiel #53
0
 def get(self):
     return RPIO.input(self.pin)
Beispiel #54
0
dFirst1 = 1

dMax2 = 0
dMin2 = 2
dSum2 = 0
dCount2 = 0
dAvg2 = 0
dFirst2 = 1

# set up input channel with pull-up control. Can be
# PUD_UP, PUD_DOWN or PUD_OFF (default)
RPIO.setup(INT11, RPIO.IN, pull_up_down=RPIO.PUD_UP)
RPIO.setup(INT9, RPIO.IN, pull_up_down=RPIO.PUD_UP)

# read input from gpio
input_value_11 = RPIO.input(INT11)
input_value_4 = RPIO.input(INT9)


#Definizione della callback per impulsi in uscita da pin 3 su 555 (collegato a GPIO 11)
def gpio_callback_1(gpio_id, val):
    global lastTime1, dMax1, dMin1, dSum1, dCount1, dFirst1
    now1 = datetime.datetime.now()
    dstr1 = str(now1.strftime("%H:%M:%S.%f"))
    nowTime1 = time.time()
    if (dFirst1 == 1):
        dFirst1 = 0
        lastTime1 = nowTime1
    else:
        dTime1 = nowTime1 - lastTime1
        lastTime1 = nowTime1