Exemplo n.º 1
0
    def __init__(self):

        self.port = "COM3"

        self.board = Arduino(self.port)
        time.sleep(3.0)
        iterator = util.Iterator(self.board)
        iterator.start()

        # Initialize Pins or Motor Shield
        self.pwmA = self.board.get_pin('d:3:p')
        self.pwmB = self.board.get_pin('d:11:p')
        self.brakeA = self.board.get_pin('d:9:o')
        self.brakeB = self.board.get_pin('d:8:o')
        self.dirA = self.board.get_pin('d:12:o')
        self.dirB = self.board.get_pin('d:13:o')

        # Release Brakes and set PMW
        self.pwmA.write(1)
        self.pwmB.write(1)
        self.brakeA.write(0)
        self.brakeB.write(0)

        # Dimension of Instruments
        self.radiusMotor = 0.03  # in meters
        self.radiusTube = 0.0015  # in meters
        self.steps = 200  # numbers of step of the stepper_motor per rotation
Exemplo n.º 2
0
 def __init__(self, arduino, pin: str):
     self.MAX_TEMP = 40
     board = arduino
     self.iterator = util.Iterator(board)
     self.iterator.setDaemon(True)
     self.iterator.start()
     self.pin = board.get_pin(pin)
Exemplo n.º 3
0
    def __init__(self, port=None):
        self.T0, self.T1, self.LDR, self.PIR = None, None, None, None
        self.LDR_TC, self.LDR_BR, self.LDR_BL = None, None, None
        self.pos_x = None

        self.t0 = time.time()

        self.port = port or LEO_COMM_PORT
        self.leonardo = Arduino(self.port)

        self.it = util.Iterator(self.leonardo)
        self.it.start()

        self.pin_t0 = self.leonardo.get_pin("a:0:i")
        self.pin_t1 = self.leonardo.get_pin("a:1:i")
        self.pin_ldr = self.leonardo.get_pin("a:2:i")
        self.pin_pir = self.leonardo.get_pin("d:9:i")
        self.pin_led = self.leonardo.get_pin("d:13:o")
        self.pir_counter = 0
        self.pir_previous = None
        self.pin_ldr_tc = self.leonardo.get_pin("a:3:i")
        self.pin_ldr_br = self.leonardo.get_pin("a:4:i")
        self.pin_ldr_bl = self.leonardo.get_pin("a:5:i")

        for nm in ("t0 t1 ldr pir ldr_tc ldr_br ldr_bl".split()):
            item = getattr(self, "pin_" + nm)
            item.enable_reporting()
            item.read()  # first read is usually None

        self.read()
Exemplo n.º 4
0
 def __init__(self):
     #board
     #self.board = Arduino('/dev/ttyACM0')
     self.board = Arduino('/dev/ttyUSB0') #for NANO 328
     self.it = util.Iterator(self.board)
     self.it.start()
     self.board.analog[0].enable_reporting()
 
 	#pins
     self.monitor_pin = self.board.get_pin('d:3:p')
     self.stim_pin = self.board.get_pin('d:6:p')
     self.off_on = self.board.get_pin('d:9:p')
     self.trigger = self.board.get_pin('d:5:p')
 
 	#monitor details
     self.res = [1280,1024]
     self.monitor_width = 37.5 #cm
     self.monitor_distance = 14 #14 #14=small box) #cm from middle #20 #20=normal box) #cm from middle
     self.mon = monitors.Monitor("mymon", distance = self.monitor_distance, width = self.monitor_width)
     self.mon.currentCalib['sizePix'] = [self.res[0], self.res[1]]
     self.mon.saveMon()
     
     #Psychopy windows
     self.window1 = visual.Window(size=[self.res[0],self.res[1]],monitor=self.mon, fullscr = False,allowGUI=False, units="deg", screen =1)
     self.window2 = visual.Window(size=[self.res[0],self.res[1]],monitor=self.mon, fullscr = False,allowGUI=False, units="deg", screen =2)
     
     #can't change gamma values; color set above middle gray to maintain the same brightness as grating
     self.fixation1 = visual.GratingStim(win=self.window1, size=300, colorSpace ='rgb255', pos=[0,0], sf=0, color=(143,143,143))
     self.fixation2 = visual.GratingStim(win=self.window2, size=300, colorSpace ='rgb255', pos=[0,0], sf=0, color=(143,143,143))
Exemplo n.º 5
0
	def __init__(self,port):
		print(port)
		self.board=Arduino(port)
		self.it=util.Iterator(self.board)
		self.it.start()
		time.sleep(2)
		print("ok")
Exemplo n.º 6
0
def setUpArduino():
    global rLED
    global lLED
    global lickPin
    global rewardPin
    global it
    global board

    ports = list(serial.tools.list_ports.comports())
    connectedDevice = None
    for p in ports:
        if 'Arduino' in p[1]:
            try:
                connectedDevice = Arduino(p[0])
                print "Connected to" + str(connectedDevice)
                break
            except serial.SerialException:
                print "Arduino detected but unable to connect to " + p[0]
    if connectedDevice is None:
        exit("Failed to connect to Arduino")

    board = connectedDevice
    lickPin = board.get_pin("a:0:i")
    greenLEDRight = board.get_pin("d:5:p")
    blueLEDRight = board.get_pin("d:6:p")
    greenLEDLeft = board.get_pin("d:9:p")
    blueLEDLeft = board.get_pin("d:10:p")
    rewardPin = board.get_pin("d:8:o")
    it = util.Iterator(board)
    it.daemon = True
    it.start()
    lickPin.enable_reporting()

    rLED = greenLEDRight
    lLED = greenLEDLeft
Exemplo n.º 7
0
def btn_port_set_click(event):
    def func_msgbox_destroy():
        msgbox.destroy()

    msgbox = Message(window, width=300)
    msgbox['text'] = 'Waitting ...'
    msgbox.grid(row=4, column=1)

    port = txtbox_port.get()
    try:
        global board
        board = arduino(port)
        iterator = util.Iterator(board)
        iterator.start()
        lbl_connection_status['text'] = 'Connected'
        frm_fasele['bg'] = 'blue'
        msgbox['text'] = 'Connected'
        msgbox.grid(row=4, column=1)
        msgbox.after(2500, func_msgbox_destroy)
    except:
        lbl_connection_status['text'] = 'DisConnected'
        frm_fasele['bg'] = 'red'
        msgbox['text'] = 'Can`t Connect. Port Name Can`t Find.'
        msgbox.grid(row=4, column=1)
        msgbox.after(5000, func_msgbox_destroy)
Exemplo n.º 8
0
def readdatafromArduino(stop):
    global datafromfile
    # load default values from
    file = open("/var/www/html/lifeboxdata", "r")
    datafromfile = file.read().split("|")
    # remove
    board = ArduinoMega('/dev/ttyACM0')
    it = util.Iterator(board)
    it.start()
    for i in range(0, 11):
        board.analog[i].enable_reporting()
    while not stop:
        #for i in range (0,11):
        #if board.analog[i].read() is not None:
        #print("Pin:"+str(i)+" Value:"+str(int(board.analog[i].read()*1000)))
        if board.analog[i].read() is not None:
            #datafromfile[16] = board.analog[8].read() # plants life expectancy
            #datafromfile[20] = board.analog[10].read() # plants energy generation
            print("Value:" + str(int(board.analog[9].read() * 1000)))
            datafromfile[17] = int(
                map(int(board.analog[9].read() * 1000), 0, 1000, 1,
                    2000))  # plants nearborn chances
            print("Return:" + str(datafromfile[17]))
            #datafromfile[6] = board.analog[3].read() # sp1 gathering
            #datafromfile[5] = board.analog[2].read() # sp1 efficency
            #datafromfile[0] = board.analog[0].read() # sp1 life exp
            #datafromfile[1] = board.analog[1].read() # sp1 nearborn chances
            #datafromfile[14] = board.analog[7].read() # sp2 gathering
            #datafromfile[13] = board.analog[6].read() # sp2 efficency
            #datafromfile[8] = board.analog[4].read() # sp2 life exp
            #datafromfile[9] = board.analog[5].read() # sp2 nearborn chances
        time.sleep(1)
def RunSensor():
	print "wait for around 10 seconds..."
	#set the board
	board = Arduino('/dev/ttyS0')

	#print "sleeping..."
	sleep(2) #very important.

	#start a thread
	it = util.Iterator(board)
	it.start()
 	
	#set the analog input pin on the Arduino ( Sleepy Pi )
	a0 = board.get_pin('a:0:i')
 
	try:
		#ignore first few 'nonetype' garbage values
		for i in range(10):
 	      		garbage = a0.read()
			#print garbage
			sleep(0.1)

		#continually read values
    		while True:
			v = a0.read()*1000
			sleep(0.5)
        		print "Pressure: ", v, " kPa"
    		
	except KeyboardInterrupt:
    		board.exit()
    		os._exit()
Exemplo n.º 10
0
    def __init__(self):

        logging.basicConfig(filename='iota.log', level=logging.DEBUG)
        #logging.basicConfig(stream=sys.__stdout__, level=logging.INFO)
        self.log = logging
        self.log.info('init(): creating an instance of Iota')
        self.connect()
        self.log.info('init(): retrieving AWS Shadow')
        self.shadow = self.client.createShadowHandlerWithName("iota", True)
        self.log.info('init(): registering delta callback')
        self.log.info('init(): Iota created')

        # Setup the Arduino Firmata interface
        self.log.info('init(): setting-up firmata')
        self.board = None
        for i in range(0, 10):
            if os.path.exists('/dev/ttyACM' + str(i)):
                self.log.info('init(): firmata: found serial device: ' +
                              '/dev/ttyACM' + str(i))
                self.board = Arduino('/dev/ttyACM' + str(i))
                break

        self.log.info('init(): getting iterator for board')
        it = util.Iterator(self.board)
        it.start()
        self.log.info('init(): started iterator for board')
        self.board.analog[0].enable_reporting()
        self.board.analog[1].enable_reporting()
        self.d7 = self.board.get_pin('d:7:i')
        self.d8 = self.board.get_pin('d:8:o')
        self.d9 = self.board.get_pin('d:9:o')
        self.log.info('init(): finished firmata setup')
Exemplo n.º 11
0
def open_dev(encoder_pins):
    '''
    Opens communication with Arduino, GPIO and lcd
    :param encoder_pins: contains the GPIO pins to the encoder
    :type encoder_pins: list of integer
    
    :returns: lcd object, arduino object and iterator
    :rtype: tuple
    '''
    # LCD
    lcd = Adafruit_CharLCDPlate()
    lcd.clear()

    # GPIO
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(encoder_pins[0], GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(encoder_pins[1], GPIO.IN, pull_up_down=GPIO.PUD_UP)

    # Arduino
    # Init Arduino and iterator
    lcd.message("Connection de \nl'Arduino ...")
    board = Arduino('/dev/ttyACM0')
    lcd.clear()
    print('Arduino connected')
    lcd.message("Arduino connecte !")
    # Création itérateur
    iter8 = util.Iterator(board)
    iter8.start()

    dev = (
        lcd,
        board,
    )
    return dev
Exemplo n.º 12
0
    def open_connection(self):
        if self.connectionStatus == ConnectionStatus.Open:
            print(self.connectionStatus)
            return None
        try:
            if self.board is None:
                print(
                    "Initializing board object specified connected to port {} ..."
                    .format(self.portName))
                self.board = Arduino(self.portName)
                print("Board object created!")
            if self._iterator is None:
                print(
                    "Initializing iterator object to prevent overflow serial buffer ..."
                )
                self._iterator = util.Iterator(self.board)
                print("Iterator object created!")
                self._iterator.start()
            self.connectionStatus = ConnectionStatus.Open
            print("{}, {} , {} ".format(self.connectionStatus,
                                        self.connectionType, self.portName))

        except serial.SerialException as e:
            print(e.args[0])
            if self.board is not None:
                self.board.exit()
            raise SystemExit
Exemplo n.º 13
0
    def connect(self, port: str, board: str="uno") -> None:
        """
        Initialize a connection with the arduino.

        Parameters
        ----------
        port : str
            Computer serial port to which the arduino is connected
        board : str, optional
            | The type of the arduino that is being used:
            | ``uno``: `Arduino Uno <https://store.arduino.cc/products/arduino-uno-rev3>`_
            | ``mega``: `Arduino Mega <https://store.arduino.cc/products/arduino-mega-2560-rev3>`_
            | ``due``: `Arduino Due <https://store.arduino.cc/products/arduino-due>`_
            | ``nano``: `Arduino Nano <https://store.arduino.cc/products/arduino-nano>`_
        """
        self.port = port

        if board == "uno":
            self.board = Arduino(self.port)
        elif board == "mega":
            self.board = ArduinoMega(self.port)
        elif board == "due":
            self.board = ArduinoDue(self.port)
        elif board == "nano":
            self.board = ArduinoNano(self.port)
        else:
            raise UnknownBoardException("Unknown board " + board)
        self.it = util.Iterator(self.board)
        self.it.start()
Exemplo n.º 14
0
 def __init__(self,port,resistor,duration,perSecondCount):
     # initiate the Arduino
     self.board = Arduino(port)
     self.data = {}
     self.channels = []
     self.index = 0
     
     self.data['res'] = resistor
     
     # iterator to read from serial
     it = util.Iterator(self.board)
     it.start()
     resLen = len(resistor)
     
     # creates Channels depending on how many drop-down resistors given
     for i in range(0,resLen):
         name = str(i)
         chan = Channel(self.board,name,resistor[i],duration,perSecondCount)
         print('Channel '+name+':', chan.readVoltage(),'V')
         self.data[name] = chan.data
         self.channels.append(chan)
             
     self.len = len(self.channels)
     # output if everything read correctly
     print('readings nominal')
Exemplo n.º 15
0
def READ_DONE_BIT():
    thread = util.Iterator(board)
    thread.start()
    trigger = False
    while(trigger is not True):
        trigger = done_pin.read()
        time.sleep(.0001)
Exemplo n.º 16
0
def READ_FLOW_RATE_SENSOR():
    pulsecount = 0
    calibration_factor = 140390.3604
    total_MilliLiters = 0.0
    
    Trigger = True
    
    flowReadOld = flow_sensor.read()
    oldTime = time.time()
    thread = util.Iterator(board)
    thread.start()
            
    while(Trigger):
        old = flow_sensor.read()
        time.sleep(.0001)
        if(flow_sensor.read() != old):
            pulsecount = pulsecount + 1
                
        if((time.time() - oldTime) > 1.0):
            print("Pulse Count: " + str(pulsecount))
            
            flow_rate = ((1000.0 / (time.time() - oldTime) * pulsecount) / calibration_factor)
            print("Flow Rate L/min: " + str(flow_rate))

            # Divide the flow rate in liters/minute by 60 to determine
            # how many liters have passed through the sensor in this 1
            # second interval, then multiple by 1000 to covert to mL
            flow_MilliLiters = (flow_rate / 60) * 1000
            
            total_MilliLiters = total_MilliLiters + flow_MilliLiters
            print("Total mL: " + str(total_MilliLiters))

            oldTime = time.time()
            pulsecount = 0
    return int(total_MilliLiters)
def excution_irrigation():
    """
    Performs irrigation regardless of soil condition.
    :return:
    """
    try:
        Board = Arduino('COM4')  # Defines the port where the Arduino is
        it = util.Iterator(Board)  # Controls arduino port readings
        it.start()  # Starts communication with the arduino.

        # Sets relay pins to OUTPUT
        Board.get_pin('d:10:o')

        # relay starts off
        Board.digital[10].write(1)

        # Defines analog port -> sensor
        Board.get_pin('a:0:i')

        time.sleep(0.5)

        Board.digital[10].write(0)  # turn on the relay
        time.sleep(2.5)  # Hold open for 3 seconds
        Board.digital[10].write(1)  # turn off the relay

    except Exception as e:
        print(e)
Exemplo n.º 18
0
 def __init__(self,
              serial_port,
              pins,
              positions,
              hand_delay=.2,
              quarter_turn_delay=.4):
     """A robotic cube manipulator. Delays are in seconds."""
     sys.stdout.write("Connecting to Arduino... ")  #  Print w/o \n
     arduino = Arduino(serial_port)
     print "Done."
     print "Configuring Arduino..."
     iterator = util.Iterator(arduino)
     iterator.start()
     sys.stdout.write("    Configuring down_claw... ")  #  Print w/o \n
     self.claw_down = Claw(arduino, pins[0], pins[1], positions[0:5],
                           hand_delay, quarter_turn_delay)
     print "Done."
     sys.stdout.write("    Configuring up_claw... ")  #  Print w/o \n
     self.claw_right = Claw(arduino, pins[2], pins[3], positions[5:10],
                            hand_delay, quarter_turn_delay)
     print "Done."
     print "Configured."
     self.orient = {
         'D': 'D',
         'F': 'F',
         'R': 'R',
         'B': 'B',
         'L': 'L',
         'U': 'U'
     }
     #  Open the claws and put them in the correct orientation without a delay
     self.claw_down.wrist.write(self.claw_down.home_turn_deg)
     self.claw_down.hand.write(self.claw_down.open_hand_deg)
     self.claw_right.wrist.write(self.claw_right.home_turn_deg)
     self.claw_right.hand.write(self.claw_right.open_hand_deg)
Exemplo n.º 19
0
def setup():
    # setup runs once
    board = Arduino('/dev/ttyACM0')
    board.digital[13].write(1)  # sets the onboard LED to ON.

    analog_0 = board.get_pin('a:0:i')  # pot pin
    pin0 = board.get_pin('d:8:o')  # pin0 for motor 1
    pin1 = board.get_pin('d:9:o')  # pin1 for motor 1
    pin2 = board.get_pin('d:10:o')  # pin2 for motor 2
    pin3 = board.get_pin('d:11:o')  # pin3 for motor 2
    pwm1 = board.get_pin('d:5:p')  # pwm pin for motor 1
    pwm2 = board.get_pin('d:6:p')  # pwm pin for motor 2

    # start these values with the correct values for a forward shot.
    pin0state = 0
    pin1state = 0
    pin2state = 0
    pin3state = 0

    pin0.write(pin0state)
    pin1.write(pin1state)
    pin2.write(pin2state)
    pin3.write(pin3state)

    iter = util.Iterator(board)
    iter.start()
    board.analog[0].enable_reporting()  # change to be port of potentiometer.
    print('done!')
Exemplo n.º 20
0
def initiate_arduino():
    """ Sets up the Arduino port and pins. Returns a microController object for saving data about the Arduino."""
    # Pyfirmata
    board = Arduino("COM4")
    it = util.Iterator(board)
    it.start()
    # Setting up pins on the Arduino board
    red_led = board.get_pin('d:6:o')
    blue_led = board.get_pin('d:10:o')
    temp_sensor = board.get_pin('a:0:i')
    temp_sensor.enable_reporting()
    photo_sensor = board.get_pin('a:2:i')
    photo_sensor.enable_reporting()
    center_button = board.get_pin('d:13:i')
    center_button.enable_reporting()

    # Starting values
    time_start = time.time()  # Used for the interval
    debounce_start = time.time()  # Used for the button bouncing

    # Custom object to store info of the Arduino micro controller
    micro_controller = MicroController(center_button, debounce_start,
                                       photo_sensor, temp_sensor, time_start,
                                       red_led, blue_led)

    time.sleep(
        1
    )  # Important for pyfirmata to initialize before trying to read values
    print("Ready!")

    return micro_controller
Exemplo n.º 21
0
def startup_routine():
    """
    Initializes the communication port with the JUAMI potentistat

    Returns
    -------
    Map of hardware
    com : string
      the name of the port with the potentiostat on it
    board : serial communication for board
    a0 : location of analog read pin 0
    a2 : location of analog read pin 2
    d9 : location of digital pwm pin 9
    """

    print("Welcome to the JUAMI pytentiostat interface!")
    connect = input("Press enter to connect to a JUAMI potentiostat.")
    com = _load_arduino()
    board = _initialize_arduino(com)

    it = util.Iterator(board)
    it.start()

    # Setup Arduino pins
    a0 = board.get_pin("a:0:i")
    a2 = board.get_pin("a:2:i")
    d9 = board.get_pin("d:9:p")

    return com, board, a0, a2, d9
Exemplo n.º 22
0
 def board_d_reporting(self):
     iterator = util.Iterator(self.board)
     iterator.start()
     sleep(1)
     self.button = self.board.get_pin('d:4:i')
     sleep(1)
     self.button.enable_reporting()
     sleep(1)
Exemplo n.º 23
0
 def __init__(self, arduino, pin: str):
     self.MAX_VOLTAGE = 4.2
     self.MIN_VOLTAGE = 3.0
     board = arduino
     self.iterator = util.Iterator(board)
     self.iterator.setDaemon(True)
     self.iterator.start()
     self.pin = board.get_pin(pin)
Exemplo n.º 24
0
    def __init__(self, app, parent=None):
        super(Form, self).__init__(parent)

        # Pyfirmata code
        self.potPin = 0
        self.servoPin = 9
        self.ledPin = 13
        self.board = Arduino('/dev/ttyACM0')

        iterator = util.Iterator(self.board)
        iterator.start()

        self.board.analog[self.potPin].enable_reporting()
        #self.board.digital[self.servoPin].mode = SERVO
        
        # PyQT Code
        servoLabel = QLabel("Servo")
        self.servoDial = QDial()
        self.servoDial.setMinimum(0)
        self.servoDial.setMaximum(180)
        self.servoPosition = 0

        potLabel = QLabel("Potenciometro")
        self.potSlider = QSlider()
        self.potSlider.setMinimum(0)
        self.potSlider.setMaximum(1000)

        ledLabel = QLabel("Led 13")
        self.ledButton = QPushButton('Light')

        grid = QGridLayout()
        grid.addWidget(servoLabel, 0, 0)
        grid.addWidget(potLabel, 0, 1)
        grid.addWidget(ledLabel, 0, 2)
        grid.addWidget(self.servoDial, 1, 0)
        grid.addWidget(self.potSlider, 1, 1)
        grid.addWidget(self.ledButton, 1, 2)
        self.setLayout(grid)

        self.connect(self.ledButton,
                SIGNAL("pressed()"), self.ledOn)
        self.connect(self.ledButton,
                SIGNAL("released()"), self.ledOff)

        #self.connect(self.servoDial,
                #SIGNAL("valueChanged(int)"), self.moveServo)

        self.connect(app,
                SIGNAL("lastWindowClosed()"), self.cleanup)

        self.timer = QTimer()
        self.timer.setInterval(500)

        self.connect(self.timer, SIGNAL("timeout()"), self.readPot)

        self.setWindowTitle("Arduino")

        self.timer.start()
Exemplo n.º 25
0
def initialize_arduino_reading(board, analog_ports=None, digital_ports=None):
    it = util.Iterator(board)
    if analog_ports:
        for port in analog_ports:
            board.analog[port].enable_reporting()
    if digital_ports:
        for port in digital_ports:
            board.digital[port].enable_reporting()
    it.start()
    def setup():
        ArduinopiOperator.board = Arduino(PORT)
        it = util.Iterator(ArduinopiOperator.board)
        it.start()

        all_sensors = config["sensors"]

        for sensor_key in all_sensors:
            ArduinopiOperator.board.analog[all_sensors[sensor_key]["pin"]].enable_reporting()
Exemplo n.º 27
0
def main():
    board = Arduino('COM3')
    board.add_cmd_handler(pyfirmata.pyfirmata.STRING_DATA, on_string_received)

    iter = util.Iterator(board)
    iter.start()


    write_loop(board)
Exemplo n.º 28
0
def PRESSURE_SENSOR_READ():
    print("Reading CO2 Pressure")
    it = util.Iterator(board)
    it.start()
    board.analog[pressure_sensor_pin].enable_reporting()
    pressureVal = board.analog[pressure_sensor_pin].read()
    voltage = (pressure * 5.0) / 1023
    pressure_pascal = 300000 * (float(voltage) - 0.5)
    pressure_psi = pressure_pascal / 6895
    print("Pressure Reading: " + str(pressure_psi) + " psi")
Exemplo n.º 29
0
def create_arduino_connection(port='COM13'):
    try:
        port = port
        board = Arduino(port)
        sleep(3)
        it = util.Iterator()
        it.start()
        return True
    except serial.serialutil.SerialException:
        return False
Exemplo n.º 30
0
 def __init__(self, widget):
     super(FirmataThread, self).__init__()
     self.board = ArduinoMega('/dev/ttyACM0')
     self.it = util.Iterator(self.board)
     self.it.start()
     self.board.analog[0].enable_reporting()
     self.board.analog[1].enable_reporting()
     self.stopNow = False
     self.widget = widget
     print "ArduinoMEGA ready to operate"