class Ard_T(object): def __init__(self, address, pin): self.address = address self.pin = pin self.ard = Arduino(address) self.ard.output([]) self.aref = 3.3 def readTemp(self): # Celcius V = int((self.ard).analogRead(self.pin)) * self.aref / 1024 T = (V - 1.250) / .005 return T def isSafeTemp(self): crit = 35 # 32 temp = self.readTemp() return (temp < crit) def isStartTemp(self): crit = 25 # 27 temp = self.readTemp() # print(temp) return (temp < crit) def isWarmTemp(self): crit = 15 # 32 temp = self.readTemp() # print(temp) return (temp > crit)
class WhatsHappening(object): _screenPos = 0 _mail = Mail() _owm = pyowm.OWM('4c046ad50263519b269d79a1e9453a53') def __init__(self, port): self._arduino = Arduino(port) def update(self): #ip = socket.gethostbyname(socket.gethostname()) if self._screenPos == 0: observation = self._owm.weather_at_place('halifax,ns') w = observation.get_weather() temp = w.get_temperature(unit='celsius')['temp'] status = w.get_status() hum = w.get_humidity() line_one = '%s %dC %d%%' % (status, temp, hum) line_two = '%s' % time.strftime("%a %b %d") self._screenPos += 1 else: line_one = 'Email:%d' % self._mail.unread_messages() line_two = 'RAM:%d%% CPU:%d%%' % (psutil.virtual_memory().percent, psutil.cpu_percent()) self._screenPos = 0 self._arduino.clear() self._arduino.write('%s\r\n%s' % (line_one, line_two))
def __init__(self): self.board = Board() self.game_over = False self.opencv = OpenCV() self.turn = random.randint(player_piece, AI_piece) self.minmaxPlayer = MiniMaxPlayer() self.arduino = Arduino()
def __init__(self): wx.Frame.__init__(self, None, title=self.title, size=(650, 570)) if platform.system() == 'Windows': arduino_port = 'COM4' else: arduino_port = '/dev/ttyACM0' # Try Arduino try: self.arduino = Arduino(arduino_port, 115200) except: msg = wx.MessageDialog( self, 'Unable to connect to arduino. Check port or connection.', 'Error', wx.OK | wx.ICON_ERROR) msg.ShowModal() == wx.ID_YES msg.Destroy() self.create_main_panel() self.recording = False self.output_file = '' time.sleep(1) # Timer self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_timer, self.timer) self.rate = 500 self.timer.Start(self.rate)
def __init__(self, *args): ManagedThread.__init__(self, *args) self.rotation = 0.0 self.arduino = Arduino() # config read from ~/.robovision/pymata.conf self.rotation, self.x, self.y = 0, 0, 0.2 self.state = None self.prev = None
class Request: STP = 'a' STR = 'b' ROT = 'c' GET_MODE = 'e' GET_DIST = 'f' GET_BATT = 'g' def __init__(self): self.arduino = Arduino() def set(self, cmd_data): self.arduino.send(cmd_data) def get(self, mode): cmd_data = [mode, 0, 0] self.set(cmd_data) return self.arduino.receive() def get_dist(self): cmd_data = self.get(Request.GET_DIST) if cmd_data is False: return False return cmd_data[1], cmd_data[2] # Left, Rightの順番 def get_batt(self): cmd_data = self.get(Request.GET_BATT) if cmd_data is False: return False return cmd_data[1] / 100.0
def discover(self): print("Louis has started. Running cell discovery ...") arduino = Arduino() num_cells = arduino.discover() print(num_cells) cells = [Cell(i) for i in range(1, num_cells + 1)] print("Cell discovery completed. " + str(num_cells) + " cells found.") return arduino, cells
def __init__(self, *args, **kwargs): ManagedThread.__init__(self, *args) self.arduino = Arduino() # config read from ~/.robovision/pymata.conf self.state = Patrol(self) self.recognition = None self.closest_edges = [] self.safe_distance_to_goals = 1.4 self.config = config
def __init__(self, **kwargs): super().__init__(**kwargs) Window.clearcolor = (204 / 255, 229 / 255, 255 / 255, 1) self.sound = Sound() self.header = Header() self.body = Body() self.arduino_queue = Queue(maxsize=10) Arduino.initialize(self.arduino_queue) Sound.header = self.header Clock.schedule_interval(self.getQueueUpdates, 0.05)
class Neopixel(): def __init__(self): self.board = Arduino() self.board.connect() def reset(self): return self.board.sendCommand(Commands.RESET_NEO_PIXELS,0,0) def writePixel(self,pixel,r,g,b): return self.board.sendCommand(Commands.WRITE_NEO_PIXEL,0,pixel,r,g,b)
def getArduino(temperatura, presenca, luminosidade): a1 = Arduino() # Criação do objeto arduino a1.temperatura = temperatura a1.presenca = presenca a1.luminosidade = luminosidade dao = ArduinoDAO() dao.create(a1) output = "Temperatura: " + str(a1.temperatura) + ", " + "Presença: " + str(a1.presenca) + ", " + "Luminosidade: " + str(a1.luminosidade) return output
def __init__(self, arduino_device_path, pump_configs, flow_rate): self._arduino = Arduino(arduino_device_path) self._pump_configs = pump_configs self._flow_rate = flow_rate output_pins = [] for config in self._pump_configs: output_pins.append(config.get_enable_pin_number()) output_pins.append(config.get_forward_pin_number()) output_pins.append(config.get_reverse_pin_number()) self._arduino.output(output_pins)
class Encoder(): def __init__(self): self.board = Arduino() self.board.connect() def getRevsright(self): rightrevs = self.board.sendCommand(Commands.READ_RIGHT_ENCODER,0,-1) return rightrevs def getRevsleft(self): leftrevs = self.board.sendCommand(Commands.READ_LEFT_ENCODER,0,-1) return leftrevs
def __init__(self, datapath): self.logger = getLogger('thinkleg') self.datapath = datapath self.change_event = Event() self.arduino = Arduino(path=self.datapath, fname='arduino') self.arduino.start() super().__init__() self.title('ThinkLegTaskApp') self.first = FirstFrame(self) self.first.grid(row=0, column=0) self.time_manager = TimeManager(self) self.logger.debug('ThinkLegApp is initialized.')
class Main: def __init__(self): self.board = Board() self.game_over = False self.opencv = OpenCV() self.turn = random.randint(player_piece, AI_piece) self.minmaxPlayer = MiniMaxPlayer() self.arduino = Arduino() def game_loop(self): self.opencv.capture() # start opencv record and "red" detection if self.arduino.arduino_receive() == 1: # if button is pressed if self.turn == player_piece: col = self.opencv.get_new_stone( ) # detect red object, get column of location if self.board.is_possible_move(col): row = self.board.next_open_row(col) self.board.place_piece(row, col, player_piece) self.arduino.arduino_com_PLAYER( row, col) # send piece position to arduino if self.board.winning_move(player_piece): print("player wins") self.game_over = True self.arduino.arduino_com_PLAYER( 10, 10) # turn all the LEDs on (player color) self.board.print_board() self.turn = AI_piece # AI turn if self.turn == AI_piece and not self.game_over: time.sleep( 1 ) # wait a second to establish the arduino connection if AI starts col = self.minmaxPlayer.do_move( self.board) # get the best column to place the move if self.board.is_possible_move(col): row = self.board.next_open_row(col) self.board.place_piece(row, col, AI_piece) self.arduino.arduino_com_AI(row, col) if self.board.winning_move(AI_piece): print("AI wins") self.game_over = True self.arduino.arduino_com_AI(10, 10) self.board.print_board() self.turn = player_piece
class Ultrasound(): def __init__(self): self.board = Arduino() self.board.connect() def getDistance(self): distance = int(self.board.sendCommand(Commands.READ_ULTRASOUND,TRIGGER_PIN,0)) # large distances are reported as 0, so change to max distance if distance == 0: distance = 100 # limit to 100 elif distance > 100: distance = 100 return distance
class ImageServer: def __init__(self, port='COM7'): imgdir = 'images' self.images = [os.path.join(imgdir, fname) for fname in os.listdir(imgdir)] self.arduino = Arduino(port, 9600) def run(self): while True: code = self.arduino.serial.read(1) if code == 'A': print 'got request for image' self.send_image(random.choice(self.images)) elif code == 'B': print 'got request for column' self.send_cols(random.choice(self.images)) elif code == 'C': print 'got request for title' self.send_image('title.png') def send_image(self, imgpath): img = Image.open(imgpath) print 'sending {0}...'.format(os.path.basename(imgpath)) # this next line breaks the list of pixels into groups of 2 for colour1, colour2 in zip(*[iter(img.getdata())] * 2): r1, g1, b1 = convert_colour(*colour1) r2, g2, b2 = convert_colour(*colour2) self.arduino.write_ints(r1 << 4 | g1, b1 << 4 | r2, g2 << 4 | b2) self.arduino.serial.read(1) print 'done.' def send_cols(self, imgpath): img = Image.open(imgpath) pix = img.load() w, h = img.size for x in xrange(w): print 'sending column', x if x > 0: self.arduino.serial.read(1) for y in xrange(0, h, 2): r1, g1, b1 = convert_colour(*pix[x, y]) r2, g2, b2 = convert_colour(*pix[x, y + 1]) self.arduino.write_ints(r1 << 4 | g1, b1 << 4 | r2, g2 << 4 | b2)
def __init__(self): threading.Thread.__init__(self) #self.pc = PC(tcp_ip="192.168.1.1") self.android = Android() self.arduino = Arduino() #self.pc.connect() self.android.connect() self.arduino.connect() time.sleep(1) self.interface = Interface(arduino=self.arduino, fakeRun=False, android=self.android)
def initialize(self, uni): """docstring for __init__""" self.arduino = Arduino() self.arduino.start() self.client = MongoClient('localhost', 27017) self.uni = uni self.mongo_gestures = self.client.affordance.gestures self.mongo_envelopes = self.client.affordance.envelopes self.mongo_users = self.client.affordance.users self.mongo_tracking = self.client.affordance.tracking self.mongo_studies = self.client.affordance.studies self.list_obj = [] self.current_study_participant = None self.data_fetcher = DataFetcher(self.client.affordance) self.zap_speed = 1500 self.zap_strength = {"ems1": self.arduino.channels['ems1']['min_max'][0], "ems2": self.arduino.channels['ems2']['min_max'][0]} self.zap_gestures = {"squeeze": False, "shake": False, "repel": False, "tap": False, "rotate": False, "ems1": False, "ems2": False, "ems3": False, "ems4": False} #self.data_fetcher = DataFetcher(self.mongo_tracking, False) # Recorded data! self.hand = Hand(self.data_fetcher, self.client.affordance, self.arduino) self.uni.hand = self.hand #screw_driver = AffordanceObjects(self.data_fetcher, self.uni, self.arduino, ["screwdriver_trackable"], "screwdriver", "Screwdriver") #screw_brick = AffordanceObjects(self.data_fetcher, self.uni, self.arduino, ["screw_brick_trackable"], "screw_brick", "Screw brick") #teapot = AffordanceObjects(self.data_fetcher, self.uni, self.arduino, ["teapot_trackable"], "teapot", "Teapot") #spray_can = AffordanceObjects(self.data_fetcher, self.uni, self.arduino, ["spray_can_trackable"], "spray_can", "Spray Can") #lamp = AffordanceObjects(self.data_fetcher, self.uni, self.arduino, ["hot_cup_trackable"], "hot_cup", "hot_cup") #paint_brush = AffordanceObjects(self.data_fetcher, self.uni, self.arduino, ["paint_trackable"], "paint_brush", "Paint brush") self.hand.start() self.data_fetcher.register_trackers()
def __init__(): root = Tk() arduino_due = Arduino() root.bind('w', event_w) root.bind('a', event_a) root.bind('d', event_d) root.mainloop()
def test_str(capsys): a = Arduino("Test Arduino") bar = Bargraph("Test Bargraph", "Test api", {"type": "green"}) bar.attach(a, 0) bar.set(24, 24) print str(bar) out, err = capsys.readouterr() assert out == "[GGGGGGGGGGGGGGGGGGGGGGGG]\n" bar.set(12, 24) print str(bar) out, err = capsys.readouterr() assert out == "[GGGGGGGGGGGG ]\n" bar.set(6, 24) print str(bar) out, err = capsys.readouterr() assert out == "[GGGGGG ]\n" bar.set(0, 24) print str(bar) out, err = capsys.readouterr() assert out == "[ ]\n" bar.set(0, 0) print str(bar) out, err = capsys.readouterr() assert out == "[ ]\n"
def init_arduino(): # Arduino process parent_pipe, child_pipe = Pipe() # Starts the process proc = Arduino(child_pipe) proc.start() queue = Queue() # Creates a new thread that will be listening the pipe nbpl = NBPL(parent_pipe, queue) nbpl.setDaemon(True) nbpl.start() return parent_pipe, queue
def test_analogin_get(): a = Arduino("Test Arduino") pin = AnalogIn(a, "Test Pin", "Test api", 0) pin.value = 500 assert pin.get() == 500
def __init__(self): wx.Frame.__init__(self, None, title=self.title, size=(650,570)) if platform.system() == 'Windows': arduino_port = 'COM4' else: arduino_port = '/dev/ttyACM0' # Try Arduino try: self.arduino = Arduino(arduino_port, 115200) except: msg = wx.MessageDialog(self, 'Unable to connect to arduino. Check port or connection.', 'Error', wx.OK | wx.ICON_ERROR) msg.ShowModal() == wx.ID_YES msg.Destroy() self.create_main_panel() self.recording = False self.output_file = '' time.sleep(1) # Timer self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_timer, self.timer) self.rate = 500 self.timer.Start(self.rate)
def OnChangeSerialPort(self, event): # wxGlade: MainWindow.<event_handler> self.windowPrintLn('') self.windowPrintLn("Searching for available serial ports...") #scan for available ports. return a list of tuples (num, name) available = [] for i in range(256): try: s = serial.Serial(i) available.append( (i, s.portstr)) s.close() # explicit close because of delayed GC in java except serial.SerialException: pass self.windowPrintLn("Found the following avilable ports:") for nu, na in available: self.windowPrintLn(na) dlg = wx.SingleChoiceDialog(self, "Select the correct serial port", 'Serial Port Selection', [na for nu, na in available], wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: self.serialPort = dlg.GetStringSelection() self.windowPrintLn('Selected ' + self.serialPort) self.windowPrintLn("Attempting to connect to arduino over " + self.serialPort + ".....") try: self.arduino = Arduino(self.serialPort) self.arduino.output(self.arduinoPinMap) self.arduino.turnOff() self.windowPrintLn(str(self.arduino)) except serial.serialutil.SerialException: self.windowPrintLn("Failed to connect to port " + self.serialPort + "!") self.arduino = None except TimeoutException: self.windowPrintLn("5 second timeout: Failed to communicate with arduino over " + self.serialPort) self.windowPrintLn("Reset arduino and try again, or try different port.") self.arduino = None
def __init__(self, waypointFile=None): """Constructor for the boat object""" self.arduino = Arduino() self.gps = Gps() self.xbee = Xbee() self._waypointN = 0 self._waypointE = 0 self._waypointNumber = 0 self._waypointDist = 0 self._waypointHeading = 0 self._targetHeading = 0 self._targetDistance = 0 self.s = 0 self.c = 0 self.r = 250
def __init__(self, com=None): """ :param com: 设备管理器中的com号。 """ self.board = Arduino(com) self.K1 = 22 self.K2 = 26 self.K3 = 30 self.K4 = 34 self.K_demo = 38 self.keys = [self.K1, self.K2, self.K3, self.K4, self.K_demo] self.board.output(self.keys) for key in self.keys: self.board.setLow(key) self.delay_time = 0.1 self.config = TimeConfig()
def action(self, request,pk): global DEVICES,PATHS,SEMAPHORES actuator = self.get_object() arduino = Arduino(actuator.device.path) if actuator.ejecute: P(SEM) ejecute = False ActuatorArduino.objects.filter(id = actuator.id).update(ejecute = False) arduino.digitalWriteDown(actuator.pin) V(SEM) else: P(SEM) ejecute = True ActuatorArduino.objects.filter(id = actuator.id).update(ejecute = True) arduino.digitalWriteUp(actuator.pin) V(SEM) return Response([{"actuator_name":actuator.name,"ejecute":ejecute}])
def test_digitalout_init(): a = Arduino("Test Arduino") pin = DigitalOut(a, "Test Pin", "Test api", 0) assert pin.name == "Test Pin" assert pin.api == "Test api" assert pin.arduino.name == "Test Arduino"
def test_analogout_init(): a = Arduino("Test Arduino") pin = AnalogOut(a, "Test Pin", "Test api", 0) assert pin.name == "Test Pin" assert pin.api == "Test api" assert pin.arduino.name == "Test Arduino"
def test_set(): a = Arduino("Test Arduino") bar = Bargraph("Test Bargraph", "Test api") bar.attach(a, 0) bar.set(100, 100) assert bar.value == 100 assert bar.max == 100
def __init__(self): wx.Frame.__init__(self, None, title=self.title, size=(650, 600)) # Try Arduino try: self.arduino = Arduino(115200) except: print 'unable to connect to arduino' self.create_main_panel() self.recording = False time.sleep(1) # Timer self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_timer, self.timer) self.rate = 500 self.timer.Start(self.rate)
def verify(): global PATHS, DEVICES, SEM,SEM2,ALL tiempo = 0 while 1: data = {} devices = Device.objects.all() for device in devices: if device.path not in PATHS: PATHS.append(device.path) arduino = Arduino(device.path) DEVICES.append(arduino) else: for dev in DEVICES: if dev.getLocation() == device.path: arduino = dev break test = True while test: #print "while" #print try: data[device.path] = ast.literal_eval(arduino.readAll()) test = False except: pass controllersComplete = ControllerComplete.objects.all() for controller in controllersComplete: value = "" try: value = data[controller.sensor.device.path][controller.sensor.pin] except Exception,e: print e try: flag = eval(str(value)+controller.condition+controller.value) if controller.actuator.ejecute and not flag: P(SEM) arduino = Arduino(controller.actuator.device.path) ActuatorArduino.objects.filter(id = controller.actuator.id).update(ejecute = False) arduino.digitalWriteDown(controller.actuator.pin) V(SEM) elif flag and not controller.actuator.ejecute: P(SEM) arduino = Arduino(controller.actuator.device.path) ActuatorArduino.objects.filter(id = controller.actuator.id).update(ejecute = True) arduino.digitalWriteUp(controller.actuator.pin) V(SEM) except Exception, e: print e
def test_init(): a = Arduino("Test Arduino") mod = Mod(a, "Test Mod", "Test api", 0xA9, 0xAB, 0xAA) assert mod.name == "Test Mod" assert mod.api == "Test api" assert mod.mod.arduino.name == "Test Arduino" assert mod.indicator.arduino.name == "Test Arduino" assert mod.button.arduino.name == "Test Arduino"
def pollj(): ret = [] pin = 1 try: b = Arduino('/dev/ttyACM0') b.output([]) except: print 'couldnt create b' for i in range(10): val = None try: val = b.analogRead(pin) except: print 'couldnt analogread ' + str(i) ret.append(val) print val time.sleep(0.5) return " | ".join(ret)
def test_init(): a = Arduino("Test Arduino") sev = SevenSegment("Test SevenSegment", "Test api") assert sev.name == "Test SevenSegment" assert sev.api == "Test api" assert sev.arduino is None sev.attach(a, 0) assert sev.arduino is not None assert sev.arduino.name == "Test Arduino"
def run(self): # Conectando com Arduino self.__controller = Arduino() if not self.__controller.is_open(): debug('Falha ao conectar com Arduino! Conecte Arduino ao computador.') else: debug('Arduino detectado') webinterface.inject_functions(self.change_key, self.change_and_measure_key, self.blow_drops, self.init_measures, self.save_measures) debug('Interface carregada') ips = webinterface.getServerIPs() print("IP disponível:") for ip in ips: print('\t{}'.format(ip)) webinterface.runserver() self.quit_program()
def test_init(): a = Arduino("Test Arduino") bar = Bargraph("Test Bargraph", "Test api") assert bar.name == "Test Bargraph" assert bar.api == "Test api" assert bar.arduino is None bar.attach(a, 0) assert bar.arduino is not None assert bar.arduino.name == "Test Arduino"
def __init__(self, fname, nrepeat=10, ard_port='/dev/ttyACM0', pump_port='/dev/ttyUSB0'): self.__observers = [] # define an observer self.step = -1 # before execution self.conf_label = 'R' + 'CUCI' * nrepeat print(self.conf_label) self.n_session = 1 + nrepeat * 4 self.sessions = len(self.conf_label) # the number of steps self.__construct__() self.time_flag = pd.Series(np.zeros(self.n_session), index=list(self.conf_label)) ard_reset(ard_port) self.ard = Arduino(ard_port) self.ard.output([pin_LED, pin_Servo]) self.ard.setLow(pin_LED) # Initial self.fname = fname self.pump_init(pump_port)
class StdOutListener(tweepy.StreamListener): a = Arduino(conf.arduini) def on_data(self, data): d = json.loads(data) #print d['user']['screen_name'] + " - " + d['text'] self.a.decode(d['text']) return True def on_error(self, status): print status
def OnChangeSerialPort(self, event): # wxGlade: MainWindow.<event_handler> self.windowPrintLn('') self.windowPrintLn("Searching for available serial ports...") #scan for available ports. return a list of tuples (num, name) available = [] for i in range(256): try: s = serial.Serial(i) available.append((i, s.portstr)) s.close() # explicit close because of delayed GC in java except serial.SerialException: pass self.windowPrintLn("Found the following avilable ports:") for nu, na in available: self.windowPrintLn(na) dlg = wx.SingleChoiceDialog(self, "Select the correct serial port", 'Serial Port Selection', [na for nu, na in available], wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: self.serialPort = dlg.GetStringSelection() self.windowPrintLn('Selected ' + self.serialPort) self.windowPrintLn("Attempting to connect to arduino over " + self.serialPort + ".....") try: self.arduino = Arduino(self.serialPort) self.arduino.output(self.arduinoPinMap) self.arduino.turnOff() self.windowPrintLn(str(self.arduino)) except serial.serialutil.SerialException: self.windowPrintLn("Failed to connect to port " + self.serialPort + "!") self.arduino = None except TimeoutException: self.windowPrintLn( "5 second timeout: Failed to communicate with arduino over " + self.serialPort) self.windowPrintLn( "Reset arduino and try again, or try different port.") self.arduino = None
def __init__(self): self.parser = Parser() self.arduino = Arduino(ArduinoController.BAUD_RATE) self.arduino.register_listener(self) self.msg_handlers = { 'log_format': self.parser.register_log_format, 'sensor_readings': self.notify_listeners } self.log_received_listeners = []
def __init__(self): if pi is True: self.board = Arduino() self.board.connect() self.move = Motors() GPIO.setup(GREEN_LED_GPIO,GPIO.OUT) GPIO.setup(RED_LED_GPIO,GPIO.OUT) GPIO.setup(BUTTON, GPIO.IN, pull_up_down=GPIO.PUD_UP) # load the sample hash with open(rfid_hash) as fh: self.rfid_hash = json.load(fh)
def __init__(self, webserver_queue=None, looprate=0.2): self.arduino = Arduino() self.navigation = Navigation(self.arduino) self.state = State.COLLECT_spin_and_search_cone # Define constants self.looprate = looprate # Variables updated from webserver self.webserver_queue = webserver_queue self.mode = "auto" self.manual_direction = "stop" # Variables used by states self.start_time = None self.ready_to_deliver = False
def __init__(self, fname, nrepeat=10, ard_port="/dev/ttyACM0", pump_port="/dev/ttyUSB0"): self.__observers = [] # define an observer self.step = -1 # before execution self.conf_label = "R" + "CUCI" * nrepeat print(self.conf_label) self.n_session = 1 + nrepeat * 4 self.sessions = len(self.conf_label) # the number of steps self.__construct__() self.time_flag = pd.Series(np.zeros(self.n_session), index=list(self.conf_label)) ard_reset(ard_port) self.ard = Arduino(ard_port) self.ard.output([pin_LED, pin_Servo]) self.ard.setLow(pin_LED) # Initial self.fname = fname self.pump_init(pump_port)
def __init__(self, waypointFile=None): """Constructor for the boat object""" self.arduino = Arduino() self.gps = Gps() self.xbee = Xbee() self._waypointN = 0 self._waypointE = 0 self._waypointNumber = 0 self._waypointDist = 0 self._waypointHeading = 0 self._targetHeading = 0 self._targetDistance = 0 self.s = 0 self.c = 0 self.r = 250
class ArduinoController: BAUD_RATE = 115200 def __init__(self): self.parser = Parser() self.arduino = Arduino(ArduinoController.BAUD_RATE) self.arduino.register_listener(self) self.msg_handlers = { 'log_format': self.parser.register_log_format, 'sensor_readings': self.notify_listeners } self.log_received_listeners = [] def register_listener(self, listener): """Register a listener to the log received event.""" # Make sure the listener has the on_log_received method defined. m = getattr(listener, 'on_log_received', None) if callable(m): self.log_received_listeners.append(listener) def on_msg_received(self, msg): """Attempt to parse & handle the received serial message.""" try: parsed_msg = self.parser.parse_msg(msg) handler = self.msg_handlers[parsed_msg['header']] handler(parsed_msg['data']) except KeyError: raise BadSerialMessageError( 'Unknown command: {}'.format(parsed_msg['header'])) except BadSerialMessageError as e: print 'Ignoring bad msg: {}'.format(e) def start(self): self.arduino.start() # For now simply delegate to the Arduino class. def stop(self): self.arduino.stop() # For now simply delegate to the Arduino class. def notify_listeners(self, data): """Notify all listeners of the log received event.""" try: readings = self.parser.parse_sensor_readings(data) for listener in self.log_received_listeners: listener.on_log_received(readings) except BadSerialMessageError as e: print "Ignoring bad log: {}".format(e)
def main(): network_clients_sh = path.join(path.dirname(__file__), 'networkClientsInNetwork.sh') config_path = path.join(path.dirname(__file__), 'config.json') print config_path print network_clients_sh with open(config_path) as config_fh: config = json.load(config_fh) args = get_args() is_live_run = args["productive_system"] base_url = config["URL"] security_token = config["KEY"] port = config["TTY"] poster = Poster() if is_live_run: cprint("Live run!", color="magenta") delay = 300 else: cprint("Test run!", color="green") delay = 3 arduino = Arduino(port=port) arduino.start() time.sleep(15) network_clients_count = None while True: is_door_open = arduino.get_is_door_open() temperature = arduino.get_temperature() recieved = arduino.get_last_recieved() nmap = subprocess.Popen(network_clients_sh, stdout = subprocess.PIPE, stderr = subprocess.PIPE) network_clients_count = int(nmap.stdout.readlines()[0]) poster.post_door_state(base_url, is_door_open, security_token) poster.post_temperature(base_url, str(temperature), security_token) poster.post_clients(base_url, str(network_clients_count), security_token) cprint(str(datetime.datetime.now().strftime('%G-%b-%d-%H:%M:%S')), color="red") cprint("Nmap " + str(network_clients_count), color="blue") cprint("Tür offen: " + str(is_door_open), color="yellow") cprint("Temperatur: " + str(temperature), color="cyan") print recieved print ("\n") time.sleep(delay)
def __init__(self): wx.Frame.__init__(self, None, title=self.title, size=(650,570)) # Try Arduino try: self.arduino = Arduino(arduino_port, 115200) except: print 'unable to connect to arduino' self.create_main_panel() self.recording = False time.sleep(1) # Timer self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_timer, self.timer) self.rate = 500 self.timer.Start(self.rate)
def __init__(self, frame): ''' initiate the window''' self.uno = Arduino() self.threshold = StringVar() self.threshold.set("90") self.frame = frame self.skytmphist = [] self.ambtmphist = [] self.timearray = [] self.skytemp = None self.ambtemp = None self.fig = None self.canvas = None self.ax1 = None self.csmode = StringVar() self.socket = None self.mute = False self.mutebutton = None self.com = None self.stopbutton = None self.stop = True rframe = ttk.Frame(self.frame) rframe.grid(sticky=(N, S, E, W)) plot = ttk.Frame(rframe) plot.grid(column=0, row=0, sticky=(N, E, W)) plot.columnconfigure(1, weight=3) self.__plot(plot) info = ttk.Frame(rframe) info.grid(column=1, row=0, sticky=(N, E, W)) info.rowconfigure(0, weight=3) self.__info(info) self.updatetmp() self.network()
def __init__(self, video_src, port, baud): self.cam = cv2.VideoCapture(video_src) ret, self.frame = self.cam.read() cv2.namedWindow('Arduino Tracker') cv2.setMouseCallback('Arduino Tracker', self.mouse) self.selection = None self.drag_start = None self.tracking_state = 0 self.dest = None self.state = 'Servo: Pivot' self.pivot_dir = 'l' # default pivot direction left self.move_dir = 'f' # default move direction forward if not port: port = '/dev/tty.usbmodem1A1341' if not baud: baud = 115200 self.robot = Arduino(port, baud) self.prev_angle = 0 self.prev_dist = 0 self.counter = 0
def __init__(self,vDev): # Set arduino pins mode self.redPin = 5 self.greenPin = 6 self.bluePin = 9 self.redVal = 0 self.greenVal = 0 self.blueVal = 0 self.prevR = 0 self.prevB = 0 self.prevG = 0 self.wait = 0.05 self.hold = 0 self.repeat = 0 self.j = 0 self.myArduino = Arduino(vDev) self.myArduino.output([self.redPin,self.greenPin,self.bluePin]) print self.myArduino
import pygame import sys from multiprocessing import freeze_support from arduino import Arduino if __name__ == "__main__": freeze_support() device = Arduino() pygame.init() pygame.display.set_mode((100, 100)) prev = pygame.time.get_ticks() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: device.close() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_f: device.forwardMotor() elif event.key == pygame.K_b: device.backwardMotor() if event.type == pygame.KEYUP: if event.key == pygame.K_f or event.key == pygame.K_b: device.stopMotor() cur = pygame.time.get_ticks() if cur - prev < 3000: device.forwardMotor() else: device.stopMotor() # if cur - prev > 1000:
def __init__(self): self.board = Arduino() self.board.connect()
manualMode=False #parametro per abilitare modalita maunale found=False #parametro che indica se ho trovato la pallina ball_state= 0 #parametro per contare il numero di framein cui vedo la pallina roaming_timer = 0 #conta il tempo in cui non vedo palline spiral = 0 #moltiplicatore per aumentare raggio spirale target = IMAGE_WIDTH/2 #voglio che l'oggetto stia al centro dello schermo delta_t = 200 #intervallo di tempo prima di passare al frame successivo enableMotor = 0 #Abilita/Disabilita i motori roaming_timer = 0 #conta il tempo in cui non vedo palline manualDir=None #direzione in modalita manuale manualSpeed=0 #velocita in modalita manuale maxRadius=0 wm=None manualSpeed2=0 motor=Arduino() #variabili per la gestione del socket client_socket = None server_socket = None def initSocketThread(): global client_socket global server_socket TCP_IP = '' TCP_PORT = 32245 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) server_socket.bind((TCP_IP,TCP_PORT)) server_socket.listen(5)
class RGBLamp: def __init__(self,vDev): # Set arduino pins mode self.redPin = 5 self.greenPin = 6 self.bluePin = 9 self.redVal = 0 self.greenVal = 0 self.blueVal = 0 self.prevR = 0 self.prevB = 0 self.prevG = 0 self.wait = 0.05 self.hold = 0 self.repeat = 0 self.j = 0 self.myArduino = Arduino(vDev) self.myArduino.output([self.redPin,self.greenPin,self.bluePin]) print self.myArduino def calculateStep(self,prevValue, endValue): step = endValue - prevValue if (step != 0): step = 1020 / step return step def calculateVal(self,step,val,i): if ((step != 0) and (i % step == 0)): if (step >= 0): val += 1 elif (step < 0): val -= 1 # PWM safe range: (0,255) if (val > 255): val = 255 if (val < 0): val = 0 return val def crossFade(self,(r,g,b)): stepR = self.calculateStep(self.prevR, r) stepG = self.calculateStep(self.prevG, g) stepB = self.calculateStep(self.prevB, b) for i in range(1020): self.redVal = self.calculateVal(stepR, self.redVal, i) self.greenVal = self.calculateVal(stepG, self.greenVal, i) self.blueVal = self.calculateVal(stepB, self.blueVal, i) self.myArduino.analogWrite(self.redPin, self.redVal) self.myArduino.analogWrite(self.greenPin, self.greenVal) self.myArduino.analogWrite(self.bluePin, self.blueVal) time.sleep(self.wait) # update values for next iteration self.prevR = self.redVal self.prevG = self.greenVal self.prevB = self.blueVal time.sleep(self.hold)
class CloudSensor(object): ''' Cloud sensor notebook object''' def __init__(self, frame): ''' initiate the window''' self.uno = Arduino() self.threshold = StringVar() self.threshold.set("90") self.frame = frame self.skytmphist = [] self.ambtmphist = [] self.timearray = [] self.skytemp = None self.ambtemp = None self.fig = None self.canvas = None self.ax1 = None self.csmode = StringVar() self.socket = None self.mute = False self.mutebutton = None self.com = None self.stopbutton = None self.stop = True rframe = ttk.Frame(self.frame) rframe.grid(sticky=(N, S, E, W)) plot = ttk.Frame(rframe) plot.grid(column=0, row=0, sticky=(N, E, W)) plot.columnconfigure(1, weight=3) self.__plot(plot) info = ttk.Frame(rframe) info.grid(column=1, row=0, sticky=(N, E, W)) info.rowconfigure(0, weight=3) self.__info(info) self.updatetmp() self.network() def __plot(self, frame): ''' Draw the plot of temperatures. ''' sframe = ttk.Frame(frame) sframe.grid() self.fig = Figure(figsize=(12, 6), dpi=50) self.fig.autofmt_xdate() # create plots self.ax1 = self.fig.add_subplot(111) self.ax1.plot(self.timearray, self.skytmphist) self.ax1.plot(self.timearray, self.ambtmphist) self.canvas = FigureCanvasTkAgg(self.fig, master=sframe) self.canvas.show() c = self.canvas.get_tk_widget() c.grid(row=0, column=0) def __updateplot(self): ''' Update the plot with the latest values ''' self.ax1.clear() self.ax1.plot(self.timearray, self.skytmphist) self.ax1.plot(self.timearray, self.ambtmphist) self.fig.autofmt_xdate() ax = self.canvas.figure.axes[0] maxt = max([float(a) for a in self.skytmphist + self.ambtmphist]) mint = min([float(a) for a in self.skytmphist + self.ambtmphist]) ax.set_ylim(int(mint) - 2, int(maxt) + 2) self.canvas.draw() c = self.canvas.get_tk_widget() c.grid(row=0, column=0) def __info(self, frame): ''' Show the info panel. ''' skytemplabel = ttk.Label(frame, text="Sky Temperature (C)") skytemplabel.grid(column=0, row=0, padx=5, sticky=(N, S, E, W)) self.skytemp = ttk.Label(frame, text="-10") self.skytemp.grid(column=1, row=0, padx=5, sticky=(N, S, E, W)) ambtemplabel = ttk.Label(frame, text="Ambient Temperature (C)") ambtemplabel.grid(column=0, row=1, padx=5, sticky=(N, S, E, W)) self.ambtemp = ttk.Label(frame, text="0") self.ambtemp.grid(column=1, row=1, padx=5, sticky=(N, S, E, W)) thresholdlabel = ttk.Label(frame, text="Threshold Temperature") thresholdlabel.grid(column=0, row=2, padx=5, sticky=(N, S, E, W)) threshold = ttk.Entry(frame, textvariable=self.threshold) threshold.grid(column=1, row=2, padx=5, sticky=(N, S, E, W)) comlabel = ttk.Label(frame, text="Select Client/Server Mode: ") comlabel.grid(column=0, row=3, padx=5, sticky=(N, S, E, W)) self.com = ttk.Combobox(frame, textvariable=self.csmode) self.com['values'] = ('Off', 'Client', 'Server') self.com.current(0) self.com.grid(column=1, row=3, padx=5, sticky=(N, S, E, W)) self.mutebutton = ttk.Button(frame, text="Mute", command=self.__mutebutton) self.mutebutton.grid(column=0, row=4, padx=5, sticky=(N, S, E, W)) self.stopbutton = ttk.Button(frame, text="Start", command=self.__stopbutton) self.stopbutton.grid(column=1, row=4, padx=5, sticky=(N, S, E, W)) resetbutton = ttk.Button(frame, text="Reset", command=self.__reset) resetbutton.grid(column=0, row=5, padx=5, sticky=(N, S, E, W)) def __reset(self): ''' Purge the existing cloud data. ''' self.skytmphist = [] self.ambtmphist = [] self.timearray = [] def __stopbutton(self): ''' Private function to toggle stop and start and change button text. ''' if self.stop is False: self.stop = True self.stopbutton.config(text='Start') else: self.stop = False self.stopbutton.config(text='Stop') def __mutebutton(self): ''' Private function to toggle mute and change button text ''' if self.mute is False: self.mute = True self.mutebutton.config(text='Unmute') else: self.mute = False self.mutebutton.config(text='Mute') def updatetmp(self): ''' Update the temperatures and gui. Also check if we need to raise alarm. ''' if self.stop: self.frame.after(polldelay, self.updatetmp) return if 'Client' in self.csmode.get(): try: if self.socket is not None: self.socket.close() self.socket = None self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((socket.gethostname(), 8001)) mesg = self.socket.recv(32).strip('\0') self.socket.close() except Exception as msg: log.error("client exception: " + str(msg)) if mesg is None: log.warning("Didn't get a response from the server...") self.frame.after(polldelay, self.updatetmp) return else: [a, b, c] = mesg.split(';') self.timearray.append(datetime.datetime.strptime(a.split('.')[0], '%Y-%m-%d %H:%M:%S')) self.skytmphist.append(int(b)) self.ambtmphist.append(int(c)) else: log.debug("Arduino is connected? " + str(self.uno.isconnected())) if self.uno.isconnected() == True: # Add workaround for 1037.55 newtmp, anewtmp = self.uno.get_temperatures() if newtmp == '1037.55': try: self.skytmphist.append(self.skytmphist[-1]) except IndexError: self.skytmphist.append('0') else: self.skytmphist.append(newtmp) if anewtmp == '1037.55': try: self.ambtmphist.append(self.ambtmphist[-1]) except IndexError: self.ambtmphist.append('0') else: self.ambtmphist.append(anewtmp) templog.debug("sky=" + str(newtmp) + ":ambient=" + str(anewtmp)) else: newtmp = randint(0, 100) anewtmp = randint(0, 100) templog.debug("sky=" + str(newtmp) + ":ambient=" + str(anewtmp)) self.skytmphist.append(newtmp) self.ambtmphist.append(anewtmp) tnow = datetime.datetime.now() self.timearray.append(tnow) self.skytemp.config(text=str(self.skytmphist[-1])) self.ambtemp.config(text=str(self.ambtmphist[-1])) self.__updateplot() if (float(self.skytmphist[-1]) > float((self.threshold.get()))) and not self.mute: log.debug("BEEEEEEEPPPPPP") if sys.platform == 'darwin': audio_file = "Siren_Noise.wav" subprocess.Popen(["afplay " + audio_file], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True) self.frame.after(polldelay, self.updatetmp) def network(self): ''' Either Run a tcp server that a client can connect to or run a client to connect to a server or do nothing. ''' mode = self.csmode.get() # print mode if 'Off' in mode: self.frame.after(offdelay, self.network) return elif 'Server' in mode: if self.socket is None: self.socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((socket.gethostname(), 8001)) self.socket.setblocking(0) self.socket.listen(5) try: cstring = str(self.timearray[-1]) + ";" + \ str(self.skytmphist[-1]) + ";" + \ str(self.ambtmphist[-1]) + "\0" a, b, c = select.select([self.socket], [], [], 0) for s in a: client_socket, address = self.socket.accept() client_socket.send(cstring) except Exception as msg: log.error("exception1: " + str(msg)) self.frame.after(serverdelay, self.network)
class Assay: # Initialize the pumps def __init__(self, fname, nrepeat=10, ard_port="/dev/ttyACM0", pump_port="/dev/ttyUSB0"): self.__observers = [] # define an observer self.step = -1 # before execution self.conf_label = "R" + "CUCI" * nrepeat print(self.conf_label) self.n_session = 1 + nrepeat * 4 self.sessions = len(self.conf_label) # the number of steps self.__construct__() self.time_flag = pd.Series(np.zeros(self.n_session), index=list(self.conf_label)) ard_reset(ard_port) self.ard = Arduino(ard_port) self.ard.output([pin_LED, pin_Servo]) self.ard.setLow(pin_LED) # Initial self.fname = fname self.pump_init(pump_port) def blink_start(self, nblink=5): # give a blinking start, the LED blinks at 1 Hz for ii in range(nblink): self.ard.setHigh(pin_LED) time.sleep(0.50) self.ard.setLow(pin_LED) time.sleep(0.50) print(ii + 1) millis = int(round(time.time() * 1000)) self.onset = millis def pump_init(self, pump_port): self.pser = serial.Serial(pump_port, 19200, timeout=0.1) print("connected to", self.pser.name) pumps = new_era.find_pumps(self.pser) self.pump = pumps[0] self.infuse = False new_era.set_diameter(self.pser, self.pump, dia_1ml) new_era.set_direct(self.pser, self.pump, 1) new_era.set_rate(self.pser, self.pump, flowrate) def register_observer(self, observer): self.__observers.append(observer) def notify_observers(self, *args, **kwargs): for observer in self.__observers: observer.notify(self, *args, **kwargs) def __construct__(self): # construct the configuration array self.CS_config = np.zeros([self.n_session, 4]) ii = 0 for ch in self.conf_label: if ch == "R": self.CS_config[ii] = CONFIG_REST elif ch == "C": self.CS_config[ii] = CONFIG_CS elif ch == "U": self.CS_config[ii] = CONFIG_US else: self.CS_config[ii] = CONFIG_INTER ii += 1 # then, we need to update duration of intersessions inter_pos = self.CS_config[:, 0] < 0 # take out the positions of intersessions, a boolean array inter_dur = self.CS_config[inter_pos, 0] self.CS_config[inter_pos, 0] = np.random.randint(40, 70, size=len(inter_dur)) print(self.CS_config) self.duration = self.CS_config[:, 0].sum() / 60.0 print("Total experimental time: %4.1f min" % self.duration) def blink(self, duration, freq=2): # blink the LED # duration: the duration of blinking nblink = int(duration * freq) thp = 1 / (freq * 2.0) # half-period for ii in range(nblink): self.ard.setHigh(pin_LED) time.sleep(thp) self.ard.setLow(pin_LED) time.sleep(thp) def run_step(self, sblink=False): millis = int(round(time.time() * 1000)) self.step += 1 self.time_flag[self.step] = millis self.notify_observers(self.step) config_list = self.CS_config[self.step] print(config_list[0]) # take the row # turn on or off all the stimuli # turn on or off the delivery if config_list[2] == 0: if self.infuse == True: new_era.stop_pump(self.pser, self.pump) self.infuse = False elif config_list[2] == 1: if self.infuse == False: new_era.set_rate(self.pser, self.pump, flowrate) new_era.run_all(self.pser) self.infuse = True if config_list[1] == 0: self.ard.setLow(pin_LED) # keep the LED off time.sleep(config_list[0]) elif config_list[1] == 1: if sblink: self.blink(config_list[0]) else: self.ard.setHigh(pin_LED) time.sleep(config_list[0]) # insert or retract the feeding tube # if config_list[3] == 0: # self.ard.analogWrite(pin_Servo, 0) # elif config_list[3] == 0: # self.ard.analogWrite(pin_Servo, 80) # time.sleep(config_list[0]) # self.terminate_step() def terminate_step(self): # terminate a step self.ard.setLow(pin_LED) self.ard.analogWrite(pin_Servo, 0) new_era.stop_pump(self.pser, self.pump) def run_through(self, sblink=False): self.blink_start() self.step = -1 ii = 0 for ii in range(self.n_session): self.run_step(sblink) print("The" + str(ii) + "th session.") # def shuffle_steps(self): # # shuffle the steps of # CS_total = np.inner(self.CS_config[:,0], self.CS_config[:,1]) # inner product of the first two columns, total duration of CS # US_total = np.inner(self.CS_config[:,0], self.CS_config[:,2]) # total duration of US # time_total = self.CS_config[:,0].sum() # The total amount of time should be equal # # # use 10 seconds as a unit of the # NC_chunk = np.round(CS_total/10.).astype('int') # NU_chunk = np.round(US_total/10.).astype('int') # Total_chunk = np.round(time_total/10.).astype('int') # # shuff_LED = random_split(NC_chunk) # def close(self): # destruct the class self.ard.setLow(pin_LED) self.ard.close() np.save("../Data/" + self.fname, self.time_flag) pd.Series.to_csv(self.time_flag, "../Data/" + self.fname + ".csv") print("Arduino port closed. ")
from bottle import route, run, template, get, view from Queue import Queue import threading from arduino import Arduino import time b = Arduino("/dev/tty.usbmodemfd121") b.output([]) input_pin = 1 max_threshold = 0 min_threshold = 0 for y in range(100): x = int(b.analogRead(input_pin)) print x max_threshold = max([max_threshold, x]) min_threshold = min([min_threshold, x]) print "+++++++++++++++++++++++" print max_threshold print min_threshold print "+++++++++++++++++++++++" @route("/") @view("main_template") def index(name="Michel"): return dict()
#the blink program #import the lib from arduino import Arduino import time #specify the port as an argument my_board = Arduino('/dev/ttyUSB0') #declare output pins as a list/tuple my_board.output([11,12,13]) #perform operations i=0 while(i<10): my_board.setHigh(13) time.sleep(1) my_board.setLow(13) i+=1