def robotSetup(): try: connection = SerialManager() a = ArduinoApi(connection = connection) except: print("Failed to connect to Arduino") sys.exit() a.pinMode(STDBY1, a.OUTPUT) a.pinMode(STDBY2, a.OUTPUT) FR = Motor(AI1, AI2, APWM) FR.setupMotor(a) BR = Motor(BI1, BI2, BPWM) BR.setupMotor(a) FL = Motor(CI1, CI2, CPWM) FL.setupMotor(a) BL = Motor(DI1, DI2, DPWM) BL.setupMotor(a) a.digitalWrite(STDBY1, a.HIGH) a.digitalWrite(STDBY2, a.HIGH) robot = Robot(FR, BR, FL, BL, a) return robot
def on(self): threading.Thread(target=self.alert.ledOn).start() if self.boardID == 2: # Board is Raspberry Pi try: GPIO.output(int(self.pin), False) notify = "{}-{} On".format(self.appliance, self.device_name) notifyLCD = "{}".format(self.device_name) print(notify) self.updateState(1) self.alert.display2(notifyLCD, "On") return True except Exception as e: print("Process Raspberry Pi failed {}".format(str(e))) return False elif self.boardID == 1: # Board is Arduino try: conn = SerialManager() a = ArduinoApi(conn) a.pinMode(int(self.pin), a.OUTPUT) a.digitalWrite(int(self.pin), a.LOW) notify = "{}-{} On".format(self.appliance, self.device_name) notifyLCD = "{}".format(self.device_name) print(notify) self.updateState(1) self.alert.display2(notifyLCD, "On") return True except Exception as e: print("Failed to connect to Arduino {}".format(str(e))) return False
def barcode_funder(): arduino = SerialManager(device='/dev/ttyACM0') # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-o", "--output", type=str, default="barcodes.csv", help="path to output CSV file containing barcodes") args = vars(ap.parse_args()) # initialize the video stream and allow the camera sensor to warm up print("[INFO] starting video stream...") # vs = VideoStream(src=0).start() vs = VideoStream(usePiCamera=True).start() time.sleep(2.0) # open the output CSV file for writing and initialize the set of # barcodes found thus far csv = open(args["output"], "w") found = set() # loop over the frames from the video stream BarCodes = [] while True: # grab the frame from the threaded video stream and resize it to # have a maximum width of 400 pixels frame = vs.read() frame = imutils.resize(frame, width=600) # find the barcodes in the frame and decode each of the barcodes barcodes = pyzbar.decode(frame) # loop over the detected barcodes if barcodes: arduino.write('stop') for barcode in barcodes: # extract the bounding box location of the barcode and draw # the bounding box surrounding the barcode on the image (x, y, w, h) = barcode.rect cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # the barcode data is a bytes object so if we want to draw it # on our output image we need to convert it to a string first barcodeData = barcode.data.decode("utf-8") # THIS IS IMPORTANT barcodeType = barcode.type BarCodes.append(barcodeData) sleep(2) return barcodeData, csv.close(), cv2.destroyAllWindows(), vs.stop() # print(BarCodes) # draw the barcode data and barcode type on the image # text = "{} ({})".format(barcodeData, barcodeType) # cv2.putText(frame, text, (x, y - 10), # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) # if the barcode text is currently not in our CSV file, write # the timestamp + barcode to disk and update the set if barcodeData not in found: csv.write("{},{}\n".format(datetime.datetime.now(), barcodeData)) csv.flush() found.add(barcodeData)
def ConnectArduino(): try: connection = SerialManager(device='/dev/ttyACM0') ConnectArduino.a = ArduinoApi(connection=connection) print("\n\nConnection Successful...\n\n") except: print("\n\nFailed to connect...\n\n")
def ConnectArduino(): #establish connection with arduino try: connection = SerialManager( device='/dev/ttyACM0') #change device path for multiple Arduinos ConnectArduino.a = ArduinoApi(connection=connection) print("\n\nConnection Successful...\n\n") except: print("\n\nFailed to connect...\n\n")
def arduino_api_scope(self): connection = SerialManager(device=self.arduino_port) arduino = ArduinoApi(connection=connection) try: yield arduino finally: connection.close()
def connect(self): # close old connection if exists if self.serialManager: self.serialManager.close() # make new connection self.serialManager = SerialManager() self.a = ArduinoApi(connection=self.serialManager)
def connectToArduino(): try: con = SerialManager(timeout=3) api = ArduinoApi(connection=con) return api except Exception as e: print "Failed to connect to Arduino" print e sys.exit(1)
def __init__(self, intent): self.intent = intent if Util.is_system_mac(): return # initialize raspberry pi connection = SerialManager(device='/dev/ttyACM0') self.arduino_conn = ArduinoApi(connection=connection) self.equipment = self.intent["EquipmentKeyword"] self.state = self.intent["OnOffKeyword"]
def connect(self): attempts = 3 conn = None if self.config.get('use_wifi', False): while attempts > 0 and self.main_thread_running.is_set(): try: Logger.log(LOG_LEVEL["debug"], '\033[1;36m{0}\033[0;0m -> Connecting... \t'.format(self.config["name"], (3-attempts))) attempts-= 1 conn = SocketManager(host=str(self.config.get('address', 'mudpi.local'))) # Test the connection with api self.api = ArduinoApi(connection=conn) except (SocketManagerError, BrokenPipeError, ConnectionResetError, socket.timeout) as e: Logger.log(LOG_LEVEL["warning"], '{name} -> Connecting...\t\t\033[1;33m Timeout\033[0;0m '.format(**self.config)) if attempts > 0: Logger.log(LOG_LEVEL["info"], '{name} -> Preparing Reconnect... \t'.format(**self.config)) else: Logger.log(LOG_LEVEL["error"], '{name} -> Connection Attempts...\t\033[1;31m Failed\033[0;0m '.format(**self.config)) conn = None self.resetConnection() time.sleep(15) except (OSError, KeyError) as e: Logger.log(LOG_LEVEL["error"], '[{name}] \033[1;33m Node Not Found. (Is it online?)\033[0;0m'.format(**self.config)) conn = None self.resetConnection() time.sleep(15) else: Logger.log(LOG_LEVEL["info"], '{name} -> Wifi Connection \t\t\033[1;32m Success\033[0;0m '.format(**self.config)) for worker in self.workers: worker.connection = conn self.node_connected.set() self.node_ready.set() break else: while attempts > 0 and self.main_thread_running.is_set(): try: attempts-= 1 conn = SerialManager(device=str(self.config.get('address', '/dev/ttyUSB1'))) except SerialManagerError: Logger.log(LOG_LEVEL["warning"], '{name} -> Connecting...\t\t\033[1;33m Timeout\033[0;0m '.format(**self.config)) if attempts > 0: Logger.log(LOG_LEVEL["info"], '{name} -> Preparing Reconnect... \t'.format(**self.config), end='\r', flush=True) else: Logger.log(LOG_LEVEL["error"], '{name} -> Connection Attempts...\t\033[1;31m Failed\033[0;0m '.format(**self.config)) self.resetConnection() conn = None time.sleep(15) else: if conn is not None: Logger.log(LOG_LEVEL["info"], '[{name}] Serial Connection \t\033[1;32m Success\033[0;0m '.format(**self.config)) for worker in self.workers: worker.connection = conn self.node_connected.set() self.node_ready.set() break return conn
def nanpyConnect(): # Manually ask the user to enter port number for Arduino #num = input("What port is Arduino plugged in to?: ") #port = '/dev/ttyACM' + str(num) try: connection = SerialManager(device='/dev/ttyUSB-ArduinoMEGA') a = ArduinoApi(connection = connection) print'Arduino communication was successful.' return a except: print'Unable to communicate with Arduino.'
def water_read_moisture(pin='A0'): air = 580 water = 277 connection = SerialManager() a = ArduinoApi(connection=connection) a.pinMode(pin, 'INPUT') moisture_read = ((a.analogRead(pin) * -1) + air) / 3.05 return moisture_read
def establish_connection(self): # establish connection to the Arduino try: conn = SerialManager() trig = 12 echo = 13 a = ArduinoApi(connection=conn) self.ultrasonic = Ultrasonic(echo, trig, False, connection=conn) return a except: sys.exit("Failed to establish connection with the Arduino") return None
def connectUSB(self): log.info("Rapberry Arduino connection Started...") # https://pypi.python.org/pypi/nanpy # https://github.com/nanpy/nanpy-firmware try: #connection = SerialManager(device='/dev/ttyUSB0') self.serialdevicename == self.config_handler.getConfigParam( "DEVICES", "GARAGE_SERIAL_MANAGER_DEVICE") tmplog = ("Garage Device configured : %s" % self.serialdevicename) log.info(tmplog) if self.serialdevicename.upper() == "ANY": connection = SerialManager() else: connection = SerialManager(self.serialdevicename) self.usbConnectHandler = ArduinoApi(connection=connection) tmplog = "Garage Device: %s" % self.usbConnectHandler.connection.device log.info(tmplog) pass except Exception: log.info("USB Device Not found !") # os._exit(-1) return
def main(pir_pin=2,inactiveDuration=10,outdir="."): """ *Parameters* > `pir_pin<int>`: the GPIO signal pin (in BCM mode) of the PIR motion sensor > `inactiveDuaration<int>`: specifies when the camera should stop recording after no motion has been detected > `outdir<str>`: the path to the desired directory of which to save the video files """ # === Local Variables === camera = PiCamera() # === setup Arduino === connection = SerialManager() a = ArduinoApi(connection=connection) # === start main loop === while True: # === sense PIR motion === motionDetected = a.digitalRead(pir_pin) print(motionDetected) # === condition === if motionDetected: print("started recording...") # === start recording === # Set-up camera camera.resolution = (1024,768) # Start camera camera.start_preview() # Camera warm-up time time.sleep(2) # Determine output filename outfilename = datetime.datetime.now().strftime("%m-%d-%Y-%H-%M-%S") + ".h264" # Start Recording camera.start_recording(outdir+"/"+outfilename) while motionDetected: # record for duration time.sleep(inactiveDuration) # detected motion motionDetected = a.digitalRead(pir_pin) # Stop Recording camera.stop_recording() print("recording finished")
def __init__(self, config, main_thread_running, system_ready): #self.config = {**config, **self.config} self.config = config self.main_thread_running = main_thread_running self.system_ready = system_ready self.node_ready = False attempts = 3 if self.config.get('use_wifi', False): while attempts > 0: try: attempts -= 1 self.connection = SocketManager( host=str(self.config.get('address', 'mudpi.local'))) self.sensors = [] self.init_sensors() except SocketManagerError: print( '[{name}] \033[1;33m Node Timeout\033[0;0m ['.format( **self.config), attempts, ' tries left]...') time.sleep(15) print('Retrying Connection...') else: print( '[{name}] Wifi Connection \t\033[1;32m Success\033[0;0m' .format(**self.config)) self.node_ready = True break else: while attempts > 0: try: attempts -= 1 self.connection = SerialManager( device=str(self.config.get('address', '/dev/ttyUSB1'))) self.sensors = [] self.init_sensors() except SerialManagerError: print( '[{name}] \033[1;33m Node Timeout\033[0;0m ['.format( **self.config), attempts, ' tries left]...') time.sleep(15) print('Retrying Connection...') else: print( '[{name}] Serial Connection \t\033[1;32m Success\033[0;0m' .format(**self.config)) self.node_ready = True break return
def __init__(self, box_id, config_box): self.box_id = box_id self.config_box = config_box if not BoxGpio._PARAM_PIN_CONTROLLER in self.config_box: self.arduino = None logging.info(f"Box {self.box_id} has no pin controller") else: connection = SerialManager( device=self.config_box[BoxGpio._PARAM_PIN_CONTROLLER]) self.arduino = ArduinoApi(connection=connection) self.set_power(False) self.set_fan(0)
def setup_arduino(): ''' Setup arduino connection :return: Arduino API object used to control Arduino UNO ''' a = None try: connection = SerialManager() a = ArduinoApi(connection=connection) a.pinMode(Util.ledPin, a.OUTPUT) except: # arduino_present = False # print("Arduino device not found") pass return a
def hello(): connection = SerialManager(sleep_after_connect=2) cols, rows = 16, 2 if I2C: pins = [0x27, 2, 1, 0, 4, 5, 6, 7, 3, 0] # "ebay" version lcd = Lcd_I2C(pins, [cols, rows], connection=connection) lcd.setBacklight(0) else: pins = [7, 8, 9, 10, 11, 12] lcd = Lcd(pins, [cols, rows], connection=connection) lcd.setCursor(0, 0) lcd.printString('hello')
def ArdConnect(com): global run try: # Establish serial communication with Arduino connection = SerialManager(device=com) ard = ArduinoApi(connection) # print('--> Arduino connected in port ' + com) run = True # indicate that arduino connection is done return ard # return an 'ArduinoApi' object except Exception: print('-->! Arduino is not connected') run = False # indicate that arduino connection could not be done return False # return a 'False' value
def ArdConnect(com): global run try: print('\nAttempting to connect to the given port -> ' + com) #Print message to user print('Connecting...') connection = SerialManager( device=com) #Connected to the provided serial com name ard = ArduinoApi(connection=connection) #Connect to the arduino print("Arduino connected") #Print message to user run = True #set run flag to true return ard #return the arduino object except: run = False #if tiem runs out set flag to False print('Error :Connection Failed!!') #Print message to user return 'EMPTY' #Return an empty object(String)
def __init__(self, size=60, crossover=0.8, elitism=0.1, mutation=0.03): self.elitism = elitism self.mutation = mutation self.crossover = crossover self.population = [] self.connection = SerialManager() self.a = ArduinoApi(connection=self.connection) for r in range(12): self.a.pinMode(r, self.a.OUTPUT) for i in range(size): self.population.append(Chromosome.gen_random()) self._setFitness() self.population = list(sorted(self.population, key=lambda x: x.fitness))
def __init__(self, _lcd): threading.Thread.__init__(self) try: self.conn = SerialManager() self.a = ArduinoApi(self.conn) except: print("Failed to connect to Arduino.") self.analogIn = '******' self.mVperAmp = 66 # use 100 for 20A Module and 66 for 30A Module self.voltage = 0 self.amps = 0 self.rawValue = 0 self.default = 510 # Current = Voltage You Applied / The Resistance of your Load self.lcd = _lcd
def __init__(self): """ Creation of connection to the arduino through nanpy and initialisation of the used Pins """ try: connection = SerialManager() self.asdw_m = ArduinoApi(connection=connection) print("failed to upload") except: print("didn't worked") self.asdw_m.pinMode(l_turn, self.asdw_m.OUTPUT) self.asdw_m.pinMode(back_d, self.asdw_m.OUTPUT) self.asdw_m.pinMode(r_turn, self.asdw_m.OUTPUT) self.asdw_m.pinMode(forward_d, self.asdw_m.OUTPUT)
def __init__(self): # self.gpio17 = rpilib.GPIOrtx('17') # self.gpio18 = rpilib.GPIOrtx('18') # self.gpio22 = rpilib.GPIOrtx('22') # self.gpio23 = rpilib.GPIOrtx('23') try: connection = SerialManager() self.a = ArduinoApi(connection=connection) except: print('Failed to connect to Arduino!') self.ENA = 10 self.ENB = 5 self.IN1 = 9 self.IN2 = 8 self.IN3 = 7 self.IN4 = 6
def establish_connection(): global a # Establish connection to Arduino try: connection = SerialManager() a = ArduinoApi(connection=connection) print "Connection established!" except: print "Connection Error!" # Setup Pinmodes try: a.pinMode(relais, a.OUTPUT) a.pinMode(smoke, a.INPUT) print "PinModes set!" except: print "Could not set PinModes!" return True
def __init__(self, uc_pin=7, ub_pin=8, pc_pin=12, pb_pin=13): # set member variables self.upstream_state = None self.phy_state = None self.uc_pin = uc_pin self.ub_pin = ub_pin self.pc_pin = pc_pin self.pb_pin = pb_pin # connect to the arduino device over serial connection self.connection = SerialManager() self.api = ArduinoApi(connection=self.connection) # initialize pins as output self.api.pinMode(self.uc_pin, self.api.OUTPUT) self.api.pinMode(self.ub_pin, self.api.OUTPUT) self.api.pinMode(self.pc_pin, self.api.OUTPUT) self.api.pinMode(self.pb_pin, self.api.OUTPUT)
def __init__(self, connection_path): try: connection = SerialManager(connection_path) self.arduino = ArduinoApi(connection=connection) self.ultrasonic = Ultrasonic(self.EchoPin, self.TrigPin, False, connection=connection) except: print("Failed to connect to the arduino") # Motors set up self.arduino.pinMode(self.Motor1A, self.arduino.OUTPUT) self.arduino.pinMode(self.Motor1B, self.arduino.OUTPUT) self.arduino.pinMode(self.Motor2A, self.arduino.OUTPUT) self.arduino.pinMode(self.Motor2B, self.arduino.OUTPUT) # Sensor set up self.arduino.pinMode(self.TrigPin, self.arduino.OUTPUT) self.arduino.pinMode(self.EchoPin, self.arduino.INPUT)
def __init__(self): try: connection = SerialManager( device='/dev/ttyACM0') # TODO script bash y variable ard = ArduinoApi(connection=connection) #lcd.setCursor(0,0) #Lcd_display.write_lcd(connection,"Conectado Ard:Pi") except: #Lcd_display.write_lcd(connection,"Err Conn Arduino") print('error') # TODO: FLAG TO RESTART /SEARCH ARDUINO self.water_pump = sensors.Control(False, 8, ard) self.uv_light = sensors.Control(False, 9, ard) self.heater = sensors.Control(False, 10, ard) self.rwater_level = sensors.Control(False, 11, ard) self.rwater_fill = sensors.Control(False, 12, ard) self.wave_maker = sensors.Control(False, 13, ard) self.uv_rele = sensors.Control(False, 7, ard) self.water_flow = sensors.Control(False, 6, ard) self.temp = sensors.Check_Sensor(5, "state")
def connect_to_arduino(self): global a, ard_setup_parameters if self.radBtn3.isChecked(): try: from nanpy import (SerialManager, ArduinoApi) connection = SerialManager() a = ArduinoApi(connection=connection) self.new_edit3.setDisabled(False) self.load3.setDisabled(False) self.save3.setDisabled(False) except: print("Failed to connect to Arduino") self.radBtn3.setChecked(False) # change back to False elif not self.radBtn3.isChecked(): try: del a except: pass ard_setup_parameters = None self.new_edit3.setDisabled(True) self.load3.setDisabled(True) self.save3.setDisabled(True)