Example #1
0
	def scanQ(self):
		# steps (1) and (2) before reading GPIOs
		self.__preRead()
		
		# (3) scan rows for pushed key/button
		rowHi=1
		while rowHi==1:
			for i in range(len(self.row)):
				tmpRead=wiringpi.digitalRead(self.row[i])
				if tmpRead==0:
					rowHi=0
					rowVal=i

		# (4) after finding which key/button from the row scans, convert columns to input
		for j in range(len(self.col)):
				wiringpi.pinMode(self.col[j],INPUT)

		# (5) switch the i-th row found from scan to output
		wiringpi.pinMode(self.row[rowVal],OUTPUT)
		wiringpi.digitalWrite(self.row[rowVal],HIGH)

		# (6) scan columns for still-pushed key/button
		colLo=0
		while colLo==0:
				for j in range(len(self.col)):
						tmpRead=wiringpi.digitalRead(self.col[j])
						if tmpRead==1:
							colLo=1
							colVal=j

		# reinitialize used GPIOs
		self.__postRead()

		# (7) return the symbol of pressed key from keyPad mapping
		return self.keyPad[rowVal][colVal]
Example #2
0
def pulse_in(gpio, state, timeout):
    tn = datetime.datetime.now()
    t0 = datetime.datetime.now()
    micros = 0

    while wp.digitalRead(gpio) != state:
        tn = datetime.datetime.now()
        if tn.second > t0.second:
            micros = 1000000L
        else:
            micros = 0
        micros += tn.microsecond - t0.microsecond
        if micros > timeout:
            return 0

    t1 = datetime.datetime.now()

    while wp.digitalRead(gpio) == state:
        tn = datetime.datetime.now()
        if tn.second > t0.second:
            micros = 1000000L
        else:
            micros = 0
        micros = micros + (tn.microsecond - t0.microsecond)
        if micros > timeout:
            return 0

    if tn.second > t1.second:
        micros = 1000000L
    else:
        micros = 0
    micros = micros + (tn.microsecond - t1.microsecond)

    return micros
Example #3
0
def pinBlinkInterval(pin, Timeout):
    # initialisation compteur
    startTime = getStartTime()
    
    initPinState = GPIO.digitalRead(pin)
    startCounting=False
    firstPulse = False
    pulse = 0
    ## récupération d'un cycle
    while True :
        # gestion du timeout
        if ( isTimeoutExpired(startTime, Timeout) ):
            return -1
            
        #time.sleep(0.01)
        # lecture de la pin
        if (startCounting == False ):
            if (GPIO.digitalRead(pin) != initPinState):
                startCounting = True
                pulse = getStartTime()
        else:
            if (firstPulse == False):
                if (GPIO.digitalRead(pin) == initPinState):
                    firstPulse = True
            if (firstPulse and GPIO.digitalRead(pin) != initPinState):
                return getStartTime() - pulse
Example #4
0
def poll():
	if wiringpi.digitalRead(WIN):
		print 'win'
	elif wiringpi.digitalRead(LOSE):
		print 'lose'
	else:
		print 'playing'
    def updateValue(self):
	if Globals.globSimulate:
	    val = (self.values[-1][1] if len(self.values) > 0 else 0) + random.randint(-10, 10)
	else:
	    # Send 10us pulse to trigger
	    wiringpi.digitalWrite(self.pinTrigger, 1)
	    time.sleep(0.00001)
	    wiringpi.digitalWrite(self.pinTrigger, 0)
	    start = time.time()
	    stop = 0

	    while wiringpi.digitalRead(self.pinEcho)==0:
	      start = time.time()

	    while wiringpi.digitalRead(self.pinEcho)==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)
	    distance = elapsed * 34300

	    # That was the distance there and back so halve the value
	    val = distance / 2


	if val < 0:
	    val = 0

	currtime = int(time.time() * 1000) # this is milliseconds so JavaScript doesn't have to do this
	self.values.append([currtime, val])
	self.values = self.values[-MAXVALUES:]
	self.emit("DistanceSensor", self)
Example #6
0
def hot_wire(enable):
    if enable:
        logging.info('Heating wire enabled Temp={0:0.1f}* < Temp_min={1:0.1f}'.format(temperature, TEMP_MIN))
	wiringpi.pinMode(PIN_WIRE, ON)
	logging.debug(wiringpi.digitalRead(PIN_WIRE))
    else:
        logging.info('Heating wire disabled Temp={0:0.1f}* > Temp_max={1:0.1f}'.format(temperature, TEMP_MAX))
	wiringpi.pinMode(PIN_WIRE, OFF)
	logging.debug(wiringpi.digitalRead(PIN_WIRE))
    return;
Example #7
0
def fan(enable):
    if enable:
        logging.info('fan enabled')
	wiringpi.pinMode(PIN_FAN, ON)
	logging.debug(wiringpi.digitalRead(PIN_FAN))
	time.sleep(240)
	logging.info('fan disabled')
	wiringpi.pinMode(PIN_FAN, OFF)
	logging.debug(wiringpi.digitalRead(PIN_FAN))
    else:
	logging.info('fan disabled')
	wiringpi.pinMode(PIN_FAN, OFF)
	logging.debug(wiringpi.digitalRead(PIN_FAN))
    return;
Example #8
0
    def read_switch(self, switch):
        if not WIRING_PI:
            return False

        pin = self.switch_pin[switch]

        return wiringpi.digitalRead(pin) > 0
Example #9
0
def read_adc(adcnum, sCon):

    if ((adcnum > 7) or (adcnum < 0)):
        return -1
    wiringpi.digitalWrite(sCon.cspin, 1)
    wiringpi.digitalWrite(sCon.clkpin, 0)  # start clock low
    wiringpi.digitalWrite(sCon.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):
            wiringpi.digitalWrite(sCon.mosipin, 1)
        else:
            wiringpi.digitalWrite(sCon.mosipin, 0)
        commandout <<= 1
        wiringpi.digitalWrite(sCon.clkpin, 1)
        wiringpi.digitalWrite(sCon.clkpin, 0)

    adcout = 0
    # read in one empty bit, one null bit and 10 ADC bits
    for i in range(12):
        wiringpi.digitalWrite(sCon.clkpin, 1)
        wiringpi.digitalWrite(sCon.clkpin, 0)
        adcout <<= 1
        if (wiringpi.digitalRead(sCon.misopin)):
            adcout |= 0x1
    wiringpi.digitalWrite(sCon.cspin, 1)

    adcout >>= 1       # first bit is 'null' so drop it
    return adcout
def WaitForCTS():
    # continually monitor the selected GPIO pin and wait for the line to go low
    # print ("Waiting for CTS")     # Added for debug purposes
    while wiringpi2.digitalRead(GPIO_PIN):
        # do nothing
        time.sleep(0.001)
    return
Example #11
0
    def run(self):
        motionFirstDetectedTime = None
        SLEEP_TIME = 0.5

        # Set up the GPIO input for motion detection
        PIR_PIN = 18
        wiringpi.wiringPiSetupSys()
        wiringpi.pinMode(PIR_PIN, wiringpi.INPUT)

        # Loop through and detect motion
        while True:
            if wiringpi.digitalRead(PIR_PIN):
                if motionFirstDetectedTime is None:
                    motionFirstDetectedTime = datetime.now()
                    print('Motion detected at: ' + str(motionFirstDetectedTime))

            # Do we need to send out a notification?
            now = datetime.now()
            if (motionFirstDetectedTime is not None) and (now - motionFirstDetectedTime) > timedelta (minutes = 1):
                print('Sending out notification now!')
                motiondate = datetime.strftime(motionFirstDetectedTime, '%Y-%m-%d %H:%M:%S')
                msg = self.message + ': ' + motiondate 
                self._send_email(msg)

                # reset state
                motionFirstDetectedTime = None

            time.sleep(SLEEP_TIME)
	def getButtonStatus(self):
		ret = self.BUTTON_NONE
		if self.isRun:
			# excute, if run
			val = wiringpi.digitalRead(self.pinButton)
			ret = self.BUTTON_ON if val == wiringpi.HIGH else self.BUTTON_OFF
		return ret		
Example #13
0
 def run(self):
     while not self.quit:
         time.sleep(1)
         print('!')
         if self.alarm_mode:
             movement = wp.digitalRead(0) != 0
             if movement:
                 self.turn_all_on_off(True, notify=True)
def garage_state():
    doorState = wiringpi.digitalRead(25)
    if doorState == 1: 
		return "open"
    elif doorState == 0:
		return "closed"
    else:
		return "error"
Example #15
0
  def __init__(self, pinNumber):
    threading.Thread.__init__(self)

    self.daemon = True
    self.pinNumber = pinNumber

    WiringPiSingleton().setup()

    self.__initialState = wiringpi.digitalRead(self.pinNumber)
    self.__previousState = self.__initialState
Example #16
0
    def is_enabled(self, button):
        if not WIRING_PI:
            return False

        pin = self.button_pin[button]

        wiringpi.pinMode(pin, 1)
        state = wiringpi.digitalRead(pin)

        return state == 1
Example #17
0
  def run(self):
    self.__running = True

    while self.__running:
      state = wiringpi.digitalRead(self.pinNumber)
      if state != self.__previousState:
        self.onStateChange(state)

      self.__previousState = state
      time.sleep(self.__RESOLUTION / 1000.0)
Example #18
0
def main():

	receiver = 27; sender = 1; state = 1; i = 0
	global last_high, ones, zeros, bits_to_output, code

	while True:
		wiringpi.delayMicroseconds(25)

		if wiringpi.digitalRead(receiver) == False:

			if (bits_to_output > 0):
				sys.stdout.write("0")
			zeros += 1
			
			if state < 80:
				state += 1
		else:
			if state >= 2 and bits_to_output > 0:
				bits_to_output -= 1
				#sys.stdout.write("\n")
				#sys.stdout.write(str(format(ones / (ones + zeros), '.2f')) + " ")
				#sys.stdout.write(str( (ones + zeros)) + " ")
				
				if ones / (ones + zeros) < 0.5:
					#sys.stdout.write("0")
					code += "0"
				else:
					#sys.stdout.write("1")
					code += "1"

				if bits_to_output == 0:
					sys.stdout.write("   " + code)
					sys.stdout.write("   " + compress_string(code))
				
				#sys.stdout.write(" --\n")
				ones = 0
				zeros = 0

			if state == 80:
				calc_time()
			
			if (bits_to_output > 0):
				sys.stdout.write("1")
			ones += 1
			

			if state >= 2:
				last_high = wiringpi.micros()

			state = 0

		i += 1
		if i == 40:
			sys.stdout.flush()
			i = 0
Example #19
0
 def checkPedal(self, dt):
   try:
     # Only trigger a capture when the circuit goes from open to closed
     nextPedal = wiringpi.digitalRead(21)
     #print('checkPedal', nextPedal)
     if self.lastPedal == 1 and nextPedal == 0 and 'beginCapture' in dir(self.manager.current_screen):
       self.manager.current_screen.beginCapture()
     self.lastPedal = nextPedal
   except Exception as e:
     handleCrash(e)
   return True
Example #20
0
def pinIs(pin, statusNotWanted, nbSec):
    # initialisation compteur
    i = 0
    while True :
        time.sleep(0.1)
        # lecture de la pin
        if (GPIO.digitalRead(pin) == statusNotWanted):
            return False
        i = i+1
        if (i > nbSec*10):
            return True 
Example #21
0
def GPIO_callback():
    import wiringpi
    global button_previous_states

    button_states = [wiringpi.digitalRead(pin) for pin in button_pins]

    for button_index, (old, new) in enumerate(zip(button_previous_states, button_states)):
        if old != new and button_callback is not None:
            button_callback(button_index, 'down' if (new == 1) else 'up')

    button_previous_states = button_states
Example #22
0
    def run(self):
        while self.running:
            time.sleep(0.1)
            qsize = self.pushsocket.queue.qsize()
            print(qsize)
            while qsize > 0:
                element = self.pushsocket.queue.get()
                valve = list(element.keys())[0]
                wp.digitalWrite(int(valve)-1, element[valve])
                qsize = self.pushsocket.queue.qsize()

            for j in range(0, 20):
                self.pullsocket.set_point_now(self.valves[j], wp.digitalRead(j))
Example #23
0
def on_switch_interrupt():
	global last_ts
	global switch_state
	time_now = time.time()
	print 'switch interrupt: %s since %s' % (time_now, last_ts)
	if (time_now - last_ts) >= 0.3:
		state = wiringpi.digitalRead(IO_PIN)
		if (state != switch_state):
			switch_state = state;
			msg = str(state) + MESSAGE_DELIM + str(time_now)
			print 'Switch interrupt: %s' % state
			print 'publishing to %s: %s' % (aio_switch_feedid, msg)
			client.publish(aio_switch_feedid, msg)
		last_ts = time_now
Example #24
0
def main():
  start, end = 32, 116
  print 'LCD Display Test: ASCII %d to %d' % (start, end)
  start_time = time.time()
  init(CONTRAST)
  load_bitmap('r.bmp')
  #gotoxy(29,29)
  finish_time = time.time()
  print 'Init, LED on, %d chars, total time = %.2f' % (
    end - start, finish_time - start_time
    )
  print
  while 1==1:
    input_value1 = wiringpi.digitalRead(UP)
    input_value2 = wiringpi.digitalRead(RIGHT)
    input_value3 = wiringpi.digitalRead(DOWN)
    input_value4 = wiringpi.digitalRead(LEFT)
    input_value5 = wiringpi.digitalRead(SELECT)
    print "SW1 = ",input_value1,'\n'
    print "SW2 = ",input_value2,'\n'
    print "SW3 = ",input_value3,'\n'
    print "SW4 = ",input_value4,'\n'
    print "SW5 = ",input_value5,'\n'
    time.sleep(1)
Example #25
0
    def run(self):
        global direction
        while True:
            valueA = wiringpi.digitalRead(obsA)
            valueB = wiringpi.digitalRead(obsB)

            #print 'obsA:', valueA, 'obsB:', valueB

            if valueA == 0 or valueB == 0:
                if direction == 'Pause':
                    pass
                else:
                    doGoBackward()
                    sleep(0.5)
                    doTurnLeft()
                    sleep(0.5)
                    doGoForward()
                    direction = 'Forward'
            #else:
            #    if direction == 'Forward':
            #        doGoForward()
            #    elif direction == 'Pause':
            #        doStop()
            #    elif direction == 'Left':
            #        doTurnLeft()
            #        direction = 'Forward'
            #    elif direction == 'Right':
            #        doTurnRight()
            #        direction = 'Forward'
            #    elif direction == 'Backward':
            #        doGoBackward()

            if threadExit == True:
                break

            sleep(0.5)
Example #26
0
    def run(self):
        while not self.baker.quit:
            self.screen.addstr(2, 2, 'Running')

            tui_string = "Watchdog TTL: {0:.0f}   "
            self.screen.addstr(4, 2, tui_string.format(self.watchdog.time_to_live))
            tui_string = "Watchdog Timer: {0:.1f}"
            self.screen.addstr(5, 2, tui_string.format(time.time() -
                                                       self.watchdog.timer) + '  ')
            self.screen.addstr(6, 2, "Watchdog safe: " +
                               str(self.watchdog.watchdog_safe) + ' ')
            self.screen.addstr(8, 2, 'Current channel status:')
            for channel in range(1, 7):
                if settings.count_from_right:
                    pin = channel
                else:
                    pin = 7 - channel
                self.screen.addstr(9, 6 * channel, str(wp.digitalRead(pin)))

            self.screen.addstr(12, 2, 'Channel duty cycles')
            for i in range(1, 7):
                self.screen.addstr(13, 7 * i, str(self.baker.dutycycles[i - 1]) + '    ')

            key = self.screen.getch()

            keyboard_actions = {ord('1'): [1, 1], ord('!'): [1, -1],
                                ord('2'): [2, 1], ord('"'): [2, -1],
                                ord('3'): [3, 1], ord('#'): [3, -1],
                                ord('4'): [4, 1], 194: [4, -1],
                                ord('5'): [5, 1], ord('%'): [5, -1],
                                ord('6'): [6, 1], ord('&'): [6, -1]}
            if key in keyboard_actions:
                channel = keyboard_actions[key][0]
                sign = keyboard_actions[key][1]
                self.baker.modify_dutycycle(channel, settings.step_size * sign)
            if key == ord('q'):
                self.baker.quit = True
                self.screen.addstr(2, 2, 'Quitting....')

            message = 'Press 1 to increase channel 1, shift-1 to decrease channel 1'
            self.screen.addstr(16, 2, message)
            self.screen.addstr(17, 2, 'Likewise for other channels, press q to quit')

            self.screen.refresh()
            time.sleep(0.2)
Example #27
0
def countdown():
	wiringpi.digitalWrite(ON, 1)

	global end
	remaining = int(end - time.time())

	while remaining > 0 and wiringpi.digitalRead(WIN) == 0:

		doClock(remaining)
		
		if wiringpi.digitalRead(PENALTY) and (end - time.time()) > 300:
                	end -= 300
			wiringpi.digitalWrite(PENALTY, 0)

		if wiringpi.digitalRead(PAUSE):
			while wiringpi.digitalRead(PAUSE):
				blinkOff()
				
			end = time.time() + remaining


		remaining = int(end - time.time())


		if wiringpi.digitalRead(OFF):
			wiringpi.digitalWrite(OFF, 0)
			remaining = 0

		if wiringpi.digitalRead(WIN):
			i = 0
			while i < 6:
				blinkOff()
				time.sleep(1)
				doClock(remaining)
				time.sleep(1)
				i += 1
				pass
			turnOff()
			remaining = 0

		pass
	
	turnOff()		
Example #28
0
# led_sw.py

import wiringpi as pi
import time

LED_PIN = 23
SW_PIN = 24
pi.wiringPiSetupGpio()
pi.pinMode(LED_PIN, pi.OUTPUT)
pi.pinMode(SW_PIN, pi.INPUT)
pi.pullUpDnControl(SW_PIN, pi.PUD_UP)

while True:
    if (pi.digitalRead(SW_PIN) == pi.LOW):
        pi.digitalWrite(LED_PIN, pi.HIGH)
    else:
        pi.digitalWrite(LED_PIN, pi.LOW)
    time.sleep(0.1)
Example #29
0
import wiringpi
from time import sleep

wiringpi.wiringPiSetupGpio()
outPin = 21  #change it to whathever pin you want
inPin = 20  #change it to whathever pin you want
wiringpi.pinMode(outPin, 1)  #set outPin to 1 (OUTPUT)
wiringpi.pinMode(inPin, 1)  #set inPin to 0 (INPUT)

while True:
    if wiringpi.digitalRead(inPin) == 1:
        wiringpi.digitalWrite(outPin, 1)
        sleep(0.2)
    else:
        wiringpi.digitalWrite(outPin, 0)
        sleep(0.2)
Example #30
0
import wiringpi as pi
import time

SW_PIN = 4

pi.wiringPiSetupGpio()
pi.pinMode(SW_PIN, pi.INPUT)

while True:
    if (pi.digitalRead(SW_PIN) == pi.HIGH):
        print("Switch is ON")
    else:
        print("Switch is OFF")

    time.sleep(1)
Example #31
0
def DigitalWrite(gate, status):
	wiringpi.digitalWrite(gate, status)
	return wiringpi.digitalRead(gate)
Example #32
0
PIN_SW2_BLACK = 16
PIN_LED1_RED = 20
PIN_LED2_YELLOW = 21
PIN_BUZZER = 25

from st7032i import St7032iLCD as LCD
I2C_ADDR_LCD = 0x3e

import NetworkManager
c = NetworkManager.const

if __name__ == '__main__':
    wp.wiringPiSetupGpio()
    wp.pinMode(20, 1)
    wp.pinMode(21, 1)
    wp.pinMode(25, 1)
    lcd = LCD(I2C_ADDR_LCD)
    while True:
        sw1 = wp.digitalRead(PIN_SW1_WHITE)
        sw2 = wp.digitalRead(PIN_SW2_BLACK)
        if sw1 == 0:
            lcd.clear()
            wp.delay(250)
            lcd.set_cursor(0, 0)
            lcd.print("state:")
            state = "{0}".format(
                c('state', NetworkManager.NetworkManager.State))
            lcd.set_cursor(0, 1)
            lcd.print(state)
        wp.delay(500)
Example #33
0
 def rotation_sequence(self):
     a_state = wiringpi.digitalRead(self.a_pin)
     b_state = wiringpi.digitalRead(self.b_pin)
     r_seq = (a_state ^ b_state) | b_state << 1
     return r_seq
Example #34
0
    if MODO == b'2':
        for w in range(0, 1):
            for z in range(0, NO_DOTS):
                D = fun.CILINDRO_ESFERICO(a, b, c, ra, rb, lz, u[z], v[z])
                #D = fun.LINEA_RECTA(P1,P2,t[z])
                #D = fun.ESPIRAL_ARQUIMIDES(ae,be,ce,t1e[z],te[z])
                #D = fun.ESFERA(a_es,b_es,c_es,r_es,u_es[z],v_es[z])
                print(D)
                pi.digitalWrite(PIN_END, 1)
                Px = b'%d' % D[0]
                Py = b'%d' % D[1]
                Pz = b'%d' % D[2]
                POS = Px + aa + Py + aa + Pz + aa + vx + aa + vy + aa + vz + b'@*\r\n'
                port.write(POS)
                while True:
                    if pi.digitalRead(PIN_STAR) == 1:
                        pi.digitalWrite(PIN_END, 0)
                        tlv.time.sleep(0.001)
                        data = tlv.READ(5)
                        pi.digitalWrite(PIN_END, 1)
                        for i in range(0, 5):
                            for j in range(0, 7):
                                f.write(format(int(data[i][j])) + ",")
                            f.write("\n")
                        break
            ce = ce - 0.001
        pi.digitalWrite(END, 0)
        tlv.time.sleep(1)

if rr == b'155':
    SS = sio.readline()
Example #35
0
 def has_ShutdownButtonBeenPressed(self):
     if (wiringpi.digitalRead(5) == 1):
         self.cursor.close()
         self.conn.close()
         time.sleep(0.5)
         os.system("sudo poweroff")
Example #36
0
# set the pin mode to an input, 0, for all our switches
wiringpi.pinMode(blue_switch, 0)
wiringpi.pinMode(yellow_switch, 0)
wiringpi.pinMode(red_switch, 0)
wiringpi.pinMode(green_switch, 0)
# the mcp23017 ic has an internal pull up resistor. enabling this will keep the output pulled high. this stops any floating states which could cause odd things to happen in our script, 2
wiringpi.pullUpDnControl(blue_switch, 2)
wiringpi.pullUpDnControl(yellow_switch, 2)
wiringpi.pullUpDnControl(red_switch, 2)
wiringpi.pullUpDnControl(green_switch, 2)

# create an infinite loop
while True:
    # because we set the pull up resistor on our output, when we press the button the pin state will actually go low. so we need to check when the pin is low, hense the not in the if statement
    if not wiringpi.digitalRead(blue_switch):
        wiringpi.digitalWrite(blue_led, 1)
    else:
        wiringpi.digitalWrite(blue_led, 0)
    if not wiringpi.digitalRead(yellow_switch):
        wiringpi.digitalWrite(yellow_led, 1)
    else:
        wiringpi.digitalWrite(yellow_led, 0)
    if not wiringpi.digitalRead(red_switch):
        wiringpi.digitalWrite(red_led, 1)
    else:
        wiringpi.digitalWrite(red_led, 0)
    if not wiringpi.digitalRead(green_switch):
        wiringpi.digitalWrite(green_led, 1)
    else:
        wiringpi.digitalWrite(green_led, 0)
Example #37
0
 def read_pir(self):
     values = []
     for pir in self.pin_pir:
         values.append(wp.digitalRead(pir))
     return values
Example #38
0
    wiringpi.pullUpDnControl(dataLine, 2)

# Setup Button
wiringpi.pinMode(buttonGPIO, 0)
wiringpi.pullUpDnControl(buttonGPIO, 2)

# Announce
print("Running")
bip(1000,100)

try:

    # Loop forever
    while True:
        # Button check
        if(wiringpi.digitalRead(buttonGPIO) == False):
            # Record time the button was pressed
            if(buttonPressed == -1):
                buttonPressed = time.time()
                print('Button pressed')
                bip(3000,20)
                buttonBip=time.time()
            else:
                # bip 3 times before act
                if(time.time() > buttonBip+1):
                    buttonBip=time.time()
                    bip(3000,10)

        elif(buttonPressed != -1):
            # Button released - but how long was it pressed for?
            buttonTime = time.time() - buttonPressed
wiringpi.pinMode(green_led, 1)      # set up green LED port for output
wiringpi.digitalWrite(red_led, led_OFF)     # make sure red led is off to start
wiringpi.digitalWrite(yellow_led, led_OFF)  # make sure yellow led is off to start
wiringpi.digitalWrite(green_led, led_OFF)   # make sure green led is off to start

def reset_ports():                          # resets the ports for a safe exit
    wiringpi.pullUpDnControl(22, wiringpi.PUD_OFF) #unset pullup on button port
    wiringpi.pinMode(button,0)              # set button port to input mode
    wiringpi.pinMode(red_led,0)             # set red led port to input mode
    wiringpi.pinMode(yellow_led,0)          # set yellow led port to input mode
    wiringpi.pinMode(green_led,0)           # set red led port to input mode

# wait for the button to be pressed
print("\nPress button to start countdown")
try:
    while wiringpi.digitalRead(button)== 1:
        sleep(0.1)
    print("\nStarting countdown")
    # STOP  : turn on red LED
    wiringpi.digitalWrite(red_led, led_ON)
    sleep (2)
    # READY : turn Yellow on
    wiringpi.digitalWrite(yellow_led, led_ON)
    sleep (2)
    # STEADY: blink red & yellow LEDs
    for i in range (0,10):
        wiringpi.digitalWrite(red_led, led_OFF)
        wiringpi.digitalWrite(yellow_led, led_OFF)
        sleep(0.1)
        wiringpi.digitalWrite(red_led, led_ON)
        wiringpi.digitalWrite(yellow_led, led_ON)
 def record_pulse_length(self):
     self.start_time=time.time()
     while ( wp.digitalRead(self.echo) == HIGH):
         pass
     self.end_time=time.time()
Example #41
0
    # balanced (default, varies frequency with duty cycle for even pulses)
    # mark-space mode (traditional)
wiringpi.pwmSetMode(wiringpi.PWM_MODE_MS)
wiringpi.pwmSetRange(Range) # sets the range register for the PWM. Default is 1024.
wiringpi.pwmSetClock(Divisor) # sets divisor for the PWM clock
wiringpi.pwmWrite(18,DutyCalc) # duty cycle between 0 and 1024. 0 = off, 1024 = fully on

# GPIO pins support 0v-3.3v
Volts = 3.3*DutyCalc/Range
#Sensor = 0.9*DutyCalc/Range
print("Pin 18 is set to %g Volts" %Volts)
#print("Past the Op Amp, sensor voltage calculates to %g Volts" %Sensor)
prompt = raw_input("please proceed, press ENTER ")
# attempt to insert pause so pin voltage is read correctly
    # forum suggests GPIO library can only read at 1MHz max
        # tested at above and below 1MHz, misreading still occurs about
            # 1 out of 10 trials
# the sampling period is variable and will not be accurate for such
    # an attempt without implementing an interrupt
            
pin24 = wiringpi.digitalRead(24) # Reads voltage as a 1 or 0
print("%i volts" %pin24)
print("reading input pin 24")
if pin24 == 1: # Logic HIGH
    print("Pin 24 reads as %i volt, therefore it is HIGH" %pin24)
else:
    print("Pin 24 reads as %i volts, therefore it is LOW" %pin24)
    


Example #42
0
    wiringpi.pinMode(24, 0)


print "These are the connections you must make on the Gertboard for this test:"
print "GP23 in J2 --- B3 in J3"
print "GP22 in J2 --- B6 in J3"
print "U3-out-B3 pin 1 --- BUF6 in top header"
print "jumper on U4-in-B6"
raw_input("When ready hit enter.\n")

button_press = 0  # set intial values for variables
previous_status = ''

try:
    while button_press < 20:  # read inputs constantly until 19 changes are made
        status_list = [wiringpi.digitalRead(23), wiringpi.digitalRead(22)]
        for i in range(0, 2):
            if status_list[i]:
                status_list[i] = "1"
            else:
                status_list[i] = "0"
                # dump current status values in a variable
        current_status = ''.join((status_list[0], status_list[1]))
        # if that variable not same as last time
        if current_status != previous_status:
            print current_status  # print the results
            # update status variable for next comparison
            previous_status = current_status
            # increment button_press counter
            button_press += 1
Example #43
0
pi.pinMode(trig, pi.OUTPUT)
pi.pinMode(echo, pi.INPUT)
r = redis.StrictRedis(host='localhost', port=6379, db=0)

while True:
    time.sleep(interval)
    is_break = False

    # start the pulse on the trig pin
    pi.digitalWrite(trig, pi.HIGH)
    time.sleep(0.00001)  # wait 10 micro seconds
    pi.digitalWrite(trig, pi.LOW)

    # listen to the echo pin
    count = 0
    while pi.digitalRead(echo) == pi.LOW:
        if count == 10000:
            is_break = True
            break
        count += 1
        t_start = time.time()
    if is_break:
        continue

    count = 0
    while pi.digitalRead(echo) == pi.HIGH:
        if count == 10000:
            is_break = True
            break
        count += 1
        t_end = time.time()
Example #44
0
 def wait_for_press(self):
     read_val = wp.digitalRead(22)
     while read_val:
         read_val = wp.digitalRead(22)
     print("Button pressed!!")
Example #45
0
def check(bot, update):
    if (wiringpi.digitalRead(LED_GRN)):
        update.message.reply_text('LED is ON.')
    else:
        update.message.reply_text('LED is OFF.')
Example #46
0
 def fault(self):
     return wiringpi.digitalRead(self.fault_pin)
Example #47
0
import wiringpi as wpi
pin = 18

wpi.wiringPiSetupGpio()
wpi.pinMode(pin, wpi.INPUT)

val = -1
while True:
    read = wpi.digitalRead(pin)
    if (read != val):
        val = read
        print(val == 0 and "no intruder" or "intruder detected")
            (0, 33),
            unicode("Скорость: " + format(agps_thread.data_stream.speed)[:3],
                    'utf-8'),
            font=font_ra,
            fill=255)  # Speed values (RUS simbol)
        draw.text((0, 50),
                  str("Course: ") +
                  (format(agps_thread.data_stream.track)[:3]) + unichr(176),
                  font=font_ra,
                  fill=255)  # Course values


try:
    while True:

        button = wpi.digitalRead(
            2)  # read the state of the button in the "button"

        if state == 0:  # if state = 0
            page1()  # the "1 page" function works
            wpi.digitalWrite(3, 0)  # LED is off
            if button:  # if the button is pressed
                state += 1  # add 1 to "state"
                sleep(0.2)  # eliminate contact bounce

        elif state == 1:  # if state = 1
            page2()  # the "2 page" function works
            wpi.digitalWrite(3, 1)  # LED is on
            if button:  # if the button is pressed
                state += 1  # add 1 to "state"
                sleep(0.2)  # eliminate contact bounce
Example #49
0
# Define rala pins and states
rala_pins = [26, 20, 19, 16]
rala_states = [[1,1,1,1], # Omnidirectional
	       [1,0,0,0], # Direction 1
               [0,1,0,0], # Direction 2
               [0,0,1,0], # Direction 3
               [0,0,0,1], # Direction 4
               [0,0,0,0]] # Off]

# Define RFSwitch pins and states
rfswitch_pins = [17,27]
rfswitch_states = [[0,0], # RFPort 1
                   [1,0], # RFPort 2
                   [0,1], # RFPort 3
                   [1,1]] # RFPort 4

# Get state for RALA
gpio = [wiringpi.digitalRead(pin) for pin in rala_pins]
for i in range(len(rala_states)):
	if rala_states[i] == gpio:
		print("RALA state: "+str(i))
		break

# Get state for RFSwitch
gpio = [wiringpi.digitalRead(pin) for pin in rfswitch_pins]
for i in range(len(rfswitch_states)):
	if rfswitch_states[i] == gpio:
		print("RFSwitch state: "+str(i+1))
		break
Example #50
0
 def reportClick(_bcmPin=bcmPin, _btnNum=btnNum):
     if wiringpi.digitalRead(_bcmPin) == 0:
         postButtonClickEvent(_btnNum)
Example #51
0
def readDigSensor(gate):	
	lvlinput = wiringpi.digitalRead(gate)
	return lvlinput
Example #52
0
import wiringpi as pi
import time

SENSOR_PIN = 18

pi.wiringPiSetupGpio()
pi.pinMode(SENSOR_PIN, pi.INPUT)

while True:
    if (pi.digitalRead(SENSOR_PIN) == pi.HIGH):
        print("S Pole.")
    else:
        print("N Pole.")

    time.sleep(1)
Example #53
0
    def medidor_agua(self):

        if (wiringpi.digitalRead(0) and wiringpi.digitalRead(1)
                and wiringpi.digitalRead(4) and wiringpi.digitalRead(6)):
            self.refWata.set(100)
            return ("100")

        elif (wiringpi.digitalRead(0) and wiringpi.digitalRead(1)
              and wiringpi.digitalRead(4) and not (wiringpi.digitalRead(6))):
            self.refWata.set(75)
            return ("75")

        elif (wiringpi.digitalRead(0) and wiringpi.digitalRead(1)
              and not (wiringpi.digitalRead(4))
              and not (wiringpi.digitalRead(6))):
            self.refWata.set(50)
            return ("50")
        elif (wiringpi.digitalRead(0) and not (wiringpi.digitalRead(1))
              and not (wiringpi.digitalRead(4))
              and not (wiringpi.digitalRead(6))):
            self.refWata.set(25)
            return ("25")
        elif (not (wiringpi.digitalRead(0) and wiringpi.digitalRead(1)
                   and wiringpi.digitalRead(4) and wiringpi.digitalRead(6))):
            self.refWata.set(0)
            return ("0")
        else:
            return ("Medicion erronea")
Example #54
0
def detectHuman():
    rightSide = wiringpi.digitalRead(RIGHT_SIDE)
    leftSide = wiringpi.digitalRead(LEFT_SIDE)

    return leftSide, rightSide
Example #55
0
 def digitalRead(pin):
     return wiringpi.digitalRead(pin)
Example #56
0
# AWSIoTMQTTClient connection configuration
client.configureAutoReconnectBackoffTime(1, 32, 20)
client.configureOfflinePublishQueueing(-1)
client.configureDrainingFrequency(2)
client.configureConnectDisconnectTimeout(10)
client.configureMQTTOperationTimeout(5)

# Connect and subscribe to AWS IoT
client.connect()

try:


    while True:
        if (pi.digitalRead(PIR_PIN) == pi.HIGH):
            message = {}
            message['id'] = DEVICE_NO
            message['id2'] = GATEWAY_NO
            message['message'] = "detected"
            messageJson = json.dumps(message)
            print (messageJson)
            client.publish(TOPIC, messageJson, 1)
            time.sleep(5)
        else:
            message = {}
            message['id'] = DEVICE_NO
            message['id2'] = GATEWAY_NO
            message['message'] = "Not detected"
            messageJson = json.dumps(message)
            print (messageJson)
Example #57
0
# HSV bounds to find the skin colors
lower = np.array([0, 48, 80], dtype = "uint8")
upper = np.array([20, 255, 255], dtype = "uint8")
points = []
tmp_points = []
camera_set_up = False
start_presenting = False
zoom_mode = True
prev_button = True
prev_time = time.time()
start_time = time.time()
# capture frames from the camera
for image in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
  frame0 = image.array
  button = wiringpi.digitalRead(BUTTON)
  # Check if button is pushed
  if button == 0 and prev_button and not start_presenting:
    camera_set_up = True
  elif button == 0 and prev_button:
    endPins()
    break
  
  if button == 0:
    prev_button = False
  else:
    prev_button = True
  
  key = cv2.waitKey(1) & 0xFF
  if key == ord('q'):
    endPins()
Example #58
0
def getled():
    return ( wiringpi.digitalRead(ledR), wiringpi.digitalRead(ledG), wiringpi.digitalRead(ledB) )
Example #59
0
    wiringpi.pinMode(22,0)              # set ports to input mode
    wiringpi.pinMode(24,0)

print "These are the connections you must make on the Gertboard for this test:"
print "GP23 in J2 --- B3 in J3"
print "GP22 in J2 --- B6 in J3"
print "U3-out-B3 pin 1 --- BUF6 in top header"
print "jumper on U4-in-B6"
raw_input("When ready hit enter.\n")

button_press = 0                          # set intial values for variables
previous_status = ''

try:
    while button_press < 20:  # read inputs constantly until 19 changes are made
        status_list = [wiringpi.digitalRead(23), wiringpi.digitalRead(22)]
        for i in range(0,2):
            if status_list[i]:
                status_list[i] = "1"
            else:
                status_list[i] = "0" 
                        # dump current status values in a variable
        current_status = ''.join((status_list[0],status_list[1]))
                        # if that variable not same as last time
        if current_status != previous_status:
            print current_status                # print the results                         
                        # update status variable for next comparison
            previous_status = current_status
                        # increment button_press counter
            button_press += 1
Example #60
0
def start():
    global counter
    global user_id
    global start
    global end 
    global status2_blink
    global start2_blink
    global stop2_threads
    
    durationStop2 = datetime.now() - timedelta(days = 1)
    duration2 = 0
    status2_toilet = "free"
    start_d = datetime.now()
    start_time = datetime.now()
    read0 = 1
    log2count = count2_people()
    temp2_count = log2count

    while True:
        time.sleep(0.1)
        read1 = wiringpi.digitalRead(GPIO_SW)
        #        print "read1= %d" % read1

        if status2_blink and (status2_toilet == "free"):
            if (datetime.now() - durationStop2).seconds > 1:
                print("stop blink")
                stop2_threads = True
                start2_blink.join()
                status2_blink = False
                duration = (datetime.now() - start_time).seconds /60  #For 1 min
                start_time = datetime.now()
                duration =str(duration)
                store2_log(duration + "\n 男子トイレ使用終了\n")
                status2("free")
                print (duration)
                print("\n男子トイレ使用終了")
                temp2_count = log2count
                status2_toilet = "free"
            
        elif (not status2_blink) and status2_toilet == "busy":
            if(datetime.now() - start_time).seconds > 60 :
                stop2_threads = False
                print("start blink")
                start2_blink = threading.Thread(target = blink_led, args = ())
                start2_blink.start()
                status2_blink = True
        if read0 == read1:

            continue

        time.sleep(0.05)
        read2 = wiringpi.digitalRead(GPIO_SW)
        now = datetime.now()
        current = datetime.now()
        current_date = now.strftime("%Y/%m/%d %H:%M:%f")
        current_time = now.strftime("%H:%M:%f")
        end = datetime.now()

        #        print "read0= %d" % read0
        if read1 == read2:
            if read1 == 1:
                duration2 = datetime.now() - durationStop2
    #            print(duration2)
                if (duration2.seconds) < 5:
                    thAnn5()
                    start_d = datetime.now()
                    status2_toilet = "busy"
                    wiringpi.digitalWrite(GPIO_LED, 0) # switch on LED. Sets port 18 to 1 (3V3, on)
                    user_id = logTable.insert_table(2, current_date, current_time,2, "Girl Busy", duration = duration)
            #        status2("Busy")
    #                print ("\n 女子トイレUse")

                else:
                #    stop_thAnn5()
                    start_time = datetime.now()
                    start_d = datetime.now()
                    status2_toilet = "busy"
                    log2count = log2count + 1
                    print ("person count:" + str(log2count))
                    start_waiting()
                    wiringpi.digitalWrite(GPIO_LED, 0)  # switch on LED. Sets port 18 to 1 (3V3, on)
                    store2_log(str(log2count) + "女子 トイレBusy\n")
                    
                    status2("Busy")
                    print ("\n 女子トイレBusy\n")
                    user_id = logTable.insert_table(2, current_date, current_time, 1, "Girl Busy", duration=duration)



            else:

                stop_waiting()
                status2_toilet = "free"
                durationStop2 = datetime.now()
                time_end = datetime.now()
                duration = time_end - start_d
                duration = duration.seconds/60.0
                wiringpi.digitalWrite(GPIO_LED, 1) # switch off LED. Sets port 18 to 0 (0V, off)
                pygame.mixer.Channel(1).stop()
            #    store2_log("女子 トイレFree\n")
                user_id = logTable.insert_table(2,current_date, current_time, 2, "Girl Free", duration= duration)
            #    print (duration)
             #   status2("Free")
             #   print ("\n女子トイレFree\n")
                if temp2_count > log2count:
                    logTable.update_table(user_id , duration)
                    temp2_count = log2count


        read0 = read1