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, lc, addr, debug=True): self.lc = lc self.board = None self.lights = [] # # pin 53 used as placeholder because we don't support buzzers yet # (r, y, g, b ) self.lights.append((22, 23, 24, 53)) self.lights.append((25, 26, 27, 53)) self.lights.append((28, 29, 30, 53)) self.lights.append((31, 32, 33, 53)) self.lights.append((34, 35, 36, 53)) self.lights.append((37, 38, 39, 53)) self.lights.append((40, 41, 42, 53)) self.lights.append((43, 44, 45, 53)) if addr is not None: self.board = ArduinoMega(addr) for r, y, g, b in self.lights: self.board.digital[r].write(1) self.board.digital[y].write(1) self.board.digital[g].write(1) self.board.digital[b].write(1) self.debug = debug
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 CriaPinos(mini = 2, maxi = 9,tipo = 'p', minis = 10, maxis = 12, tipos = 's'): #TIPO: O:OUTPUT | I:INPUT | P:PWM arduino = ArduinoMega('COM13') for p in range(mini,maxi): AP["pino" + str(p)] = arduino.get_pin('d:{}:{}'.format(p,tipo)) for s in range(minis,maxis): AS["pino" + str(s)] = arduino.get_pin('d:{}:{}'.format(s,tipos))
def __init__(self): self.logicMatrix = [] self.initialize_matrix() self.board = ArduinoMega(PORT, baudrate=RATE) super().__init__(self.board, PIN_DATA_IN, PIN_LOAD, PIN_CLOCK) self.clear() self.layout = [] self.build_layout()
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"
def readPotDatafromArduino(stop): global potData board = ArduinoMega(sys.argv[2]) 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): time.sleep(0.2) prevalue = potData[i] potData[i] = board.analog[i].read() if potData[i] is not None: potData[i] = potData[i] * 1023 else: potData[i] = prevalue
def __init__(self, addr, debug=True): self.board = None self.pins = [] # green # self.pins.append((23, 24, 22, 2)) self.pins.append((26, 27, 25, 3)) self.pins.append((29, 30, 28, 4)) self.pins.append((32, 33, 31, 5)) self.pins.append((35, 36, 34, 6)) self.pins.append((38, 39, 37, 7)) self.pins.append((41, 42, 40, 8)) self.pins.append((44, 45, 43, 9)) if addr is not None: self.board = ArduinoMega(addr) for b in self.pins: self.board.digital[b[3]].mode = pyfirmata.SERVO for c in range(3): self.board.digital[b[c]].write(True) self.debug = debug
def __init__(self, cfg): # load the config self.cfg = cfg self.board = ArduinoMega(cfg['ARDUINO_PORT']) # iterator thread for reading analog pins # self.iter = util.Iterator(self.board) # self.iter.start() # print("iterator running.") # set the select pins as arduino digital pins self.s_pin_num = cfg['MUX_SELECT_PINS'] self.s_pins = [self.board.get_pin('d:' + str(self.s_pin_num[0]) + ':o'), self.board.get_pin('d:' + str(self.s_pin_num[1]) + ':o'), self.board.get_pin('d:' + str(self.s_pin_num[2]) + ':o'), self.board.get_pin('d:' + str(self.s_pin_num[3]) + ':o')] # set the signal pin # self.sig_pin = self.board.get_pin('d:' + str(cfg['MUX_SIG_PIN']) + ':o') # TODO: add some stuff to separate digital and analog pins self.sig_pin = self.board.get_pin('a:0:i') print("Mux connected.")
from time import sleep # from pysine import sine from pyfirmata import ArduinoMega import time upperbt = 60 lowerbt = 0 l = .3 h = .9 board = ArduinoMega('COM15') servo1 = board.get_pin('d:7:s') # servo2 = board.get_pin('d:8:s') servo3 = board.get_pin('d:6:s') # servo4 = board.get_pin('d:9:s') servo5 = board.get_pin('d:5:s') # servo6 = board.get_pin('d:10:s') servo7 = board.get_pin('d:4:s') # servo8 = board.get_pin('d:13:s') servo9 = board.get_pin('d:2:s') # servo10 = board.get_pin('d:12:s') servo11 = board.get_pin('d:3:s') # servo12 = board.get_pin('d:11:s') airpin = board.get_pin('d:14:s') # not used yet # to initialize all values to zero angle servo1.write(0) # servo2.write(0) servo3.write(0) # servo4.write(0) servo5.write(0) # servo6.write(0)
Arduino_SN = arduino_boards.Arduino_SN ArduinoMega_SN = arduino_boards.ArduinoMega_SN Arduinos = {} # Initialize the board dictionary for comport in comports(): # print(comport.vid) # 9025 (type: int) # print(comport.serial_number) # "95530343235351605281" (type: str) # print(comport.device) # "COM4" (type: str) # print(comport) # "COM4 - USB Serial Device (COM4)" (type: class) SN = comport.serial_number if SN in ArduinoMega_SN.keys(): board_name = ArduinoMega_SN[SN] print(board_name, ':', comport.device) # adding the 'timeout' to prevent raising wirteTimeout Error, it's None by default board = ArduinoMega(comport.device, timeout=0) # time.sleep(0.5) # Wait for communication to get established Arduinos[board_name] = board elif SN in Arduino_SN.keys(): board_name = Arduino_SN[SN] print(board_name, ':', comport.device) board = Arduino(comport.device) # time.sleep(0.5) # Wait for communication to get established Arduinos[board_name] = board # =================== assign pins for each board ==================== # Define each board # uno_1 = Arduinos['Uno_1'] # mega_1 = Arduinos['Mega_1'] mega_2 = Arduinos['Mega_2']
from SESCdraw import _DRAW from SESCfunc import _FCM, _FCE, _PASS, _MIN, _MAX, _CEN, _MOV from pyfirmata import ArduinoMega, util MESA = "SIMULACAO" INICIAR = True mega = ArduinoMega('COM3') iterator = util.Iterator(mega) iterator.start() DM_pin_YGOL_ENE = mega.get_pin('d:18:o') DM_pin_YGOL_DIR = mega.get_pin('d:19:o') DM_pin_YGOL_PAS = mega.get_pin('d:20:o') DM_pin_RGOL_ENE = mega.get_pin('d:21:o') DM_pin_RGOL_DIR = mega.get_pin('d:22:o') DM_pin_RGOL_PAS = mega.get_pin('d:23:o') FC_pin_MGOL_MIN = mega.get_pin('d:24:i') FC_pin_MGOL_MAX = mega.get_pin('d:25:i') FC_pin_EGOL = mega.get_pin('d:26:i') DM_pin_YDEF_ENE = mega.get_pin('d:27:o') DM_pin_YDEF_DIR = mega.get_pin('d:28:o') DM_pin_YDEF_PAS = mega.get_pin('d:29:o') DM_pin_RDEF_ENE = mega.get_pin('d:30:o') DM_pin_RDEF_DIR = mega.get_pin('d:31:o') DM_pin_RDEF_PAS = mega.get_pin('d:32:o') FC_pin_MDEF_MIN = mega.get_pin('d:33:i') FC_pin_MDEF_MAX = mega.get_pin('d:34:i') FC_pin_EDEF = mega.get_pin('d:35:i')
import RPi.GPIO as GPIO from pyfirmata import Arduino, ArduinoMega, util import time GPIO.setmode(GPIO.BCM) #def arduino board for onboard comms board = ArduinoMega('/dev/ttyACM0') #in1-4 are for the arduino to interface with motor controller #these determine direction of current in1pin = board.get_pin('d:22:o') in2pin = board.get_pin('d:24:o') in3pin = board.get_pin('d:26:o') in4pin = board.get_pin('d:28:o') #for arduino again, this is PWM to attain speed control enablePin1 = board.get_pin('d:6:p') enablePin2 = board.get_pin('d:7:p') #determines encoder pins input_A = 17 input_B = 22 input_C = 18 input_D = 23 GPIO.setup(input_A, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(input_B, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(input_C, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# -*- coding: utf-8 -*- import time from pyfirmata import ArduinoMega, util import pyfirmata board = ArduinoMega('/dev/ttyUSB0') RED=0 ORANGE=1 GREEN=2 SERVO=3 combinations = [] combinations.append((22, 23, 24, 2)) combinations.append((25, 26, 27, 3)) combinations.append((28, 29, 30, 4)) combinations.append((31, 32, 33, 5)) combinations.append((34, 35, 36, 6)) combinations.append((37, 38, 39, 7)) combinations.append((40, 41, 42, 8)) combinations.append((43, 44, 45, 9)) stime=.5 for combo in combinations: board.digital[combo[SERVO]].mode = pyfirmata.SERVO while True: for i in range(3): for combo in combinations: board.digital[combo[i]].write(False) board.digital[combo[SERVO]].write(0)
if w.serial_number == "558383437333512132D0": ArduinoMegaPort = w.device if w.serial_number == "5": ArduinoNanoPort = w.device # print('Arduino Mega Port: ', ArduinoMegaPort) pygame.init clock = pygame.time.Clock() useArduino = True # Try to connect to the arduino board. If it fails, then we will use the keyboard. # TODO: create something that finds which port the arduino is connected to... try: arduino = ArduinoMega(ArduinoMegaPort) # arduino = ArduinoMega('/dev/ttyACM1') # arduino = ArduinoMega('/dev/ttyACM0') # arduino = ArduinoMega('COM7') time.sleep(0.2) iterator = util.Iterator(arduino) iterator.start() time.sleep(0.2) # Define all input pins PIN_ONE = arduino.get_pin("d:37:i") PIN_TWO = arduino.get_pin("d:36:i") PIN_THREE = arduino.get_pin("d:35:i") PIN_LEFT = arduino.get_pin("d:32:i") PIN_RIGHT = arduino.get_pin("d:31:i") PIN_UP = arduino.get_pin("d:34:i")
def CriaPinos(mini = 2, maxi = 13,tipo = 'p'): #TIPO: O:OUTPUT | I:INPUT | P:PWM arduino = ArduinoMega('COM3') for i in range(mini,maxi): AP["pino" + str(i)] = arduino.get_pin('d:{}:{}'.format(i,tipo))
""" import cv2 import numpy as np import pygame from pygame.locals import * import time from pyfirmata import ArduinoMega, util from OpenGL.GL import * from OpenGL.GLU import * face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') body_cascade = cv2.CascadeClassifier('haarcascade_fullbody.xml') board = ArduinoMega('COM4') iterator = util.Iterator(board) iterator.start() S1 = board.get_pin('d:5:p') #ght D1 = board.get_pin('d:7:o') #right S2 = board.get_pin('d:4:p') #ft D2 = board.get_pin('d:6:o') #left time.sleep(1.0) def left(): for i in range(50): S1.write(i) D1.write(0) S2.write(i) #left forward
from pyfirmata import ArduinoMega, util from pyfirmata import SERVO import time board = ArduinoMega('com3') board.digital[7].mode = SERVO board.digital[6].mode = SERVO window_width = 650 window_height = 400 def translate(value, leftMin, leftMax, rightMin, rightMax): # Figure out how 'wide' each range is leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin # Convert the left range into a 0-1 range (float) valueScaled = float(value - leftMin) / float(leftSpan) # Convert the 0-1 range into a value in the right range. return rightMin + (valueScaled * rightSpan) def getValues(): try: f = open('values.txt','r') values = f.read().split(':') f.close return values except: pass
from pyfirmata import ArduinoMega, util import time import pyfirmata board = ArduinoMega('/dev/tty.usbmodem1441') #board = ArduinoMega('COM8') board.analog[0].mode = pyfirmata.INPUT it = util.Iterator(board) it.start() board.analog[0].enable_reporting() while True: print(board.analog[0].read())
def setBoard(boardType, port): if boardType == 'arduino': board = Arduino(port) else: board = ArduinoMega(port) return board
device_helpers) except (SystemError, ImportError): import assistant_helpers import audio_helpers import browser_helpers import device_helpers ASSISTANT_API_ENDPOINT = 'embeddedassistant.googleapis.com' END_OF_UTTERANCE = embedded_assistant_pb2.AssistResponse.END_OF_UTTERANCE DIALOG_FOLLOW_ON = embedded_assistant_pb2.DialogStateOut.DIALOG_FOLLOW_ON CLOSE_MICROPHONE = embedded_assistant_pb2.DialogStateOut.CLOSE_MICROPHONE PLAYING = embedded_assistant_pb2.ScreenOutConfig.PLAYING DEFAULT_GRPC_DEADLINE = 60 * 3 + 5 port = '/dev/ttyACM0' board = ArduinoMega(port) sleep(1) pin13 = board.get_pin('d:13:p') class SampleAssistant(object): """Sample Assistant that supports conversations and device actions. Args: device_model_id: identifier of the device model. device_id: identifier of the registered device instance. conversation_stream(ConversationStream): audio stream for recording query and playing back assistant answer. channel: authorized gRPC channel for connection to the Google Assistant API. deadline_sec: gRPC deadline in seconds for Google Assistant API call.
def ir_mux(ir_name): logging.debug('Starting') # ------- connect to IR hardwares -------- board_port = ir_port # The port is from the USB port ir_board = ArduinoMega( board_port) # Creat the Serial port for ArduinoMega board # first multiplexer, define switch and signal pins on boards PinS, PinSig = mux.DefinePin(ir_board, [30, 31, 32, 33], 3) # second multiplexer, define switch and signal pins on boards PinS2, PinSig2 = mux.DefinePin(ir_board, [40, 41, 42, 43], 4) logging.debug('connected to IR board') # ------- initialize hardwares and variables ------ # start switches with connectin to channel 0 mux.SwitchMUX(PinS, 0) mux.SwitchMUX(PinS2, 0) Data = {} # Creat an empty dictionary num_of_data = 2000 # ------ start Iterator to avoid serial overflow ----- it = util.Iterator( ir_board) # need this iteration otherwise pin just reporting 'None' it.start() time.sleep(0.5) # ------ start collect data ------ for n in range(32): # logging.debug('IR channel '+str(n+1)+'...') print("IR channel " + str(n + 1) + "...") t = [] v = [] t0 = time.time() if n < 16: # It's on the first mutiplexer mux.SwitchMUX(PinS, n) time.sleep(0.1) for m in range(num_of_data): t.append(time.time() - t0) v.append( float(mux.Read(PinSig)) ) # mux returns a string, need to transfer to float number time.sleep(0.000001) Data['Time' + str(n + 1)] = t Data['Chan' + str(n + 1)] = v else: # switch to the second mutiplexer, need to re-define channel number m = n - 16 mux.SwitchMUX(PinS2, m) time.sleep(0.1) for m in range(num_of_data): t.append(time.time() - t0) v.append( float(mux.Read(PinSig2)) ) # MUX returns a string, need to transfer to float number time.sleep(0.000001) Data['Time' + str(n + 1)] = t Data['Chan' + str(n + 1)] = v ir_board.exit() np.save( os.path.join(file_dir, ir_name), Data ) # use np.load(filename) to read data, and dict will be in .item() freq = [] drops = [] for i in range(32): time_title = 'Time' + str(i + 1) chan_title = 'Chan' + str(i + 1) time_stamp = Data[time_title] ir = Data[chan_title] ir = np.array(ir) # convert list to array, for the following process rel_ir = -1 * ir + max(ir) cut_height = 0.3 * max(rel_ir) spec_cut_half = rel_ir - cut_height fwhm_index = np.where(np.diff(np.sign(spec_cut_half)))[0] peak_numbs = len(fwhm_index) / 2 # time lapse between reading is 1ms, the unit below is ms liq_total_time = sum(counter > cut_height for counter in rel_ir) freq.append(peak_numbs / (time_stamp[-1] - time_stamp[0])) # unit Hz drops.append(liq_total_time / peak_numbs) # unit: ms/drop print('########### Droplet frequency is ' + str(np.mean(freq)) + ' Hz ##############') print('########### Droplet size is ' + str(np.mean(drops)) + ' ms/drop ##############') logging.debug('Exiting')
from pyfirmata import ArduinoMega, util import pyfirmata, pyfirmata.util import time import pygame from random import seed from random import randint from random import seed from random import choice # Initialize PyGame and PyFirmata pygame.mixer.init() board = ArduinoMega('COM7', baudrate=57600) iterator = pyfirmata.util.Iterator(board) iterator.start() time.sleep(1) # Button Pin Declarations button2 = board.get_pin('d:2:i') button4 = board.get_pin('d:4:i') button6 = board.get_pin('d:6:i') button8 = board.get_pin('d:8:i') button10 = board.get_pin('d:10:i') button12 = board.get_pin('d:12:i') button30 = board.get_pin('d:30:i') button32 = board.get_pin('d:32:i') button34 = board.get_pin('d:34:i') button36 = board.get_pin('d:36:i')