def __init__(self): self.ardu1 = Arduino('COM9') self.ardu2 = Arduino('COM3') self.pinlist = np.array([3, 5, 6, 9, 10, 11]) self.servoset = np.array([[600, 2300], [500, 2380]]) self.logdata = [] self.usedservo = np.zeros((2, 6), dtype=np.uint8) self.delaysec = 0.75 self.ispacked = False time.sleep(2)
def feed(): if content[7] == 'Off': board = Arduino("COM4") illum = 5 illumOn(illum) if content[7] == 'Low': board = Arduino("COM4") illum = 9 illumOn(illum) if content[7] == 'Medium': board = Arduino("COM4") illum = 10 illumOn(illum) if content[7] == 'High': board = Arduino("COM4") illum = 11 illumOn(illum) if content[7] == 'Manual Control': board = Arduino("COM4") illum = 3 illumOn(illum) cap = cv2.VideoCapture(1) #cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) #cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080) #cap.set(cv2.CAP_PROP_FPS, 5) if (cap.isOpened() == False): print("Error opening video stream or file") while (cap.isOpened()): ret, frame = cap.read() if ret == True: cv2.imshow( 'Live Video Feed (Press "q" to return to Recording Parameters)', frame) if cv2.waitKey(25) & 0xFF == ord('q'): break else: break cap.release() cv2.destroyAllWindows()
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()
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))
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
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')
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')
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()
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
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
def _initialize_arduino(com): try: board = Arduino(com, baudrate=_BAUD_RATE) # opens communication to Arduino except: sys.exit("Error. Could not open COM port") return board
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
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()
class Semaforo: board = Arduino("/dev/ttyACM0") LED_RED = board.digital[13] LED_YELLOW = board.digital[12] LED_GREEN = board.digital[11] ####################### def led_red_on(self): self.LED_RED.write(1) def led_red_off(self): self.LED_RED.write(0) ####################### def led_yellow_on(self): self.LED_YELLOW.write(1) def led_yellow_off(self): self.LED_YELLOW.write(0) ####################### def led_green_on(self): self.LED_GREEN.write(1) def led_green_off(self): self.LED_GREEN.write(0)
def __init__(self): # Initialize environment if DOMAIN == "discrete": self.action_space = Tuple([Discrete(N_ACTIONS) for n in range(N_MOTORS)]) self.observation_space = Tuple([Discrete(N_STATES) for n in range(N_MOTORS)]) elif DOMAIN == "continuous": self.action_space = Discrete(N_ACTIONS**N_MOTORS) self.observation_space = Box(low=0, high=N_STATES, shape=(N_MOTORS, ), dtype=int) else: raise Exception self.step_no = 0 # Initialize Arduino self.board = Arduino("/dev/ttyACM0") print("Connected to Arduino!") self.motor = [self.board.get_pin('d:{}:p'.format(pin)) for pin in PINS] self.state = np.zeros(N_MOTORS).astype(int) + N_STATES // 2 self.move() # Start camera stream self.camera = cv2.VideoCapture(1) self.new_position = None self.old_position = None t = threading.Thread(target=self.stream) t.daemon = True t.start() print("Beginning camera stream...") self.reset()
def __init__(self,port): print(port) self.board=Arduino(port) self.it=util.Iterator(self.board) self.it.start() time.sleep(2) print("ok")
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)
def LED_GAR(data): board = Arduino('/dev/ttyACM0') led_gar = board.get_pin('d:2:o') if data == 'off_garage': led_gar.write(0) elif data == 'on_garage': led_gar.write(1)
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
def connect(self): """Attempts to connect to the device""" self.connected = False for port in range(1, 256 + 1): port = 'COM{}'.format(port) try: temp1 = serial.Serial(port) temp1.flush() temp1.close() self.board = Arduino(port) except serial.serialutil.SerialException: try: self.board.exit() except AttributeError: try: temp2 = serial.Serial(port) except serial.serialutil.SerialException: pass else: temp2.flush() temp2.close() else: self.main_output = self.board.get_pin(self.main_pin) self.test_output = self.board.get_pin(self.test_pin) print('Arduino Port Found at: {}'.format(port)) self.connected = True break
def clima(data): board = Arduino('/dev/ttyACM0') vent = board.get_pin('d:4:o') if data == 'on_vent' or '1': vent.write(1) elif data == 'off_vent' or data == '0': vent.write(0)
def main(): args = get_arguments() log('Initializing....') board = Arduino(args.arduino_device) log('Arduino connected to: {}'.format(args.arduino_device)) initialize_arduino_reading(board, args.analog_ports) client = None if args.influxdb_host: client = InfluxDBClient(args.influxdb_host, 8086, 'root', 'root', args.database) client.create_database(args.database) points = [] for port in args.analog_ports: port_read = board.analog[port].read() log('Port {}: {}'.format(port, port_read)) if client: time = datetime.datetime.utcnow().strftime(TIME_FORMAT) port_name = 'A{}'.format(port) point = dict(measurement='humidity_sensor', time=time, fields={'value': port_read}, tags={'sensor_port': port_name}) log(point) points.append(point) if client and points: client.write_points(points) board.exit() log('Connection with board has been closed') log('Finish')
def __init__(self): self.board = Arduino("COM3") self.Motor_Sequence = [Rubic_MCU.Motor_Sequence() for i in range(6)] self.Motor_Port_dict = dict([(Rubic_MCU.Motor_Port.motor_L, 0), (Rubic_MCU.Motor_Port.motor_R, 1), (Rubic_MCU.Motor_Port.motor_U, 2), (Rubic_MCU.Motor_Port.motor_D, 3), (Rubic_MCU.Motor_Port.motor_F, 4), (Rubic_MCU.Motor_Port.motor_B, 5)]) data = [('F2', (Rubic_MCU.Motor_Port.motor_F, 180)), ('F', (Rubic_MCU.Motor_Port.motor_F, 90)), ('F\'', (Rubic_MCU.Motor_Port.motor_F, -90)), ('B2', (Rubic_MCU.Motor_Port.motor_B, 180)), ('B', (Rubic_MCU.Motor_Port.motor_B, 90)), ('B\'', (Rubic_MCU.Motor_Port.motor_B, -90)), ('L2', (Rubic_MCU.Motor_Port.motor_L, 180)), ('L', (Rubic_MCU.Motor_Port.motor_L, 90)), ('L\'', (Rubic_MCU.Motor_Port.motor_L, -90)), ('R2', (Rubic_MCU.Motor_Port.motor_R, 180)), ('R', (Rubic_MCU.Motor_Port.motor_R, 90)), ('R\'', (Rubic_MCU.Motor_Port.motor_R, -90)), ('U2', (Rubic_MCU.Motor_Port.motor_U, 180)), ('U', (Rubic_MCU.Motor_Port.motor_U, 90)), ('U\'', (Rubic_MCU.Motor_Port.motor_U, -90)), ('D2', (Rubic_MCU.Motor_Port.motor_D, 180)), ('D', (Rubic_MCU.Motor_Port.motor_D, 90)), ('D\'', (Rubic_MCU.Motor_Port.motor_D, -90))] self.rubic_dict = dict(data)
def connectArduino(): global duino, heater, fan, humidifier, devices a = 0 while a < 5: duino = "" comport = "/dev/ttyACM" + str(a) if path.exists(comport): duino = Arduino(comport) logger.debug(duino) if str(duino).startswith("Arduino"): logger.debug("Connected to Arduino.") a = 5 logger.debug("Connecting peripherals.") l = 0 while l < len(devices): devices[l]["device"] = duino.get_pin('d:' + devices[l]["pin"] + ':o') if devices[l]["device"] != "Uninit": devname = devices[l]["name"] logger.debug("Connected to " + devname + " successfully on " + str(devices[l]["device"])) dowrite(devname, 0) logger.debug("New status of " + devname + ": " + str(devices[l]["status"])) l = l + 1 # duino.digital[2].write(1) # duino.digital[4].write(1) # duino.digital[7].write(1) a = a + 1
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)
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!')
def __init__(self, name): self.arduino = Arduino('debug') # No anonymous superheroes on my watch! Every narcoleptic superhero gets # a name. Any name at all. SleepyMan. SlumberGirl. You get the idea. self.name = name self.uv_dose_to_administer_mins = 5 * 60 self.uv_dose_to_administer = self.uv_dose_to_administer_mins * 60 # What have we accomplished today? self.kittens_rescued = 0 self.state_timers = None self.states = [ { 'name': 'WAITING_FOR_OBJECTS', 'on_enter': ['reset_and_create_state_timers'] }, { 'name': 'SANITIZING', 'timeout': 10 * 60, 'on_timeout': 'high_temp', 'on_enter': ['start_uv_timer'], 'on_exit': ['stop_uv_timer'] }, { 'name': 'COOLING', 'timeout': 5 * 60, 'on_timeout': 'low_temp', 'on_enter': ['start_cooling_timer'], 'on_exit': ['stopping_cooling_timer'] }, { 'name': 'CYCLE_COMPLETE', 'on_enter': ['wrap_up'] }, ] self.transitions = [['lid_close', 'WAITING_FOR_OBJECTS', 'SANITIZING'], [ 'high_temp', ['SANITIZING', 'COOLING'], 'COOLING' ], ['low_temp', 'COOLING', 'SANITIZING'], [ 'dosage_cycle_complete', ['SANITIZING', 'COOLING'], 'CYCLE_COMPLETE' ]] @add_state_features(Tags, Timeout) class CustomStateMachine(Machine): pass # Initialize the state machine self.machine = CustomStateMachine(model=self, states=self.states, transitions=self.transitions, initial='WAITING_FOR_OBJECTS') self.reset_and_create_state_timers()
def main(): parser = argparse.ArgumentParser() parser.add_argument("-s", "--serial", default="ttyACM0", type=str, help="Arduino serial port [ttyACM0] (OSX is cu.usbmodemXXXX)") cli.grpc_host(parser) parser.add_argument("-x", "--xservo", default=5, type=int, help="X servo PWM pin [5]") parser.add_argument("-y", "--yservo", default=6, type=int, help="Y servo PWM pin [6]") cli.alternate(parser) cli.calib(parser) cli.log_level(parser) args = vars(parser.parse_args()) alternate = args["alternate"] calib = args["calib"] xservo = args["xservo"] yservo = args["yservo"] setup_logging(level=args[LOG_LEVEL]) # Setup firmata client port = ("" if is_windows() else "/dev/") + args["serial"] try: board = Arduino(port) logger.info("Connected to Arduino at: {0}".format(port)) except OSError as e: logger.error("Failed to connect to Arduino at {0} - [{1}]".format(port, e)) sys.exit(0) with LocationClient(args[GRPC_HOST]) as client: # Create servos servo_x = FirmataServo("Pan", alternate, board, "d:{0}:s".format(xservo), 1.0, 8) servo_y = FirmataServo("Tilt", alternate, board, "d:{0}:s".format(yservo), 1.0, 8) try: if calib: try: calib_t = Thread(target=calibrate_servo.calibrate, args=(client, servo_x, servo_y)) calib_t.start() calib_t.join() except KeyboardInterrupt: pass else: if alternate: # Set servo X to go first servo_x.ready_event.set() try: servo_x.start(True, lambda: client.get_x(), servo_y.ready_event if not calib else None) servo_y.start(False, lambda: client.get_y(), servo_x.ready_event if not calib else None) servo_x.join() servo_y.join() except KeyboardInterrupt: pass finally: servo_x.stop() servo_y.stop() finally: board.exit() logger.info("Exiting...")
def __init__(self, mode): self.mode = mode if self.mode == 'debug': print('WARNING: DEBUG MODE') else: from pyfirmata import Arduino, util self.board = Arduino('/dev/ttyACM0')
def main(): """ Main entry point of the app """ session = session_factory() reader = SimpleMFRC522() board = Arduino('/dev/ttyUSB0') mainApp = App(session, reader, board) asyncio.run(mainApp.main())