def run(self):
		global player
		global running
		global laser_list
		global green
		pfio.init()
		tick = 0
		while running:
			try:
				x = pfio.read_input()
				if x >= 8 :
					x=0
				if tick + 0.8 < time.time():
					#FIRE!!!!!!
					if x - 4 >= 0:
						x = x-4
						newlaser = laser_sprite(4,10,1, green)
						newlaser.rect.x = 28 + player.rect.x # laser is 4 wide player is 60; 60 /2 + 4 /2 = 28
						newlaser.rect.y =  player.rect.y
						laser_list.add(newlaser)		
					tick = time.time()
				# go right
				if x - 2 >= 0:
					x = x-2
					player.rect.x += 2
				#go left
				if x - 1 >= 0:
					player.rect.x -= 2
			except:
				pass
		pfio.deinit()
Exemplo n.º 2
0
 def __init__(self):
         self.port=8080
         pfio.init()
         print 'Start HTTP server on '+str(self.port)
         self.server = myHTTPServer(('',self.port),SondeHandler)
         self.server.serve_forever()
         print 'Stop HTTP server on '+str(self.port)
Exemplo n.º 3
0
def ButtonPressed(x):
    pfio.init()
    pressed = pfio.digital_read(x)
    while(pressed!=1):
        pressed = pfio.digital_read(x)
    if(pressed==1):
        return True 
Exemplo n.º 4
0
    def __init__(self, gui, question_file_name=None):
        threading.Thread.__init__(self)
        self.gui = gui

        self.question_file_name = question_file_name
        # set up the hardware interface
        pfio.init()

        # set up the buttons
        self.buttons = list()
        self.buttons.append(Button(ButtonSwitch(1), ButtonLight(3)))
        self.buttons.append(Button(ButtonSwitch(2), ButtonLight(4)))
        self.buttons.append(Button(ButtonSwitch(3), ButtonLight(5)))
        self.buttons.append(Button(ButtonSwitch(4), ButtonLight(6)))
        self.buttons.append(Button(ButtonSwitch(5), ButtonLight(7)))

        # set up the players
        self.player1 = Player("Adam", RacingCar(1),
                              (self.buttons[0], self.buttons[1]))
        self.player2 = Player("Eve", RacingCar(2),
                              (self.buttons[2], self.buttons[3]))
        """
        Threading stopper idea from stack overflow
        http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python
        """
        self._stop = threading.Event(
        )  # a stopper to know when to end the game
Exemplo n.º 5
0
Arquivo: game.py Projeto: AndyA/piface
    def __init__(self, gui, question_file_name=None):
        threading.Thread.__init__(self)
        self.gui = gui

        self.question_file_name = question_file_name
        # set up the hardware interface
        pfio.init()

        # set up the buttons
        self.buttons = list()
        self.buttons.append(Button(ButtonSwitch(1), ButtonLight(3)))
        self.buttons.append(Button(ButtonSwitch(2), ButtonLight(4)))
        self.buttons.append(Button(ButtonSwitch(3), ButtonLight(5)))
        self.buttons.append(Button(ButtonSwitch(4), ButtonLight(6)))
        self.buttons.append(Button(ButtonSwitch(5), ButtonLight(7)))

        # set up the players
        self.player1 = Player("Adam", RacingCar(1), (self.buttons[0], self.buttons[1]))
        self.player2 = Player("Eve", RacingCar(2), (self.buttons[2], self.buttons[3]))

        """
        Threading stopper idea from stack overflow
        http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python
        """
        self._stop = threading.Event() # a stopper to know when to end the game
Exemplo n.º 6
0
def main():
    parser = optparse.OptionParser()
    parser.add_option('-r',
                      '--room',
                      help='check access to this room',
                      dest='roomname',
                      default='room1',
                      action='store')
    parser.add_option('-f',
                      '--forever',
                      help='run forever',
                      dest='runf',
                      default=False,
                      action='store_true')
    (opts, args) = parser.parse_args()
    pfio.init()
    pin = 0
    if (opts.runf == False):
        room = opts.roomname
        ID = RFIDread()
        key = validateUser(str(ID), str(room))
    else:
        while (True):
            roomcount = 0
            ID = RFIDread()
            if validateUser(str(ID), 'room1'):
                roomcount = roomcount + 1
                print "access granted to room1"
                pfio.digital_write(0, 1)
                time.sleep(3)
                pfio.digital_write(0, 0)
            if validateUser(str(ID), 'room2'):
                roomcount = roomcount + 1
                print "access granted to room2"
                pfio.digital_write(1, 1)
                time.sleep(3)
                pfio.digital_write(1, 0)
            if validateUser(str(ID), 'room3'):
                roomcount = roomcount + 1
                print "access granted to room3"
                pfio.digital_write(2, 1)
                time.sleep(3)
                pfio.digital_write(2, 0)
            if roomcount == 3:
                print "Sorry! No access"

    if room == 'room1':
        pin = 0
    elif room == 'room2':
        pin = 1
    elif room == 'room3':
        pin = 2

    if key:
        print "!! Access Granted !!"
        pfio.digital_write(pin, 1)
        time.sleep(3)
        pfio.digital_write(pin, 0)
    else:
        print "Sorry! No access"
Exemplo n.º 7
0
def scanSwitch():
    import piface.pfio as pfio
    pfio.init() 
    loopctl = True
    button1 = 0
    button2 = 0
    button3 = 0
    button4 = 0
    input6 = 0                             # input6 and input7 are 5V logic level control signals from Arduino.
    input7 = 0
    goControl()                       
    while loopctl is True:

        for i in range (1, 15000):             # These loops indexed by "i" are delay loops to reduce keybounce.
	    delay = 0
        button1 = int(pfio.digital_read(0))    # Read the outer most button
        if button1 == 1:
            print('Stop button pressed')
            stopControl()
            for i in range (1, 15000):
		delay = 0

        button2 = int(pfio.digital_read(1))     # Read the second middle button 
        if button2 == 1:
            waitControl()
            print('Pause button pressed')
            for i in range (1, 1500):
                delay = 0   
 
        button3 = int(pfio.digital_read(2))     # Read the first middle button
        if button3 == 1:
            waitControl()
            print('Pause button pressed')
            for i in range (1, 15000):
		delay = 0

        button4 = int(pfio.digital_read(3))    # Read the inner most button
        if button4 == 1:
            goControl()
            print('Go button pressed')
            for i in range (1, 15000):
		delay = 0
		
        input6 = int(pfio.digital_read(6))    # Read the digital input pin 6, PAUSE signal from Arduino.
        input7 = int(pfio.digital_read(7))    # Read the digital input pin 7, GO signal from Arduino.
        if input6 == 1 and input7 == 0:       # PAUSE when true
           for i in range (1, 5000):
               delay = 0
           if input6 == 1 and input7 == 0:
               waitControl()
               print('WAIT signal from Arduino')   # Suppress multiple triggers

        if input6 ==0 and input7 == 1:        # GO when true
           for i in range (1, 5000):
               delay = 0
           if input6 == 0 and input7 == 1:
               goControl()
               print('GO signal from Arduino')   # Suppress multiple triggers
Exemplo n.º 8
0
    def __init__(self):

        pfio.init()

        self.prev = True

        self.state = True

        self.Motor()
    def __init__(self):

        pfio.init()

        self.prev=True

        self.state=True

        self.Motor()
Exemplo n.º 10
0
	def run(self):
		# Initialize UDP connection
		#UDP_IP = "192.168.1.10" # UDP Server
		UDP_PORT = 6005		# UDP Port
		sock = socket.socket(socket.AF_INET, # Internet
		socket.SOCK_DGRAM) # UDP
		sock.bind(("", UDP_PORT))
		
		# Initialize i2c
		bus = smbus.SMBus(1) # RPi rev 2 = SMBus(1)
		device = 0x04 # Arduino i2c device address
		
		# Initialize Piface IO
		pfio.init()
		r0 = pfio.Relay(0)
		r0State = 0
		r0CurState = 0
		r1 = pfio.Relay(1)
		r1State = 0
		r1CurState = 0
		
		while True:
			print "Listening"
			recv_data, addr = sock.recvfrom(1024)
			recv_data = recv_data.strip('[]').split(',')
			recv_data = [int(x) for x in recv_data]
			r_drive = recv_data[0]
			l_drive = recv_data[1]
			right = recv_data[2]
			left = recv_data[3]
			DServo0Cur = recv_data[4]
			DServo1Cur = recv_data[5]
			r0State = recv_data[6]
			r1State = recv_data[7]

			print r_drive, l_drive, right, left, DServo0Cur, DServo1Cur, r0State, r0CurState, r1State, r0CurState
        
			if r0State != r0CurState:
				if r0State == 1:
					r0.turn_on()
					r0CurState = 1
				else:
					r0.turn_off()
					r0CurState = 0
        
			if r1State != r1CurState:
				if r1State == 1:
					r1.turn_on()
					r1CurState = 1
				else:
					r1.turn_off()
					r1CurState = 0

			try:
				bus.write_i2c_block_data(device, 1, [r_drive, l_drive, right, left, DServo0Cur/10, DServo1Cur/10])
			except IOError, err:
					print "Lost I2C"
Exemplo n.º 11
0
def process (cycles, on, unit_mult_on, off, unit_mult_off):
        """ 
            This function contains the actual timing loops and calls to the PiFace firmware.
            It will let the user know how many cycles have been completed by sending an update to the console.
            This function also monitors the contents of "control.txt". Please refer to the doc string in main 
            for details on the operation using "control.txt".
            If a pause of the cycle is invoked locally or via Twitter.com, a counter-clockwise rotating 
            character icon is output to the console.
        """

        from time import sleep
        import piface.pfio as pfio
        pfio.init( )
        controlString = ''
        if cycles > 0:
            count = 1
            for count in range (1, cycles + 1):
                pfio.digital_write(0,1)     # Turn relay 0 / LED 0 ON
                sleep(on * unit_mult_on)     
                                           
                pfio.digital_write(0,0)     # Turn relay 0 / LED 0 OFF
                                            
                sleep(off * unit_mult_off)
                print ('Cycles completed: '+ str(count))
                controlString = str(readFile('control.txt'))
                if controlString == 'STOP':
                    exit (0)
		if controlString == 'PAUSE':
                    print ('Waiting...')
                while controlString == 'PAUSE':
	            sigwait()
                    controlString = str(readFile('control.txt'))

            return
        else:
            count = 0
            while (True):           
                pfio.digital_write(0,1)     # Turn relay 0 / LED 0 ON
                sleep(on * unit_mult_on)           
                                            
                pfio.digital_write(0,0)     # Turn relay 0 / LED 0 OFF
                                            
                sleep(off * unit_mult_off)
                count = count + 1
                print ('Cycles completed: '+ str(count))
                controlString = str(readFile('control.txt'))
                if controlString == 'STOP':
                    exit (0)
		if controlString == 'PAUSE':
                    print ('Waiting...')
                while controlString == 'PAUSE':
                    sigwait()	
                    controlString = str(readFile('control.txt'))
                   
        return
Exemplo n.º 12
0
def main():
    parser = optparse.OptionParser()
    parser.add_option('-r', '--room',help='check access to this room',
                      dest='roomname', default='room1', action='store')
    parser.add_option('-f', '--forever', help='run forever',
                      dest='runf', default=False, action='store_true')
    (opts, args) = parser.parse_args()
    pfio.init()
    pin = 0
    if(opts.runf == False):
        room = opts.roomname
        ID=RFIDread()
        key=validateUser(str(ID),str(room))
    else:
        while(True):
            roomcount = 0
            ID=RFIDread()
            if validateUser(str(ID),'room1'):
                roomcount = roomcount + 1
                print "access granted to room1"
                pfio.digital_write(0,1)
                time.sleep(3)
                pfio.digital_write(0,0)
            if validateUser(str(ID),'room2'):
                roomcount = roomcount +1
                print "access granted to room2"
                pfio.digital_write(1,1)
                time.sleep(3)
                pfio.digital_write(1,0)
            if validateUser(str(ID),'room3'):
                roomcount = roomcount +1
                print "access granted to room3"
                pfio.digital_write(2,1)
                time.sleep(3)
                pfio.digital_write(2,0) 
            if roomcount == 3:
                print "Sorry! No access"

    if room == 'room1':
        pin = 0
    elif room == 'room2':
        pin = 1
    elif room == 'room3':
        pin = 2

    if key:
        print "!! Access Granted !!"
        pfio.digital_write(pin,1)
        time.sleep(3)
        pfio.digital_write(pin,0)
    else:
        print "Sorry! No access"
Exemplo n.º 13
0
def main():

        if len(sys.argv) <= 1:
                print("A phrase/word was not informed!!")
        else:
                pfio.init()
                j = 0
                for argument in sys.argv:
                        print (argument.lower())
                        if j != 0:
                                print (translator(argument.lower()))
                                ledBlinker(list(translator(argument.lower())))
                        j += 1
                pfio.deinit()
Exemplo n.º 14
0
def ajax(request):
    data = request.GET.dict()
    return_values = dict()

    if 'init' in data:
        try:
            pfio.init()
        except pfio.InitError as error:
            return_values.update({'status': 'init failed'})
            return_values.update({'error': str(error)})
            return HttpResponseBadRequest(simplejson.dumps(return_values))

    if 'read_input' in data:
        try:
            input_bitp = pfio.read_input()
        except Exception as e:
            return_values.update({'status': 'read_input failed'})
            return_values.update({'error': str(e)})
            return HttpResponseBadRequest(simplejson.dumps(return_values))
        else:
            return_values.update({'input_bitp': input_bitp})

    if 'read_output' in data:
        try:
            output_bitp = pfio.read_output()
        except Exception as e:
            return_values.update({'status': 'read_output failed'})
            return_values.update({'error': str(e)})
            return HttpResponseBadRequest(simplejson.dumps(return_values))
        else:
            return_values.update({'output_bitp': output_bitp})

    if 'write_output' in data:
        try:
            output_bitp = int(data['write_output'])
        except ValueError:
            return_values.update({'status': 'write_output failed'})
            return_values.update(
                {'error': "write_output needs an integer bit pattern."})
            return HttpResponseBadRequest(simplejson.dumps(return_values))

        try:
            pfio.write_output(output_bitp)
        except Exception as e:
            return_values.update({'status': "write_output failed"})
            return_values.update({'error': str(e)})
            return HttpResponseBadRequest(simplejson.dumps(return_values))

    return_values.update({'status': 'success'})
    return HttpResponse(simplejson.dumps(return_values))
Exemplo n.º 15
0
def main():

    if len(sys.argv) <= 1:
        print("A phrase/word was not informed!!")
    else:
        pfio.init()
        j = 0
        for argument in sys.argv:
            print(argument.lower())
            if j != 0:
                print(translator(argument.lower()))
                ledBlinker(list(translator(argument.lower())))
            j += 1
        pfio.deinit()
Exemplo n.º 16
0
def ajax(request):
    data = request.GET.dict()
    return_values = dict()

    if 'init' in data:
        try:
            pfio.init()
        except pfio.InitError as error:
            return_values.update({'status' : 'init failed'})
            return_values.update({'error' : str(error)})
            return HttpResponseBadRequest(simplejson.dumps(return_values))

    if 'read_input' in data:
        try:
            input_bitp = pfio.read_input()
        except Exception as e:
            return_values.update({'status' : 'read_input failed'})
            return_values.update({'error' : str(e)})
            return HttpResponseBadRequest(simplejson.dumps(return_values))
        else:
            return_values.update({'input_bitp' : input_bitp})

    if 'read_output' in data:
        try:
            output_bitp = pfio.read_output()
        except Exception as e:
            return_values.update({'status' : 'read_output failed'})
            return_values.update({'error' : str(e)})
            return HttpResponseBadRequest(simplejson.dumps(return_values))
        else:
            return_values.update({'output_bitp' : output_bitp})

    if 'write_output' in data:
        try:
            output_bitp = int(data['write_output'])
        except ValueError:
            return_values.update({'status' : 'write_output failed'})
            return_values.update({'error' : "write_output needs an integer bit pattern."})
            return HttpResponseBadRequest(simplejson.dumps(return_values))

        try:
            pfio.write_output(output_bitp)
        except Exception as e:
            return_values.update({'status' : "write_output failed"})
            return_values.update({'error' : str(e)})
            return HttpResponseBadRequest(simplejson.dumps(return_values))

    return_values.update({'status' : 'success'})
    return HttpResponse(simplejson.dumps(return_values))
Exemplo n.º 17
0
 def __init__(self, ident, topicheader, uri = 'localhost', port = 1883):
     self.uri = uri
     self.port = port
     self.ident = ident
     
     self.topicheader = topicheader+ '/' + self.ident
     self.outputRegex = re.compile(self.topicheader + "/output/pin/(\d*)", re.IGNORECASE)
     
     
     self.mos = mosquitto.Mosquitto(self.ident)
     self.mos.on_message = self.on_message # register for callback
     self.connect()
     
     
     pfio.init()
     self.inputpins = pfio.read_input()
Exemplo n.º 18
0
def index(request):
    piface_detected = True
    piface_error_msg = ""

    try:
        pfio.init()
    except pfio.InitError as error:
        piface_detected = False
        piface_error_msg = error

    return render_to_response("httpiface/index.html",
            {'button_range' : range(8),
                'led_range' : range(4),
                'piface_detected' : piface_detected,
                'piface_error_msg' : piface_error_msg},
            context_instance=RequestContext(request))
Exemplo n.º 19
0
def wait_for_button_press(card_swipe_data):
    global pfinitalized
    p("Thread started---------")
    if False == pfinitalized:
        pf.init()
        p("pf initialized<-----------------")
        pfinitalized = True
    end_time = time.time() + button_press_wait_time
    while time.time() < end_time:
        button_index = button_pressed()
        p("-After-", str(button_index), time.time())
        if button_index > -1:
            server_call(card_swipe_data, button_index)
            button_index = -1
            break
        time.sleep(0.1)
    p("---------------Thread Ended---------------")
Exemplo n.º 20
0
def index(request):
    piface_detected = True
    piface_error_msg = ""

    try:
        pfio.init()
    except pfio.InitError as error:
        piface_detected = False
        piface_error_msg = error

    return render_to_response("httpiface/index.html", {
        'button_range': range(8),
        'led_range': range(4),
        'piface_detected': piface_detected,
        'piface_error_msg': piface_error_msg
    },
                              context_instance=RequestContext(request))
def decimalToBinaryConverter(numberToConver):    

    pfio.init()
    binaryListOfNumberToConvert=list(bin(numberToConver))
    binaryListOfBinaryNumber = []
     
    for i in range(len(binaryListOfNumberToConvert)-1, 0, -1):
        if binaryListOfNumberToConvert[i] == 'b':
            break
       
        binaryListOfBinaryNumber.append(binaryListOfNumberToConvert[i])
       
    for i in range(len(binaryListOfBinaryNumber),8):
        binaryListOfBinaryNumber.append(0)
    
    for i in range(7,-1,-1):
        if binaryListOfBinaryNumber[i] == "1":
            pfio.digital_write(i,1)
        else:
            pfio.digital_write(i,0)        	
Exemplo n.º 22
0
def start():
    global verbose
    listenerport = 0
    broadcastport = 0

    # parse out the command line arguments
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hl:b:v",
                                   ["help", "listenerport=", "broadcastport="])
    except getopt.GetoptError:
        print_usage(sys.argv[0])
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-v":
            verbose = True
        elif opt in ("-h", "--help"):
            print_usage(sys.argv[0])
            sys.exit()
        elif opt in ("-l", "--listenerport"):
            listenerport = int(arg)
        elif opt in ("-b", "--broadcastport"):
            broadcastport = int(arg)

    # initialise the PiFace IO library
    pfio.init()

    # start the client thread
    if (broadcastport != 0):
        if (verbose):
            print "Starting monitor on %d..." % broadcastport
        thread.start_new_thread(start_client, (broadcastport, ))

    # start the listener in this thread
    if (listenerport != 0):
        if (verbose):
            print "Starting listener on %d..." % listenerport
        server = SocketServer.UDPServer((get_hostname(), listenerport),
                                        UDPHandler)
        server.serve_forever()
Exemplo n.º 23
0
def start():
    global verbose
    listenerport = 0
    broadcastport = 0

    # parse out the command line arguments
    try:
        opts, args = getopt.getopt(sys.argv[1:],"hl:b:v",["help","listenerport=","broadcastport="])
    except getopt.GetoptError:
        print_usage(sys.argv[0])
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-v":
            verbose = True
        elif opt in ("-h", "--help"):
            print_usage(sys.argv[0])
            sys.exit()
        elif opt in ("-l", "--listenerport"):
            listenerport = int(arg)
        elif opt in ("-b", "--broadcastport"):
            broadcastport = int(arg)

    # initialise the PiFace IO library
    pfio.init()

    # start the client thread
    if (broadcastport != 0):
        if (verbose):
            print "Starting monitor on %d..." % broadcastport
        thread.start_new_thread(start_client, (broadcastport, ))

    # start the listener in this thread
    if (listenerport != 0):
        if (verbose):
            print "Starting listener on %d..." % listenerport
        server = SocketServer.UDPServer((get_hostname(), listenerport), UDPHandler)
        server.serve_forever()
Exemplo n.º 24
0
#!/usr/bin/env python
"""
simon.py
Simple simon game for use with pfio and the RaspberryPi interface (piface)

Objective of the game: You must remember an ever increasing sequence of flashes and input them correctly*

"""

from time import sleep  # for delays
import random  # for random sequence generation
import piface.pfio as pfio  # piface library

pfio.init()  # initialise pfio (sets up the spi transfers)

colours = ["Red", "Green", "Blue", "Yellow",
           "White"]  # colour names for printing to screen


def next_colour():
    """ choses a random number between 1 and 5 to represent the coloured leds and their corresponding buttons"""
    return random.randint(1, 5)


first_in_sequence = next_colour()  # create the first colour in the sequence

array = [first_in_sequence]  # add the first colour to the array

game = 1  # keep track of game active (1 for active, 0 for game over)
score = 0  # keep track of player's score
screen_output = False  # choice to write colours and cues to the screen
Exemplo n.º 25
0
def open_evsco_valve():
    pfio.init()
    pfio.digital_write(1, 1)
    time.sleep(4)
    pfio.digital_write(1, 0)
Exemplo n.º 26
0
#!/usr/bin/python

# This script flashes output 2 LED's
from time import sleep
import piface.pfio as pfio
pfio.init() # Initialise PiFace #Comment out if used as nested PiFace Script

while(True): # Variable to ensure the script runs indefinatly
  pfio.digital_write (2,1) # LED On
  sleep (0.5) # Wait Time
  pfio.digital_write (2,0) # LED off
  sleep (0.5) # Wait time
Exemplo n.º 27
0
# This scrip runs the motor out and then back in again by closing relay output 0
import piface.pfio as pfio # Import PiFace
from time import sleep
pfio.init() # initialise PiFace # Comment out if using as nested script

for x in range (0, 5): # loop x number of times
 pfio.digital_write (0,1) # motor out
 print "button pressed - motor out"
 sleep (1) # hold time
 pfio.digital_write (0,0) # release button
#print "released"
#sleep (3) # wait time
#print "running"
#pfio.digital_write (0,1) # motor stop
#print "button pressed - motor stopped"
#sleep (1) # hold time
#pfio.digital_write (0,0) # release button
#print "move in complete waiting"

#sleep (10) # in dead waiting
#print "waiting"

#pfio.digital_write (0,1) # motor in
#print "button pressed - motor in"
#sleep (1) # hold time
#pfio.digital_write (0,0) # release button
#print "released"
#sleep (4) # wait time
#print "running"
#pfio.digital_write (0,1) # motor stop
#print "button pressed - motor stopped"
Exemplo n.º 28
0
def close_evsco_valve():
    pfio.init()
    pfio.digital_write(0, 1)
    time.sleep(4)
    pfio.digital_write(0, 0)
Exemplo n.º 29
0
'''
Author: Graham Montgomery
Western State Colorado University

This file starts the piface controller and thats all
Will be imported by every file
'''

import piface.pfio as pi

pi.init()
Exemplo n.º 30
0
#!/usr/bin/env python

from time import sleep
import piface.pfio as io

io.init()
Leds = []
count = True

for i in range(1,9):
	Leds.append(io.LED(i))

def toggle(light):
	light.turn_on()
	sleep(.05)
	light.turn_off()

while True:
	""" Count up the leds """
	if count:
		for n in Leds:
			toggle(n)
		count = False

	"""Count Down the leds"""
	if count == False:
		for n in reversed(Leds):
			toggle(n)
		count = True

# vim:ts=2:sw=2:sts=2:et:ft=python
Exemplo n.º 31
0
#!/usr/bin/python

# This script flashes output 2 LED's
from time import sleep
import piface.pfio as pfio

pfio.init()  # Initialise PiFace #Comment out if used as nested PiFace Script

while (True):  # Variable to ensure the script runs indefinatly
    pfio.digital_write(2, 1)  # LED On
    sleep(0.5)  # Wait Time
    pfio.digital_write(2, 0)  # LED off
    sleep(0.5)  # Wait time
Exemplo n.º 32
0
#!/usr/bin/env python

import piface.pfio as pfio
import time

pfio.init()
score = 0
led = 0

# Ask user name and store to variable name

name = raw_input("Please type your name: ")

print "Hi %s." % (name)

# Play? Yes or No

play = raw_input("Are you ready to play? (Yes/No) ")

if ((play) == "Yes"):
    print "OK"
    time.sleep(0.5)
    print "Ready ..."
    time.sleep(0.5)
    print "Let's go!"
    time.sleep(0.2)
    print ""
else:
    print "Gutted"
    time.sleep(1)
    print "Bye"
Exemplo n.º 33
0
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.

import unittest
import sched, time
import piface.pfio as piface
import Globals
from PiObjects import *
from Signal import *
from Functions import *

piface.init()

def heartBeat(ct, events):
    #print "objects " + str(len(Globals.worldObjects))
    Globals.dt = ct - Globals.currentTime
    Globals.currentTime = ct
    Globals.events = events
    Globals.thunks = []
    for worldObject in Globals.worldObjects:
        #print("Updating object: " + repr(worldObject))
        #print repr(worldObject)
        Globals.thunks.extend(worldObject._update())
    for f in Globals.thunks:
        f()
    for obj in Globals.newObjects:
        #print("Adding object: " + repr(obj))
        Globals.worldObjects.append(obj)
    Globals.newObjects = []
    for obj in Globals.worldObjects:
Exemplo n.º 34
0
def ResetLights():
    pfio.init()
Exemplo n.º 35
0
def init():
    """Initialises the raspberry pi farm"""
    pfio.init()
Exemplo n.º 36
0
# main.py
# David R. Albrecht for Prefiat LLC
# Runs the program

import statemanager
import gpiomanager
import apimanager
import datetime
import piface.pfio as pfio_interface
import states
import sys
import os

pfio_interface.init()
gpio_mgr = gpiomanager.GPIOManager(pfio_interface)
gis_api = apimanager.GISAPIManager()

try:
    # Ensure enough space on the root device of the volume
    st = os.statvfs('/')
    free_space_mb = st.f_bavail * st.f_frsize / 1024 / 1024
    if free_space_mb < 128:
        raise Exception("Less than 128MB disk space free, raising system trouble state")
    
    current_state = statemanager.parse_state_file("state_file.yaml")
    current_state = current_state.next(gpio_mgr, gis_api)
except:
    current_state = states.TroubleState(datetime.datetime.now(), datetime.datetime.now(), 0, sys.exc_info()[0])
finally:
    current_state.set_outputs(gpio_mgr)
    statemanager.write_state_stdout(current_state)
#!/usr/bin/env python

# code modified from Andrew Robinson's chapter in Raspberry Pi Projects:"The Techno-BirdBox: A Wildlife Monitor"
# code presented in the book does not work due to inclusion of printing errors.
# code corrected & modified below
# v2 03 May 2014


import piface.pfio as p
import datetime
import time
p.init()

#Define the inputs/output pin number that the beam is connected to
INNER_BEAM = 1
OUTER_BEAM = 0
#STATUS_LED = 2

#keeps track of the last state the beam was in
#used to know if a new event has occurred

innerBeamStateWasBroken = False
outerBeamStateWasBroken = False

#function to return the current time, formatted as
# e.g. 13 Jun 2013 :: 572
def getFormattedTime():
    now = datetime.datetime.now()
    return now.strftime("%d %b %Y %H:%M:%S.") + str(int(round(now.microsecond/1000.0)))

#generate and record an event to file
Exemplo n.º 38
0
def init():
    """Initialises the raspberry pi farm"""
    pfio.init()
Exemplo n.º 39
0
# This scrip runs the motor out and then back in again by closing relay output 0
import piface.pfio as pfio  # Import PiFace
from time import sleep
pfio.init()  # initialise PiFace # Comment out if using as nested script

for x in range(0, 5):  # loop x number of times
    pfio.digital_write(0, 1)  # motor out
    print "button pressed - motor out"
    sleep(1)  # hold time
    pfio.digital_write(0, 0)  # release button
#print "released"
#sleep (3) # wait time
#print "running"
#pfio.digital_write (0,1) # motor stop
#print "button pressed - motor stopped"
#sleep (1) # hold time
#pfio.digital_write (0,0) # release button
#print "move in complete waiting"

#sleep (10) # in dead waiting
#print "waiting"

#pfio.digital_write (0,1) # motor in
#print "button pressed - motor in"
#sleep (1) # hold time
#pfio.digital_write (0,0) # release button
#print "released"
#sleep (4) # wait time
#print "running"
#pfio.digital_write (0,1) # motor stop
#print "button pressed - motor stopped"
Exemplo n.º 40
0
#
# Python script to wait until certain button is pressed
# returns button pressed and turns on a light to indicate it (for testing) 
# @Pierre
# 
import piface.pfio as pfio

pfio.init()

button = pfio.read_input()
while button == 0:
    button = pfio.read_input()
pin_number = pfio.get_pin_number(button)
pfio.digital_write(0,1)
print pin_number
Exemplo n.º 41
0
	def __init__(self, pfio, pin):
		pfio.init()
		self.pfio = pfio
		self.relay_pin = pin
Exemplo n.º 42
0
"""
simon.py
Simple simon game for use with pfio and the RaspberryPi interface (piface)

Objective of the game: You must remember an ever increasing sequence of flashes and input them correctly*

"""

from time import sleep 		# for delays
import random			# for random sequence generation
import piface.pfio as pfio			# piface library




pfio.init()			# initialise pfio (sets up the spi transfers)

colours = ["Red","Green","Blue","Yellow","White"]		# colour names for printing to screen



def next_colour():
	""" choses a random number between 1 and 5 to represent the coloured leds and their corresponding buttons"""
	return random.randint(1,5) 



first_in_sequence = next_colour()	# create the first colour in the sequence

array = [first_in_sequence]		# add the first colour to the array
Exemplo n.º 43
0
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.

import unittest
import sched, time
import piface.pfio as piface
import Globals
from PiObjects import *
from Signal import *
from Functions import *

piface.init()


def heartBeat(ct, events):
    #print "objects " + str(len(Globals.worldObjects))
    Globals.dt = ct - Globals.currentTime
    Globals.currentTime = ct
    Globals.events = events
    Globals.thunks = []
    for worldObject in Globals.worldObjects:
        #print("Updating object: " + repr(worldObject))
        #print repr(worldObject)
        Globals.thunks.extend(worldObject._update())
    for f in Globals.thunks:
        f()
    for obj in Globals.newObjects:
        #print("Adding object: " + repr(obj))
        Globals.worldObjects.append(obj)
    Globals.newObjects = []