class ArdUno(): def __init__(self): self.port = 'COM21' self.board = Arduino(self.port) self.anticrash() self.readenable() self.board.digital[8].write(1) def anticrash(self): """ Iterator evita que se crashee el puerto (no permite que se sobrecargue de trafico) """ it = util.Iterator(self.board) it.start() #corremos el iterator def readenable(self): self.board.analog[0].enable_reporting() def getpin(self,numchannel): ch=str(numchannel) pin='a:' + ch + ':i' R=self.board.get_pin(pin) return(R) def chdef(self,namechannel,numchannel): ch=str(numchannel) R='A' + ch + ' = h.getpin(' + ch + ')' return(R) def voltread(self,namechannel,numchannel): ch=str(numchannel) A=namechannel+ ch +'.read()' return(str(A))
class LightsController: def __init__(self): self.board = Arduino("/dev/ttyACM0") self.lightPin = self.board.get_pin("d:3:p") def Off(self): self.lightPin.write(0) sleep(1) def On(self): self.lightPin.write(1) sleep(1) def Fade(self): for pwm in arange(0.02, 0.1, 0.004): self.lightPin.write(pwm) sleep(0.075) for pwm in arange(0.1, 0.8, 0.01): self.lightPin.write(pwm) sleep(0.075) for pwm in arange(0.8, 0.1, -0.01): self.lightPin.write(pwm) sleep(0.075) for pwm in arange(0.1, 0.02, -0.004): self.lightPin.write(pwm) sleep(0.075) def Blink(self): self.lightPin.write(1) sleep(1) self.lightPin.write(0) sleep(1)
class Hinako: def __init__(self, port, b_pin_id, w_pin_id, h_pin_id): self.board = Arduino(port) ''' d: digital output n: number PWM pin s: servo control ''' self.b_pin = self.board.get_pin(b_pin_id) self.w_pin = self.board.get_pin(w_pin_id) self.h_pin = self.board.get_pin(h_pin_id) self.b = 0 self.w = 0 self.h = 0 def _move_servo(self, pin, begin_val, end_val, ds=0.1): step = 1 if begin_val < end_val else -1 print '%d -> %d' % (begin_val, end_val) print step for i in range(begin_val, end_val, step): print i pin.write(i) time.sleep(ds) def set_bust(self, size_cm, ds=0.1): print "bust: %d cm" % size_cm val = int(round(map_value(size_cm, 70, 100, 65, 0))) self._move_servo(self.b_pin, self.w, val, ds=ds) self.w = val def set_waist(self, val): ''' dc motor self.w_pin ''' def set_hip(self, val): self._move_servo(self.h_pin, self.h, val) self.h = val
def main(): board = Arduino("/dev/ttyACM0") board.add_cmd_handler(pyfirmata.pyfirmata.STRING_DATA, on_string_received) iter = util.Iterator(board) iter.start() write_loop(board)
def __init__(self, port): try: self.board = Arduino(port) except OSError as e: raise Exception("Arduino not found on: {0}".format(port)) self._setup()
def __init__(self, config, SS): from pyfirmata import Arduino, util, SERVO self.SS = SS self.board = Arduino(config['board']) self.iterator = util.Iterator(self.board) self.iterator.daemon = True self.iterator.start() self.fwheel = self.board.get_pin('d:11:p') self.fwheel.mode = SERVO self.rwheel = self.board.get_pin('d:10:p') self.rwheel.mode = SERVO self.awheel = self.board.get_pin('d:3:p') self.awheel.mode = SERVO self.awheel.write(self.awheel_stop) self.state = 'start' self.controlobjects = [ ControlObject(9, self, [self.fire_red]), ControlObject(8, self, [self.fire_orange]), ControlObject(12, self, [self.fire_yellow]), ControlObject(13, self, [self.fire_green]) ] self.colormatch_measurement = M.Measurement.objects(method="closestcolorml")[0] self.timesince_measurement = M.Measurement.objects(method="timesince_manual")[0] self.deliveredcolor_measurement = M.Measurement.objects(method="closestcolor_manual")[0] self.region_inspection = M.Inspection.objects[0] self.SS = SS if not "debug" in config: self.cw = ControlWatcher() self.cw.control = self self.cw.daemon = True self.cw.start()
class ArduinoConnection(Thread): def __init__(self): Thread.__init__(self) self.SAMPLING_INTERVAL = 0.100 self.MEAN_INTERVAL = 5 self.MEAN_SAMPLES_NUMBER = round(self.MEAN_INTERVAL/self.SAMPLING_INTERVAL) PORT = '/dev/ttyACM0' self.board = Arduino(PORT) it = util.Iterator(self.board) it.start() self.analog_pin_value_arr = [self.board.get_pin('a:0:i'), self.board.get_pin('a:1:i'), self.board.get_pin('a:2:i'), self.board.get_pin('a:3:i'), self.board.get_pin('a:4:i'), self.board.get_pin('a:5:i')] for i in range(len(self.analog_pin_value_arr)): self.analog_pin_value_arr[i].enable_reporting() self.mean_analog_valuea_arr = [0.0] * 6 self.mean_analog_valuea_assigned_arr = [0.0] * 6 def run(self): #s= '' sample_number = 0 while True: while (sample_number < self.MEAN_SAMPLES_NUMBER): # time.sleep(DELAY) self.board.pass_time(self.SAMPLING_INTERVAL) for i in range(len(self.mean_analog_valuea_arr)): self.mean_analog_valuea_arr[i] = self.mean_analog_valuea_arr [i] + self.analog_pin_value_arr[i].read() sample_number = sample_number + 1 for i in range(len(self.mean_analog_valuea_arr)): self.mean_analog_valuea_arr[i] = self.mean_analog_valuea_arr[i] / self.MEAN_SAMPLES_NUMBER #s = s + str(self.mean_analog_valuea_arr[i]) + ' ' self.mean_analog_valuea_assigned_arr = self.mean_analog_valuea_arr #print s #s = '' sample_number = 0 self.mean_analog_valuea_arr = [0.0] * 6 def getMeanAnalogArduinoValueArray(self): return self.mean_analog_valuea_assigned_arr
def __init__(self, pk, port, *args, **kwargs): self.pk = pk self.port = port self._board = Arduino(self.port) self.pins = dict(((i, Pin(pk, i)) for i in range(14))) [setattr(self, k, v) for k, v in kwargs.items()] super(Board, self).__init__(*args, **kwargs)
def __init__(self, port, claw=False): self.uarm_status = 0 # self.pin2_status = 0 self.coord = {} self.g_interpol_val_arr = {} self.angle = {} self.claw = claw self.uarm = Arduino(port) self.assignServos() self.uarmDetach()
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()
class ArduinoConnection(ConnectionBase): def __init__(self, connection_type, port_name): super().__init__() self.connectionStatus = ConnectionStatus.Closed self.connectionType = connection_type self.portName = port_name self._iterator = None 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 close_connection(self): if self.connectionStatus == ConnectionStatus.Closed: print("Connection is already closed!") else: self.board.exit() self.board = None self._iterator = None self.connectionStatus = ConnectionStatus.Closed print(self.connectionStatus)
def main(): board = Arduino('/dev/ttyUSB0') #starting values multiplier = 400.0 cam = Camera() js = JpegStreamer() analog_4 = board.get_pin('a:1:i') analog_5 = board.get_pin('a:2:i') button_13 = board.get_pin('d:13:i') it = util.Iterator(board) it.start() while (1): #print str(analog_5.read()) + "\t\t" + str(analog_4.read()) t1 = analog_5.read() t2 = analog_4.read() b13 = button_13.read() if not t1: t1 = 50 else: t1 *= multiplier if not t2: t2 = 100 else: t2 *= multiplier print "t1 " + str(t1) + ", t2 " + str(t2) + ", b13 " + str(b13) cam.getImage().flipHorizontal().edges(int(t1), int(t2)).invert().smooth().save(js.framebuffer) time.sleep(0.01)
def main(): parser = ArgumentParser( description='Bridge connecting Arduino and hat webapp') parser.add_argument('-s', '--server', default='127.0.0.1:3000', help='Server the webapp is running on') parser.add_argument('device', help='Path to Arduino device, e.g., /dev/tty/ACM0') args = parser.parse_args() url = ddp.ServerUrl(args.server) board = None hat_controller = None try: print 'Connecting to Arduino board...' board = Arduino(args.device) print 'Connecting to DDP server...' hat_controller = HatController(url, board) hat_controller.connect() wait_for_user_to_exit() finally: if hat_controller is not None: try: hat_controller.disconnect() except: print ( 'An error occurred while disconnecting from the DDP ' 'server.' ) if board is not None: try: board.exit() except: print 'An error occurred while exiting from the Arduino board.'
class Board(SerializableModel): pk = None port = None pins = None name = None written_pins = set() json_export = ('pk', 'port', 'pins') def __init__(self, pk, port, *args, **kwargs): self.pk = pk self.port = port self._board = Arduino(self.port) self.pins = dict(((i, Pin(pk, i)) for i in range(14))) [setattr(self, k, v) for k, v in kwargs.items()] super(Board, self).__init__(*args, **kwargs) def __del__(self): try: self.disconnect() except: print(traceback.format_exc()) def disconnect(self): for pin in self.written_pins: pin.write(0) return self._board.exit() def firmata_pin(self, identifier): return self._board.get_pin(identifier) def release_pin(self, identifier): bits = identifier.split(':') a_d = bits[0] == 'a' and 'analog' or 'digital' pin_nr = int(bits[1]) self._board.taken[a_d][pin_nr] = False
def onActivated(self, ec_id): print "onActivated Begin" pinNumber = [3, 5, 6, 7, 11] self.pin = [None, None, None, None, None] try: self.board = Arduino(self._com_port[0]) for i in range(5): self.board.servo_config(pinNumber[i], angle=90) # Caution: Don't use board.get_pin('d:*:s') as it calls servo_config method with angle=0, which damages your servo. self.pin[i] = self.board.digital[pinNumber[i]] print "onActivated End" except Exception as e: print "some errors %s" % str(e) self.pin[0].write(80) return RTC.RTC_OK
def __init__(self, port, b_pin_id, w_pin_id, h_pin_id): self.board = Arduino(port) ''' d: digital output n: number PWM pin s: servo control ''' self.b_pin = self.board.get_pin(b_pin_id) self.w_pin = self.board.get_pin(w_pin_id) self.h_pin = self.board.get_pin(h_pin_id) self.b = 0 self.w = 0 self.h = 0
def init(): global board board = Arduino('/dev/ttyACM0') global lazer1 lazer1 = board.get_pin('d:2:o') global lazer2 lazer2 = board.get_pin('d:3:o') global lazer3 lazer3 = board.get_pin('d:4:o') global pump1 pump1 = board.get_pin('d:11:o') global pump2 pump2 = board.get_pin('d:12:o') global pwm_led pwm_led = board.get_pin('d:6:p')
def __init__(self): Thread.__init__(self) self.SAMPLING_INTERVAL = 0.100 self.MEAN_INTERVAL = 5 self.MEAN_SAMPLES_NUMBER = round(self.MEAN_INTERVAL/self.SAMPLING_INTERVAL) PORT = '/dev/ttyACM0' self.board = Arduino(PORT) it = util.Iterator(self.board) it.start() self.analog_pin_value_arr = [self.board.get_pin('a:0:i'), self.board.get_pin('a:1:i'), self.board.get_pin('a:2:i'), self.board.get_pin('a:3:i'), self.board.get_pin('a:4:i'), self.board.get_pin('a:5:i')] for i in range(len(self.analog_pin_value_arr)): self.analog_pin_value_arr[i].enable_reporting() self.mean_analog_valuea_arr = [0.0] * 6 self.mean_analog_valuea_assigned_arr = [0.0] * 6
def __init__(self, port, log_handler): ## Initalize logging logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger('Arduino_Interface') self.logger.addHandler(log_handler) # Add Tk log handler self.logger.debug('__init__') ## Board Initalization self.board = Arduino(port) self.board.add_cmd_handler(pyfirmata.START_SYSEX, self.handleIncomingSysEx) self.board.add_cmd_handler(pyfirmata.STRING_DATA, self.handleIncomingString) ## Data Buffer Initalization self.incoming_data = [] ## Callback holder self.callback_holder = dict()
def __init__(self, session): monkey.patch_socket() import gevent_zeromq gevent_zeromq.monkey_patch() #we do use greenlets, but only patch sock stuff #other stuff messes up the config = session.arduino boardglob = config['board'] boards = glob(boardglob) if not len(boards): raise Exception("No Arduino found") self.board = Arduino(boards[0]) #self.iterator = util.Iterator(self.board) #self.iterator.daemon = True #self.iterator.start() #initialize servo objects self.servos = {} if "servos" in config: for servo in config["servos"]: self.servos[servo['name']] = Servo(servo['pin'], self.board) #initialize light objects self.digitalouts = {} if "digitalouts" in config: for do in config["digitalouts"]: self.digitalouts[do['name']] = DigitalOut(do['pin'], self.board) if "digitalouts" in config or "servos" in config: self.subsock = ChannelManager().subscribe("ControlOutput/") self.buttons = [] if "buttons" in config: for button in config["buttons"]: self.buttons.append(Button(button['pin'], button['message'], self.board)) self.potentiometers = [] if "potentiometers" in config: for pot in config["potentiometers"]: self.buttons.append(Potentiometer(pot['pin'], pot['name'], self.board))
def __init__(self, api_key, feed, serial_port, delay=5): """Setup hardware and remote feeds. @param api_key This is the key from Cosm.com @param feed This is the feed ID from Cosm.com @param serial_port Where to read data from @param delay Number of seconds to wait between read/sends. """ self.api_key = api_key self.feed = feed self.serial_port = serial_port self.delay = delay self.arduino = Arduino(self.serial_port) self.iterator = util.Iterator(self.arduino) self.iterator.start() self.cosm = CosmSender(self.api_key, self.feed, {}, cacheSize=0) self.streams = {}
class ArduinoWrapper: __arduino = None def __init__(self, com=None): self.connect(com) def connect(self, com=None): if com != None: self.__arduino = Arduino(com) else: self.__arduino = Arduino(DEFAULT_COMPORT) def update_pin(self, num, status): if status: print "update pin: %s -> ON" %str(num) return self.__arduino.digital[num].write(1) else: print "update pin: %s -> OFF" %str(num) return self.__arduino.digital[num].write(0) def get_pin(self, status): return self.__arduino.get_pin(status)
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
from pyfirmata import Arduino, util import time Uno = Arduino("COM6") print('Olá Mundo!') while True: Uno.digital[13].write(1) print('Led ligado') time.sleep(1) Uno.digital[13].write(0) print('Led desligado') time.sleep(1)
from pyfirmata import Arduino, util import time board =Arduino('/dev/cu.usbmodem14101') acquisition = util.Iterator(board) acquisition.start() servo_pin = board.get_pin('d:9:s') ser = board.get_pin('a:0:i') def servo(angle): while True: if angle < 10: angle = 10 elif angle > 170: angle = 170 servo_pin.write(angle) def getTFminiData(): while True: count = ser.in_waiting if count > 8: recv = ser.reset_input_buffer() if recv[0] == 'Y' and recv[1] == 'Y': # 0x59 is 'Y' low = int(recv[2].encode('hex'), 16) high = int(recv[3].encode('hex'), 16) distance = low + high * 256 print(distance) try : getTFminiData()
import fileinput import random import math import pygame import traceback import imp import os import glob import sys import helpers import csv from pyfirmata import Arduino, util board = Arduino('/dev/tty.usbmodem144301') it = util.Iterator(board) it.start() board.analog[0].enable_reporting() board.analog[1].enable_reporting() board.analog[2].enable_reporting() board.analog[3].enable_reporting() board.analog[4].enable_reporting() analog_0 = board.get_pin('a:0:i') analog_1 = board.get_pin('a:1:i') analog_2 = board.get_pin('a:2:i') analog_3 = board.get_pin('a:3:i') analog_4 = board.get_pin('a:4:i')
#https://github.com/firmata/firmata_test from pyfirmata import Arduino, util import time board = Arduino('/dev/ttyACM1') print('Firmata version:', board.get_firmata_version()) while True: board.digital[13].write(1) time.sleep(0.5) board.digital[13].write(0) time.sleep(0.5)
from pyfirmata import Arduino, util from time import sleep def control_led(board,pin,value): board.digital[pin].write(value) PORT = '/tmp/ttyS1' # importamos los elementos necesarios board = Arduino(PORT) it = util.Iterator(board) # le pasamos la tarjeta al iterador it.start() # arrancamos a el iterador para poder leer entradas # configuro el pin como ENTRADA PIR_INPUT = 2 SWICTH_INPUT = 3 board.get_pin(f'd:{str(PIR_INPUT)}:i') board.get_pin(f'd:{str(SWICTH_INPUT)}:i') # declaro mi lista de la posicion de los leds FOCO = 8 status_foco = False count = 0 # contador del temporizador while True: pir = board.digital[PIR_INPUT].read() switch = board.digital[SWICTH_INPUT].read()
#!/usr/bin/env python from pyfirmata import Arduino, util import time #remember to change the ACM to the correct number board = Arduino('/dev/ttyACM0') it = util.Iterator(board) it.start() while True: board.digital[13].write(1) time.sleep(1) board.digital[13].write(0) time.sleep(1)
return cfg[0], cfg[1], cfg[2] else: return None, None, None def all_mute_angles(): res = dict() with open('servo_config.json', 'r') as f: pins_config = json.load(f) for cfg in pins_config.values(): res[cfg[0]] = cfg[1] return res ### ARDUINO board = Arduino('COM7') pins = [board.get_pin('d:{0}:s'.format(i)) for i in range(2, 10)] def move_servo(pin, angle): print 'Writing {0} to pin {1}'.format(angle, pin) pins[pin - 2].write(angle) mute_angles = all_mute_angles() for pin in mute_angles: board.servo_config(pin, mute_angles[pin]) move_servo(pin, mute_angles[pin]) ### MIDI midi.init() inp = midi.Input(1)
from pyfirmata import Arduino, util import time carte = Arduino('/dev/ttyACM0') acquisition = util.Iterator(carte) acquisition.start() tension_A0 = carte.get_pin('a:0:i') time.sleep(1.0) R1 = 3000 R2 = 1000 Umes = tension_A0.read() * 5 + (R1 + R2) / R2 print(Umes, "V") carte.exit()
# In[1]: #Author: Daniel Kulik # Setup Python import random, os, glob, time, sys, statistics from pyfirmata import Arduino, util import pygame pygame.init() pygame.mixer.init() ################################################################################# #Setup Arduino Connection,Variables and Test Condition try: board = Arduino('COM3')#baudrate=57600 it = util.Iterator(board) it.start() pygame.time.delay(100) #board.analog[0].enable_reporting() analog_0 = board.get_pin('a:1:i') analog_1 = board.get_pin('a:2:i') analog_2 = board.get_pin('a:3:i') analog_3 = board.get_pin('a:4:i') LED_Lose = board.get_pin('d:10:o') LED_Win = board.get_pin('d:11:o') pygame.time.delay(200) V0_start = float(analog_0.read()) V1_start = float(analog_1.read())
from pyfirmata import Arduino, util import time board = Arduino('/dev/cu.wch') print "yo" #pin9 = board.get_pin('d:10:s') pin10 = board.get_pin('d:10:s') board.digital[13].write(1) while 1: pin10.write(90) time.sleep(1) pin10.write(70) time.sleep(1) print "yeah"
class ArduinoLaserControl: color2index = {'r': 0, 'g': 1, 'b': 2} ind2color = ['r', 'g', 'b'] def __init__(self, port='/dev/cu.usbmodem14301', pins=None): """ :param port: the port of your Arduino. You may find the port at your Arduino program -> Tool tab -> port (Mac) Device manager -> Ports (COM & LPT) (Windows) :param pins: an array of Arduino d pins with PWM """ self.board = Arduino(port) self.pinNums = [6, 10, 11] if pins is None else pins self.pins = {} self.default_pin = self.board.get_pin(f'd:3:p') for c in self.color2index: self.pins[c] = self.board.get_pin( f'd:{self.pinNums[self.color2index[c]]}:p') def setPins(self, pins): """ set output pins of arduinos, for control :param pins: an array of RGB pin numbers - PWM capable - at your Arduino Uno (e.g. [9, 10, 11]) """ self.pinNums = pins for c in self.color2index: self.pins[c] = self.board.get_pin( f'd:{self.pinNums[self.color2index[c]]}:p') def setValue(self, colors, values): """ :param colors: an array or chars ('r' or 'g' or 'b'), single char (e.g. 'r') is acceptable :param values: an array of normalized values (corresponds to the percent in the control box) for each color. e.g. [0.4 0.1 1] if you want identical values for all colors just put a scalar """ # check whether parameter is scalar or array if isinstance(colors, list) is False: if len(colors) > 1: colors = colors[0] colors = [colors] numColors = len(colors) if not isinstance(values, list): values = [values] * numColors if len(values) != len(colors): print( " - LASER CONTROL : Please put the same number of values to 'colors' and 'values' " ) return # turn on each color for i in range(numColors): # Detect color if colors[i] in self.color2index: pin = self.pins[colors[i]] else: # colors must be 'r' or(and) 'g' or(and) 'b' print( " - LASER CONTROL: Wrong colors for 'setValue' method, it must be 'r' or(and) 'g' or(and) 'b'" ) return print(f' - V[{colors[i]}] from Arduino : {values[i]:.3f}V\n') pin.write(values[i]) def switch_control_box(self, channel): """ switch color of laser through control box with D-Sub 9pin, but note that it uses only 4-bit encoding. R: 1100 G: 1010 B: 1001 :param channel: integer, channel to switch (Red:0, Green:1, Blue:2) """ self.default_pin.write(1.0) time.sleep(10.0) if channel in [0, 1, 2]: self.pins[self.ind2color[channel]].write(1.0) for c in [0, 1, 2]: if c != channel: self.pins[self.ind2color[c]].write(0.0) else: print('turning off') for c in [0, 1, 2]: self.pins[self.ind2color[c]].write(0.0) time.sleep(10.0) self.default_pin.write(1.0) def turnOffAll(self): """ Feed 0000 to control box :return: """ for c in self.color2index: pin = self.pins[c] pin.write(0) self.switch_control_box(3) print(' - Turned off') def disconnect(self): self.turnOffAll()
""" Global parameter declarations. """ # UI parameters VERBOSITY = 1 # max. verbosity level of messages # to be shown to user (see vprint()) # System parameters MOVE_ENABLED = False # enable turret movement FIRE_ENABLED = True # enable turret firing GUI_ENABLED = True # enable graphical user interface # Arduino ARDUINO_PORT = '/dev/ttyACM0' # port arduino is connected to BOARD = Arduino(ARDUINO_PORT) # object representing arduino # Azimuth servo control THETA_PIN = BOARD.get_pin('d:11:p') # azimuth PWM control pin THETA_MIN = 0.0 # min. azimuth angle (deg) TODO use THETA_MAX = 105.0 # max. azimuth angle (deg) TODO use THETA_PWM_MIN = 0.40 # min. azimuth PWM duty cycle THETA_PWM_MAX = 0.99 # max. azimuth PWM duty cycle THETA_HOME = 0.5 # default azimuth PWM duty cycle # Elevation servo control PHI_PIN = BOARD.get_pin('d:10:p') # elevation PWM control pin PHI_MIN = 0.0 # min. elevation angle (deg) TODO use PHI_MAX = 105.0 # max. elevation angle (deg) TODO use PHI_PWM_MIN = 0.40 # min. elevation PWM duty cycle PHI_PWM_MAX = 0.99 # max. elevation PWM duty cycle
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf import numpy as np import PIL.Image as Image import time import cv2 from pyfirmata import Arduino board = Arduino('/dev/ttyACM0') little = board.get_pin('d:3:s') ring = board.get_pin('d:5:s') middle = board.get_pin('d:6:s') thumb = board.get_pin('d:9:s') index = board.get_pin('d:10:s') def rock(): thumb.write(170) index.write(170) middle.write(170) ring.write(170) little.write(170) def paper(): thumb.write(10) index.write(10)
def RCtime(RCpin): reading = 0 GPIO.setup(RCpin, GPIO.OUT) GPIO.output(RCpin, GPIO.LOW) time.sleep(0.1) GPIO.setup(RCpin, GPIO.IN) # This takes about 1 millisecond per loop cycle while (GPIO.input(RCpin) == GPIO.LOW): reading += 1 return reading #board=Arduino("/dev/ttyACM0") #board=Arduino("/dev/ttyUSB0") board = Arduino("/dev/ttyAMA0") board.digital[9].mode = SERVO # humidity board.digital[8].mode = SERVO # temp board.digital[11].mode = SERVO # light count = 0 lastlightvalue = 0 light = 0 servolightposition = arduino_map((math.sqrt(1024 - light)), 0, 32, 10, 170) while True: humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 4) if humidity is not None and temperature is not None: light = RCtime(22) # light sensor tunning, must be setup always if light > 1024: light = 1024 if light < 0:
#!/usr/bin/env python3 import time import paho.mqtt.client as mqtt import signal from pyfirmata import Arduino, util board = Arduino('/dev/ttyACM0') it = util.Iterator(board) it.start() servo = board.get_pin('d:10:p') servo.write(0) time.sleep(1) servo.write(90) ##client = mqtt.Client()
from pyfirmata import Arduino, util from time import sleep import pymysql def arduino_map(x, in_min, in_max, out_min, out_max): return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min PORT = "COM4" uno = Arduino(PORT) sleep(5) it = util.Iterator(uno) it.start() a4 = uno.get_pin('a:4:i') a5 = uno.get_pin('a:5:i') db = pymysql.connect("120.110.114.14", "hanshin", "Hanshin519", "Student", port=3306) cursor = db.cursor() print("Arduino start~") try: while True: gas = a4.read()
# verificar se o numero digitado é positivo ou negativo from pyfirmata import Arduino import lcd import time board = Arduino('COM6') lcd.escrever(board, 0, 0, '2 DIA PYTHON') time.sleep(10.0) variavel1 = input(lcd.escrever(board, 0, 0, 'DIGITE UM NUMERO')) if variavel1 >= str(0): lcd.escrever(board, 0, 1, f'NUM POSITIVO ') lcd.escrever(board, 13, 1, f'{variavel1}') else: lcd.escrever(board, 0, 1, f'NUM NEGATIVO ') lcd.escrever(board, 13, 1, f'{variavel1}') time.sleep(100.0) lcd.limpar(board) board.exit()
from pyfirmata import Arduino, util import ImageGrab import Image import time board = Arduino("COM3") blue = board.get_pin("d:9:p") green = board.get_pin("d:10:p") red = board.get_pin("d:11:p") while True: im = ImageGrab.grab() im.resize((5, 5), Image.NEAREST) pix = im.load() (r, g, b) = pix[2, 2] red.write(r / 255.0) green.write(g / 255.0) blue.write(b / 255.0) time.sleep(1)
pygame.mixer.stop() restartGame = True if __name__ == "__main__": mega = { "digital": tuple(x for x in range(54)), "analog": tuple(x for x in range(16)), "pwm": tuple(x for x in range(2, 14)), "use_ports": True, "disabled": (0, 1, 14, 15), # Rx, Tx, Crystal } try: arduino = Arduino("/dev/ttyACM0", mega, 57600) except: arduino = Arduino("/dev/ttyACM1", mega, 57600) #### CONSTANTS BUTTON_PRESSED = False ##### LIGHT CONSTANTS ##### LIGHT_GREEN = arduino.get_pin( "d:3:o" ) # If pin "Invalid pin definition" it could be due to standard Firmata not recognizing ArduinoMEGA pins. LIGHT_BLUE = arduino.get_pin("d:24:o") LIGHT_YELLOW = arduino.get_pin("d:11:o") LIGHT_1 = arduino.get_pin("d:23:o") LIGHT_2 = arduino.get_pin("d:22:o") LIGHT_3 = arduino.get_pin("d:2:o")
from pyfirmata import Arduino, util import pymysql import time import threading board = Arduino('/dev/ttyACM1') board2 = Arduino('/dev/ttyACM2') conn = pymysql.connect(host="localhost", user="******", port=3306, passwd="1234", db="mysql") try: it = util.Iterator(board) it.start() time_ctl_p = 1 time_ctl_l = 1 led_avg = 0 pump_avg = 0 flag_1f = 1 flag_2f = 1 DELAY = 0.002 stepPerResolution = 650 with conn.cursor() as cur : sql_ctl = "select water_ctl,fan_ctl,light_ctl,slide,heat_ctl from smartfarm_ctl_values_1f" sql_ctl_2 = "select water_ctl,fan_ctl,light_ctl,slide,heat_ctl from smartfarm_ctl_values_2f" sql_ans = "select * from smartfarm_automaticsys" sql_data = "select tem_data,hum_data,light_data,sm_data from smartfarm_data_values_1f" sql_avg = "select avg(minled),avg(maxled), avg(minpump), avg(maxpump) from smartfarm_data_standard" cur.execute(sql_avg) avg = cur.fetchone() while True: cur.execute(sql_data)
import variables import time from pyfirmata import Arduino board = Arduino(variables.PUERTO) def f_blik(encender): valor = board.digital[13].read() if valor == True: board.digital[13].write(0) else: board.digital[13].write(1)
# /usr/bin/env python import time import numpy as np from pyfirmata import Arduino """ Constant declarations. """ ARDUINO_PORT = '/dev/ttyACM0' print('Connecting to arduino at ' + str(ARDUINO_PORT) + '...') BOARD = Arduino(ARDUINO_PORT) print('Connected OK!') THETA_PIN = BOARD.get_pin('d:11:p') THETA_MIN = 0.0 THETA_MAX = 105.0 THETA_PWM_MIN = 0.40 THETA_PWM_MAX = 0.99 PHI_PIN = BOARD.get_pin('d:10:p') PHI_MIN = 0.0 PHI_MAX = 105.0 PHI_PWM_MIN = 0.40 PHI_PWM_MAX = 0.99 GUN0_PIN = BOARD.get_pin('d:13:o') GUN1_PIN = BOARD.get_pin('d:12:o')
from pyfirmata import Arduino, util from time import sleep from math import ceil PORT = '/tmp/ttyS1' board = Arduino(PORT) util.Iterator(board).start() # Config pot POT = 0 # configuro la entrada del potenciometro pot = board.get_pin(f'a:{str(POT)}:i') # config Servo SERVO = 3 servo = board.get_pin(f'd:{str(SERVO)}:s') sleep(1) # time to wait while True: value = pot.read() if value == None: continue ang = value * 180 ang = ceil(ang) # redondeo para no generar falla servo.write(ang) print(f'angulo {ang}')
#!/usr/bin/python from pyfirmata import Arduino, util PIN = 12 # Pin 12 is used DELAY = 2 # A 2 seconds delay PORT = '/dev/ttyACM0' board = Arduino(PORT) while True: board.digital[PIN].write(1) # Set the LED pin to 1 (HIGH) board.pass_time(DELAY) board.digital[PIN].write(0) # Set the LED pin to 0 (LOW) board.pass_time(DELAY)
from pyfirmata import Arduino, util import time board = Arduino('COM3') servo = board.get_pin('d:9:s') while 1: servo.write(180) time.sleep(2) servo.write(0) time.sleep(2)
from pyfirmata import Arduino, util import mysql.connector import time board = Arduino('/dev/ttyUSB0') green_led = 8 blue_led = 7 db = mysql.connector.connect( host="localhost", user="******", passwd="", database="storedb" ) cursor = db.cursor() while True: time.sleep(1) cursor.execute("SELECT * FROM items WHERE avail<'5'") if cursor.fetchone() is not None: board.digital[blue_led].write(1) else: board.digital[green_led].write(1) cursor.reset() cursor.close()
from pyfirmata import Arduino from time import sleep PORT = '/tmp/ttyS1' #en window es COMx board = Arduino(PORT) print('Conexion creada') # Luces RED = 2 YELLOW = 3 GREEN = 4 while True: print('Enciendo Rojo') board.digital[RED].write(1) sleep(4) board.digital[RED].write(0) print('Apago Rojo') print('Enciendo Verder') board.digital[GREEN].write(1) sleep(2) board.digital[GREEN].write(0) sleep(0.4) board.digital[GREEN].write(1) sleep(0.4) board.digital[GREEN].write(0) sleep(0.4) board.digital[GREEN].write(1) sleep(0.4)
You will also need pyfirmata (https://github.com/tino/pyFirmata) installed: pip install pyfirmata Once they are installed you also have to verify the USB location of the Arduino. On linux it is typically: /dev/ttyUSBO or /dev/ttyACM0 but the Arduino IDE should tell you where you should mount the Arduino from. """ print __doc__ import time from simplecv.api import Camera from pyfirmata import Arduino, util board = Arduino('/dev/ttyUSB0') # The location of the Arduino analog_pin_1 = board.get_pin('a:1:i') # Use pin 1 as input analog_pin_2 = board.get_pin('a:2:i') # Use pin 2 as input button_13 = board.get_pin('d:13:i') # Use pin 13 for button input it = util.Iterator(board) # Initalize the pin monitor for the Arduino it.start() # Start the pin monitor loop multiplier = 400.0 # A value to adjust the edge threshold by cam = Camera() # Initalize the camera while True: t1 = analog_pin_1.read() # Read the value from pin 1 t2 = analog_pin_2.read() # Read the value from pin 2 b13 = button_13.read() # Read if the button has been pressed.
pip.main(['install','pyfirmata']) from pyfirmata import Arduino, util try: import Tkinter as tk except ImportError: import tkinter as tk try: import ttk py3 = False except ImportError: import tkinter.ttk as ttk py3 = True board = Arduino('COM3') #Confirm port on Rasp. Pi ## Inputs ## pressure_sensor = board.get_pin('a:0:i') flow_sensor = board.get_pin('d:2:i') estop_pin = board.get_pin('d:3:i') done_pin = board.get_pin('d:4:i') spare_input_pin = board.get_pin('d:5:i') ## Outputs ## beer_selection_0 = board.get_pin('d:7:o') beer_selection_1 = board.get_pin('d:8:o') beer_selection_2 = board.get_pin('d:9:o') start_pin = board.get_pin('d:10:o') spare_output_pin = board.get_pin('d:11:o') LED = board.get_pin('d:13:o')
from pyfirmata import Arduino, util port = Arduino("COM4")
import firebase_admin from firebase_admin import credentials from firebase_admin import db from pyfirmata import Arduino, util from tkinter import * from PIL import Image from PIL import ImageTk import time import pandas as pd import datetime cont,cont2=0,0 placa = Arduino ('COM4') it = util.Iterator(placa) it.start() led1 = placa.get_pin('d:3:p') led2 = placa.get_pin('d:5:p') led3 = placa.get_pin('d:6:p') led4 = placa.get_pin('d:9:p') led5 = placa.get_pin('d:10:p') led6 = placa.get_pin('d:11:p') A0 = placa.get_pin('a:0:i') A1 = placa.get_pin('a:1:i') A2 = placa.get_pin('a:2:i') A3 = placa.get_pin('a:3:i') time.sleep(0.5)
import time from pyfirmata import Arduino, util board = Arduino('/dev/tty.usbmodem411') led = board.get_pin('d:13:o') while True: led.write(1) time.sleep(.1) led.write(0) time.sleep(.1) led.write(1) time.sleep(1) led.write(0) time.sleep(1)
devconfig.readfp(open('config.txt')) pscom = devconfig.get('Parameters', 'pscom') arduinocom = devconfig.get('Parameters', 'arduinocom') ports = devconfig.getint('Parameters', 'ports') tubevol = devconfig.getfloat('Parameters', 'tubevol') length1 = devconfig.getfloat('Parameters', 'length1') length2 = devconfig.getfloat('Parameters', 'length2') length3 = devconfig.getfloat('Parameters', 'length3') piv = devconfig.getint('Parameters', 'piv') len1 = int(tubevol*length1) len2 = int(tubevol*length2) len3 = int(tubevol*length3) ps = serial.Serial(port=pscom, baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) # VICI port selector board = Arduino(arduinocom) # Arduino Uno n2 = board.get_pin('d:2:o') # Solenoid valve normally closed, connected to digital pin 2 vent = board.get_pin('d:3:o') # Solenoid valve normally open, connected to digital pin 3 reagent = board.get_pin('d:4:o') # Solenoid valve normally closed, connected to digital pin 4 waste = board.get_pin('d:5:o') # Solenoid valve normally closed, connected to digital pin 5 prime = board.get_pin('d:6:o') # Solenoid valve normally closed, connected to digital pin 6 pump = board.get_pin('d:7:o') # Solenoid micro pump with an internal volume of 20 microliter and rated for a maximum pumping rate of 2.4 ml/min or 40 microliter/sec, connected to digital pin 7 print(" ") print("--------------------------------------------------------------------------------------------------") print(" PepSy ") print("--------------------------------------------------------------------------------------------------") print(" ") print(datetime.datetime.now().strftime('%m-%d-%Y %I:%M:%S %p')) print(" ")
class Arduino_Interface(object): ## ## ## CONSTANTS ## ## ## ## ## PING = 0x01 TEST_DATA = 0x02 ## ## ## Initalization ## ## ## ## ## def __init__(self, port, log_handler): ## Initalize logging logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger('Arduino_Interface') self.logger.addHandler(log_handler) # Add Tk log handler self.logger.debug('__init__') ## Board Initalization self.board = Arduino(port) self.board.add_cmd_handler(pyfirmata.START_SYSEX, self.handleIncomingSysEx) self.board.add_cmd_handler(pyfirmata.STRING_DATA, self.handleIncomingString) ## Data Buffer Initalization self.incoming_data = [] ## Callback holder self.callback_holder = dict() ## ## ## Runtime Functions ## ## ## ## ## def begin_scanning(self): self.board.iterate() ## ## ## Senders ## ## ## ## ## def ping(self, pingCallback): self.logger.debug('----Sending Ping----') ## Attach callback self.callback_holder[Arduino_Interface.PING] = pingCallback byte_array = bytearray() byte_array.append(Arduino_Interface.PING) self.sendSysEx(byte_array) def requestTestData(self, testDataCallback): self.logger.debug('----Requesting Test Data----') ## Attach callback self.callback_holder[Arduino_Interface.TEST_DATA] = testDataCallback byte_array = bytearray() byte_array.append(Arduino_Interface.TEST_DATA) self.sendSysEx(byte_array) def sendSysEx(self, byteArray): self.logger.debug('----sendSysEx----') self.logger.debug('SEND Data: {}'.format(binascii.hexlify(byteArray))) self.board.send_sysex(pyfirmata.START_SYSEX, byteArray) self.begin_scanning() def sendString(self, stringToSend): pass #self.board.send_sysex # for byte in dataArray: # self.incoming_data.append(chr(byte)) # print self.incoming_data ## ## ## Handlers ## ## ## ## ## def handleIncomingString(self, *string): self.logger.debug('handling Incoming String') ## Flush incoming_data self.incoming_data = [] for byte in string: self.incoming_data.append(chr(byte)) recieved_string = ''.join(self.incoming_data) print recieved_string def handleIncomingSysEx(self, *byteArray): self.logger.debug('----Incoming SysEx----') ## Flush incoming_data array self.incoming_data = [] self.incoming_data = self.filterSysEx(byteArray) ## Get header header = byteArray[0] self.logger.debug('header: {}'.format(header)) if (header == Arduino_Interface.PING): self.logger.debug('PING Response recieved') ## Ping response recieved. Return True self.callback_holder[Arduino_Interface.PING](True) elif (header == Arduino_Interface.TEST_DATA): self.logger.debug('Test Data recieved') self.callback_holder[Arduino_Interface.TEST_DATA](self.incoming_data) ## ## ## Utilities ## ## ## ## ## def filterSysEx(self, byteArray): self.logger.debug('filterSysEx') incoming_data = [] for idx, byte in enumerate(byteArray): if idx == 0: continue incoming_data.append(byte) self.logger.debug('SysEx Data:') self.logger.debug(incoming_data) return incoming_data
# -*- coding: utf-8 -*- """ @file: ForceSense.py @author: Pierre Schegg & Yann Briançon @date: 2017 Oct 10 @version: 1.0.0 Test of a force sense. """ import signal import sys import time from pyfirmata import Arduino, util board = Arduino('/dev/ttyACM0') # analog_0 = board.get_pin('a:0:i') it = util.Iterator(board) it.start() # Start reporting for defined pins board.analog[0].enable_reporting() finger = board.get_pin('d:3:s') def signal_handler(signal, frame): board.exit() sys.exit(0) signal.signal(signal.SIGINT, signal_handler)
#!/usr/bin/python # This code is supporting material for the book # Python Programming for Arduino # by Pratik Desai # published by PACKT Publishing from pyfirmata import Arduino, PWM from time import sleep import random # Setting up the Arduino board port = '/dev/cu.usbmodemfa1311' board = Arduino(port) # Need to give some time to pyFirmata and Arduino to synchronize sleep(5) # Setup mode of pin 2 as PWM pin = 11 board.digital[pin].mode = PWM for i in range(0, 99): # This python method generate random value between given range r = random.randint(1, 100) board.digital[pin].write(r / 100.00) # divide by 100.00 here as the answer will be float, integer otherwise sleep(0.1) board.digital[pin].write(0) board.exit()
class ArduinoDevice(object): """Connects to external arduino hardware""" def __init__(self): self.main_pin = 'd:{}:o'.format(ARDPIN) # digital, pin 6, output self.test_pin = 'd:13:o' # ask arduino for connection status. Added benefit of seeing LED 13 as visual aid self.ping_state = 0 self.ping_interval = 1 self.ping_timer = StopWatch() self.ping_timer.start() self.manual_mode = False self.connected = False 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 toggle_manual(self): """Turns manual mode on or off""" self.manual_mode = not self.manual_mode def __send_signal__(self): """Sends a pulse""" self.write(1) time.sleep(STIM_ON) self.write(0) def send_signal(self): """Sends a pulse using a worker thread""" thread = thr.Thread(target=self.__send_signal__, daemon=True, name=SEND_SIGNAL) thread.start() def write(self, num): """Writes to arduino while handling any serial errors""" try: self.main_output.write(num) except (serial.serialutil.SerialTimeoutException, serial.serialutil.SerialException, AttributeError): self.connected = False def exit(self): """Close device cleanly""" try: self.board.exit() except (serial.serialutil.SerialException, serial.serialutil.SerialTimeoutException, AttributeError): pass def ping(self): """test if arduino is still connected""" if self.ping_timer.elapsed() > self.ping_interval: try: self.ping_state ^= 1 self.test_output.write(self.ping_state) except (serial.serialutil.SerialTimeoutException, serial.serialutil.SerialException, AttributeError): self.connected = False finally: self.ping_timer.reset() self.ping_timer.start()