コード例 #1
0
    def __init__(self, port="ttyACM0", auto_calibrate=False):
        self.uno = arduino.Arduino(port, baud=9600)
        time.sleep(2)  # Wait for serial to connect
        self.__valve(False)

        self.horizontal_motor = Motor(self.uno,
                                      dir_pin=3,
                                      step_pin=2,
                                      trigger_pos=6,
                                      trigger_neg=UNCONNECTED_3,
                                      home_dir=1,
                                      home_offset=500 * 16,
                                      ms1=LEFT_RIGHT_MS1,
                                      ms2=LEFT_RIGHT_MS2,
                                      ms3=LEFT_RIGHT_MS3)
        self.vertical_motor = Motor(self.uno,
                                    dir_pin=4,
                                    step_pin=5,
                                    trigger_pos=UNCONNECTED_3,
                                    trigger_neg=7,
                                    home_dir=0,
                                    home_offset=200 * 16,
                                    ms1=UP_DOWN_MS1,
                                    ms2=UP_DOWN_MS2,
                                    ms3=UP_DOWN_MS3)
        answer = None
        while answer not in ('y', 'n') and auto_calibrate:
            answer = raw_input("Calibrate (y/n)? ").lower()
        if answer == 'y':
            self.calibrate()
コード例 #2
0
 def run(self):
     """
     Run Training
     :return:
     """
     with arduino.Arduino() as ard:
         pass
コード例 #3
0
    def __init__(self, port="ttyACM0"):
        self.uno = arduino.Arduino(port, baud=9600)
        time.sleep(2)
        self.uno.Blink(13, 0.3)

        self.horizontal_motor = Motor(self.uno,
                                      dir_pin=3,
                                      step_pin=2,
                                      trigger_pos=6,
                                      trigger_neg=UNCONNECTED_3,
                                      home_dir=1,
                                      home_offset=500,
                                      ms1=LEFT_RIGHT_MS1,
                                      ms2=LEFT_RIGHT_MS2,
                                      ms3=LEFT_RIGHT_MS3)
        self.vertical_motor = Motor(self.uno,
                                    dir_pin=4,
                                    step_pin=5,
                                    trigger_pos=UNCONNECTED_3,
                                    trigger_neg=7,
                                    home_dir=0,
                                    home_offset=200,
                                    ms1=UP_DOWN_MS1,
                                    ms2=UP_DOWN_MS2,
                                    ms3=UP_DOWN_MS3)
        self.calibrate()
コード例 #4
0
    def set_config(self, param_dict):
        '''this method sets the config, and is called in the brain
        this is _not_ done in the constructor, since the behaviors construct this
        class as well, and they dont have the param_dict'''

        global USE_MARYTTS
        mary = param_dict.get_option("body", "marytts", None)
        if mary is not None:
            mary = eval(mary)
            self.use_marytts = USE_MARYTTS = mary

        self.__nao_list = []  #list of the nao objects
        self.__pioneer_list = []  #list of the pioneer objects
        self.__alice_list = []  #list of the alice objects
        self.__movebase = None  #the movebase objects
        self.__param_dict = param_dict

        self.arduino = None
        if self.__param_dict.get_option('body', 'arduino') == "True":
            self.arduino = arduino.Arduino()

        self.__create_robots()

        self.speak_cnt = 0
        self.use_svox_speach = True
        self.speech_commands = []
        self.prev_speech_command = {}
        self.remove_all_prev_speech_files()
コード例 #5
0
    def __init__(self, panelFile=None):
        # instantiate serial
        self.arduino = None
        try:
            self.arduino = arduino.Arduino()
        except Exception as e:
            print e.message

        if panelFile is None:
            # read from serial the panel id?
            pass
        else:
            self.panelFile = panelFile

        # build panel
        self.panels = dict()
        self.panels[1] = panel.Panel(self.panelFile,
                                     panelId=1)  # the key is = to panelId
        self.currentPanelId = 1

        # here the messages from Control will arrive
        # onOffQueue will contain string messages with 'on' and 'off'
        # panelQueue will contain panel that will be drawn
        # optionQueue will contain option that was selected
        self.onOffQueue = Queue.Queue()
        self.panelQueue = Queue.Queue()
        queues = (self.onOffQueue, self.panelQueue)

        # create GUI
        self.synchGUI = threading.Event()
        self.gui = GUI.GUI(queues, self.synchGUI)

        self.state = 'off'
コード例 #6
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_LinearTrackUI()
        self.ui.setupUi(self)

        # Trigger checkbox
        QtCore.QObject.connect(self.ui.cb_trigger, QtCore.SIGNAL("clicked()"),
                               self.toggleTrigger)

        # Status bar
        self.statusBar().showMessage("Ready")

        # Actions
        exit = QtGui.QAction(QtGui.QIcon('icons/exit.png'), 'Exit', self)
        exit.setShortcut('Ctrl+Q')
        exit.setStatusTip('Exit Spotter')
        self.connect(exit, QtCore.SIGNAL('triggered()'),
                     QtCore.SLOT('close()'))

        self.arduino = arduino.Arduino('COM3')

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.checkPhysState)
        self.timer.start(5)

        self.t_elapsed = QtCore.QTime()
        self.t_elapsed.start()
コード例 #7
0
 def serialInit(self, port='ACM0', baud=9600):
     self.ard = arduino.Arduino(port, baud)
     time.sleep(2)
     data = self.ard.recv()
     while data != None and data != '' and data != b'':
         time.sleep(0.05)
         #ard.send((str(i)).encode('utf-8'))
         #print(ard.recv())
         print(data)
         data = self.ard.recv()
コード例 #8
0
    def __init__(self, device_list):
        self.arduino_handlers = {}
        self.cv = threading.Condition()

        print 'Device list: %s' % device_list
        for path in device_list:
            try:
                device = self.ArduinoHandler(arduino.Arduino(path), self.cv)
            except Exception as e:
                print('Error while initializing device %s: %s' % (path, e))
                continue
            id = device.get_id()
            self.arduino_handlers[id] = device
            print 'Got device with ID=%s' % id
コード例 #9
0
def start_scanner():
    con_list = {}

    while True:
        # Scan all ports
        ports = get_serial_ports()

        # If a device connected
        if len(ports) > 0:

            # For-Loop in the scanned ports
            for current in ports:

                # New Arduino is connected
                # Register to con_list
                # Returns False because we don't connect yet
                if current not in con_list:
                    con_list[current] = False

                # Arduino is connected
                if current in con_list and con_list[current] == False:
                    con = arduino.Arduino(current, 9600)
                    if con.open(max_attempt=5):
                        con_list[current] = True
                        to_node("status", {
                            "name": "connect",
                            "data": "connected"
                        })

                        thread = threading.Thread(target=con.start_serial())
                        thread.start()

                # Arduino in con_list, nothing to do
                elif current in con_list and con_list[current] == True:
                    continue

        # Any Arduino connected, set them all False
        # We are not goint to clean the list because we will check if it is connected again
        elif len(con_list) > 0:
            for con in con_list:
                if con_list[con] == True:
                    con_list[con] = False
                    to_node("status", {
                        "name": "connect",
                        "data": "disconnected"
                    })

        time.sleep(1)
コード例 #10
0
ファイル: io_bank.py プロジェクト: OpenSourceIronman/nebree8
 def __init__(self, update_shift_reg=False, update_arduino=True):
   self.last_time = time.time()
   gpio.setmode(gpio.BCM)
   gpio.setwarnings(False)
   if update_arduino:
     self.arduino = arduino.Arduino()
   else:
     self.arduino = None
   for output in Outputs:
     if output.value < _SHIFT_REG_ADDRESS_OFFSET:
       gpio.setup(output.value, gpio.OUT)
     self.WriteOutput(output, 0)
   for pin in Inputs:
     gpio.setup(pin.value, gpio.IN, pull_up_down=gpio.PUD_UP)
   if update_shift_reg:
     self.current_shifted_byte = [0] * 24
     self.current_shifted_byte[Outputs.COMPRESSOR.value - _SHIFT_REG_ADDRESS_OFFSET] = 1
     self.signal_refresh = Queue.Queue(1)
     self.thread = threading.Thread(target=self.__RefreshShiftOutputs)
     self.thread.daemon = True
     self.thread.start()
   self.WriteOutput(Outputs.COMPRESSOR, 1)
コード例 #11
0
    def __init__(self, tof_lib):
        """ Constructor """

        # Create a list of servo's
        self.servos = dict()
        # Add Motor Servo's. NOTE: Left motor esc is reversed.
        self.servos[ServoEnum.LEFT_MOTOR_ESC] = [
            servo_control.Servo_Controller(min=800,
                                           mid=1300,
                                           max=1800,
                                           bReverse=True), LEFT_MOTOR_ESC_PIN,
            'Left Motor'
        ]
        self.servos[ServoEnum.RIGHT_MOTOR_ESC] = [
            servo_control.Servo_Controller(min=800,
                                           mid=1300,
                                           max=1800,
                                           bReverse=False),
            RIGHT_MOTOR_ESC_PIN, 'Right Motor'
        ]

        # Add Auxilary servo's. NOTE: Aux esc's are not reversed.
        self.servos[ServoEnum.LEFT_AUX_ESC] = [
            servo_control.Servo_Controller(min=800,
                                           mid=1300,
                                           max=1800,
                                           bReverse=False), LEFT_AUX_ESC_PIN,
            'Left Aux'
        ]
        self.servos[ServoEnum.RIGHT_AUX_ESC] = [
            servo_control.Servo_Controller(min=800,
                                           mid=1300,
                                           max=1800,
                                           bReverse=False), RIGHT_AUX_ESC_PIN,
            'Right Aux'
        ]

        # Add Auxilary servo's. NOTE: Ball Flinger esc's are not reversed.
        self.servos[ServoEnum.LEFT_FLINGER_ESC] = [
            servo_control.Servo_Controller(min=800,
                                           mid=1300,
                                           max=1800,
                                           bReverse=False),
            LEFT_FLINGER_ESC_PIN, 'Left Flinger ESC'
        ]
        self.servos[ServoEnum.RIGHT_FLINGER_ESC] = [
            servo_control.Servo_Controller(min=800,
                                           mid=1300,
                                           max=1800,
                                           bReverse=False),
            RIGHT_FLINGER_ESC_PIN, 'Right Flinger ESC'
        ]

        # Add Auxilary servo's. NOTE: Ball Flinger esc's are not reversed.
        self.servos[ServoEnum.LEFT_FLINGER_SERVO] = [
            servo_control.Servo_Controller(min=800,
                                           mid=1300,
                                           max=1800,
                                           bReverse=False),
            LEFT_FLINGER_SERVO_PIN, 'Left Flinger Servo'
        ]
        self.servos[ServoEnum.RIGHT_FLINGER_SERVO] = [
            servo_control.Servo_Controller(min=800,
                                           mid=1300,
                                           max=1800,
                                           bReverse=False),
            RIGHT_FLINGER_SERVO_PIN, 'Right Flinger Servo'
        ]

        # Add Auxilary servo's. NOTE: Aux 4 servo is not reversed.
        self.servos[ServoEnum.WINCH_SERVO] = [
            servo_control.Servo_Controller(min=800,
                                           mid=1300,
                                           max=1800,
                                           bReverse=False), WINCH_SERVO_PIN,
            'Winch'
        ]

        # Always set these to None for initialisation
        self.PWMservo = None
        self.arduino = None

        self.arduino_mode = 0  # Not using Arduino
        self.lidars = []

        if (self.arduino_mode == 1):
            self.arduino = arduino.Arduino()
        else:
            self.arduino = None
            self.PWMservo = PWM.Servo(pulse_incr_us=1)

        # I2C lidar sensors should be enabled
        # in both Arduino mode or direct pi mode.
        for pin in range(0, 3):
            i2c_lidar.xshut([LIDAR_PINS[pin]])
            self.lidars.append(
                i2c_lidar.create(LIDAR_PINS[pin], tof_lib, 0x2a + pin))
コード例 #12
0
#!/usr/bin/env python
import time

import arduino

uno = arduino.Arduino("ttyACM", baud=9600)


UNCONNECTED_1 = 8
UNCONNECTED_2 = 9
UNCONNECTED_3 = 12
ICE_STEPS = 6

class Motor(object):
  def __init__(self, uno, dir_pin, step_pin, trigger_neg, trigger_pos, home_dir, home_offset):
    self.uno = uno
    self.dir_pin = dir_pin
    self.step_pin = step_pin
    self.trigger_neg = trigger_neg
    self.trigger_pos = trigger_pos
    self.home_dir = home_dir
    self.home_offset = home_offset

  def Move(self, forward, steps):
    self.uno.Move(stepper_dir_pin=self.dir_pin,
                  stepper_pulse_pin=self.step_pin,
                  negative_trigger_pin=self.trigger_neg,
                  positive_trigger_pin=self.trigger_pos,
                  done_pin=UNCONNECTED_1,
                  forward=forward,
                  steps=steps,
コード例 #13
0
ファイル: core.py プロジェクト: robberwick/piwars3
    def __init__(self, tof_lib):
        """ Constructor """

        # Minimum and maximum theoretical pulse widths. Ignore reversing here
        # ESC "DB1" midpoint is about 1440
        # ESC "DB2" midpoint is 1500
        self.LEFT_MIN = 800
        self.LEFT_MID = 1300
        self.LEFT_MAX = 1800

        self.RIGHT_MIN = 800
        self.RIGHT_MID = 1300
        self.RIGHT_MAX = 1800

        self.LEFT_AUX_1_MIN = 800
        self.LEFT_AUX_1_MID = 1300
        self.LEFT_AUX_1_MAX = 1800

        self.RIGHT_AUX_1_MIN = 800
        self.RIGHT_AUX_1_MID = 1300
        self.RIGHT_AUX_1_MAX = 1800

        self.left_servo = servo_control.Servo_Controller(
            self.LEFT_MIN,
            self.LEFT_MID,
            self.LEFT_MAX, True)
        self.right_servo = servo_control.Servo_Controller(
            self.RIGHT_MIN,
            self.RIGHT_MID,
            self.RIGHT_MAX, False)

        self.left_aux_1_servo = servo_control.Servo_Controller(
            self.LEFT_AUX_1_MIN,
            self.LEFT_AUX_1_MID,
            self.LEFT_AUX_1_MAX, False)
        self.right_aux_1_servo = servo_control.Servo_Controller(
            self.RIGHT_AUX_1_MIN,
            self.RIGHT_AUX_1_MID,
            self.RIGHT_AUX_1_MAX, False)

        self.left_channel = 1
        self.right_channel = 2

        # Proximity sensor: roughly cm from closest measurable point
        # self.tof_left = sensor.Sensor(0, 450, 20, 0)
        # self.PWMservo = PWM.Servo(pulse_incr_us=1)

        # Always set these to None for initialisation
        self.PWMservo = None
        self.arduino = None

        self.arduino_mode = 0  # Not using Arduino
        self.lidars = []

        if (self.arduino_mode == 1):
            self.arduino = arduino.Arduino()
        else:
            self.arduino = None
            self.PWMservo = PWM.Servo(pulse_incr_us=1)
            for pin in range(0, 3):
                i2c_lidar.xshut([LIDAR_PINS[pin]])
                self.lidars.append(i2c_lidar.create(LIDAR_PINS[pin], tof_lib, 0x2a + pin))
コード例 #14
0
ファイル: motor.py プロジェクト: gkanwar/maslab-staff-2013
import sys
sys.path.append("../..")
import time

import arduino

ard = arduino.Arduino()
m0 = arduino.Motor(ard, 0, 2, 3)
ard.run()  # Start the Arduino communication thread

while True:
    m0.setSpeed(127)
    time.sleep(1)
    m0.setSpeed(0)
    time.sleep(1)
    m0.setSpeed(-127)
    time.sleep(1)
    m0.setSpeed(0)
    time.sleep(1)
コード例 #15
0
ファイル: sensors.py プロジェクト: mbrar8/amsen
 def __init__(self):
     self.arduino = arduino.Arduino()
コード例 #16
0
#in this file:
#   headers
#   creation of a device from a list of commands
#   execution of device
#   command line workings

import arduino
import creator
import properties as P
import sys

if __name__ == "__main__":
    try:
        with open(sys.argv[1], "r") as f:
            listtobeprocessed = []
            for line in f:
                line = line.strip()
                if line != "" and line[0] != "#":
                    listtobeprocessed.append(line)
    except IndexError:
        listtobeprocessed = creator.main()
    except IOError:
        print "Exception: The input file could not be found. Aborting..."
        quit()
    dev = arduino.Arduino()
    o1 = dev.add("thermal_iterator")  #add output
    dev.add("diode_output", o1)  #add output
    o2 = dev.add("thermal_iterator")  #add output
    dev.add("diode_output", o2)  #add output
    print dev.build()
コード例 #17
0
ファイル: test.py プロジェクト: mbrar8/amsen
import time

import arduino
import driver


device1 = '/dev/ttyACM0'
device2 = '/dev/ttyACM1'
a1 = arduino.Arduino(device1)
a2 = arduino.Arduino(device2)
d = driver.Driver
while True:
    d.stop()
    print("Move forward 5")
    d.forward(5)
    d.wait()
    print("Reading")
    a1.read()
    a2.read()
    print(device1 + str(a1.sensor_input))
    print(device2 + str(a2.sensor_input))
    print("Turn left 90 degrees")
    d.turn_left(90)
    d.wait()
    time.sleep(1)
コード例 #18
0
ファイル: test.py プロジェクト: alexandremot/arduino-python
import arduino
import telegram
from time import sleep

while True:
    comand = telegram.get_my_posts()
    my_arduino = arduino.Arduino('test')

    print(f">>> Comando recebido pelo Telegram: {comand}")

    my_arduino.set(comand)

コード例 #19
0
ファイル: main.py プロジェクト: OhDongsung/Capstone_Raspi
split_data = data[0].split()
ipaddr = split_data[split_data.index('src') + 1]

# Unique number of raspberry pi
dat = {'did': 'raspberry002', 'ip': ipaddr}

# Server ID
serverURL = "http://rails-beanstalk.gb6ktuimmz.ap-northeast-2.elasticbeanstalk.com/regist"

# make public queue
commandQueue = Queue.Queue()

# init module
andRaspTCP = tcpServer.TCPServer(commandQueue, ipaddr, 1234)
andRaspTCP.start()
arduinoSerial = arduino.Arduino(commandQueue)
arduinoSerial.start()

# set module to executer
commandExecuter = executer.Executer(andRaspTCP, arduinoSerial)

# post raspby device id, ip
res = requests.post(serverURL, data=dat)
print(res.text)
while True:
    try:
        command = commandQueue.get()
        commandExecuter.startCommand(command)
    except:
        pass
コード例 #20
0
ファイル: main.py プロジェクト: miller45/heatingpi
import tempsensors
import relay
import time
import mqttcom
import configparser
import math
import arduino
import time

print("Starting HeatingPI V0.2")

ard = arduino.Arduino('/dev/ttyACM0')

hpConfig = configparser.ConfigParser()
hpConfig.read("config.ini")

#myOled = oled.OLED()
#myOled.showSplashScreen()

# mySens = tempsensors.TempSensors("28-3c01f0964f8c", "28-3c01f0965e56")
mySens = tempsensors.TempSensors(hpConfig["sensors"]["T1"],
                                 hpConfig["sensors"]["T2"],
                                 hpConfig["sensors"]["T3"],
                                 hpConfig["sensors"]["T4"])
# mySens = tempsensors.TempSensors("28-0317607252ff", "28-051760bdebff")

relayBoard = relay.RelayBoard()

mqttClient = mqttcom.MQTTComm(hpConfig["mqtt"]["server_address"],
                              hpConfig["mqtt"]["base_topic"])
コード例 #21
0
#-*- coding: utf-8 -*-
# stino/__init__.py

import sublime

import utils
import stpanel
import setting
import const
import osfile
import language
import smonitor
import arduino
import stmenu
import actions
import compilation

log_panel = stpanel.STPanel()
serial_listener = smonitor.SerialPortListener()
cur_language = language.Language()
arduino_info = arduino.Arduino()
cur_menu = stmenu.STMenu(cur_language, arduino_info)
status_info = setting.Status(const.settings, arduino_info, cur_language)
serial_port_in_use_list = []
serial_port_monitor_dict = {}
コード例 #22
0
import time
import sys
sys.path.append("../..")

import arduino

# Example code to run an IR sensor. Turns on the LED
# at digital pin 13 when the IR sensor detects anything within
# a certain distance.

THRESH = 200.0  # Experimentally chosen

ard = arduino.Arduino()  # Create the Arduino object
a0 = arduino.AnalogInput(ard, 0)  # Create an analog sensor on pin A0
ard.run()  # Start the thread which communicates with the Arduino

# Main loop -- check the sensor and update the digital output
while True:
    ir_val = a0.getValue()  # Note -- the higher value, the *closer* the dist
    print ir_val, ir_val >= THRESH
    time.sleep(0.1)
コード例 #23
0
ファイル: allegro.py プロジェクト: 7mobile56/allegro
                delta = self.ttl
            for led in range(len(self.cur_chain)):
                for clr in range(3):
                    self.cur_chain[led][clr] = self.slopes[led][clr] * delta + \
                        self.old_chain[led][clr]
            self.cur_chain.draw()
            if delta >= self.ttl:
                raise StopIteration


if __name__ == '__main__':
    #port = "/dev/tty.usbserial-A800ewuP"
    port = "/dev/ttyUSB0"
    debug = True
    debug = False
    hwport = arduino.Arduino(port, debug=debug)
    hwport.reset(5)
    chain = Chain(hwport)
    chain.length = 2
    chain.clear()
    HSV = 1000
    while 1:
        for hue in range(HSV):
            hue = hue / float(HSV)
            for led in range(chain.length):
                chain.lights[led].hsv = (hue, 1, 1)
            chain.draw()
            #time.sleep(.1)
    """
    while 1:
        for x in range(1023):
コード例 #24
0
    def __init__(self,
                 parent,
                 verbose=False,
                 emulate_wheel=False,
                 print_arduino=False):
        self.parent = parent
        parent.columnconfigure(0, weight=1)
        # parent.rowconfigure(1, weight=1)

        self.verbose = verbose

        self.var_cache_size = tk.IntVar()
        self.var_sess_dur = tk.IntVar()
        self.var_rec_zeros = tk.IntVar()
        self.var_emulate_wheel = tk.IntVar()
        self.var_track_per = tk.IntVar()
        self.var_save_txt = tk.BooleanVar()

        self.var_cache_size.set(500)
        self.var_sess_dur.set(1)
        self.var_rec_zeros.set(1)
        self.var_emulate_wheel.set(emulate_wheel)
        self.var_track_per.set(50)
        self.var_save_txt.set(True)

        self.parameters = {
            'emulate_wheel': self.var_emulate_wheel,
            'session_dur': self.var_sess_dur,
            'record_zeros': self.var_rec_zeros,
            'track_period': self.var_track_per,
        }

        self.var_print_arduino = tk.BooleanVar()
        self.var_stop = tk.BooleanVar()

        self.var_print_arduino.set(print_arduino)
        self.var_stop.set(False)

        # Counters
        # IMPORTANT: need to keep `counter_vars` in same order as `arduino_events`
        self.var_counter_wheel = tk.IntVar()
        counter_vars = [self.var_counter_wheel]
        self.counter = {
            ev: var_count
            for ev, var_count in zip(arduino_events.values(), counter_vars)
        }

        self.var_start_time = tk.StringVar()
        self.var_stop_time = tk.StringVar()

        # Lay out GUI

        frame_setup = tk.Frame(parent)
        frame_setup.grid(row=0, column=0)
        frame_setup_col0 = tk.Frame(frame_setup)
        frame_setup_col1 = tk.Frame(frame_setup)
        # frame_setup_col2 = tk.Frame(frame_setup)
        frame_setup_col0.grid(row=0, column=0, sticky='we')
        frame_setup_col1.grid(row=0, column=1, sticky='we')
        # frame_setup_col2.grid(row=0, column=2, sticky='we')

        frame_monitor = tk.Frame(parent)
        frame_monitor.grid(row=1, column=0)
        # frame_monitor.rowconfigure(0, weight=1)
        # frame_monitor.columnconfigure(1, weight=1)

        # Session frame
        frame_params = tk.Frame(frame_setup_col0)
        frame_params.grid(row=0, column=0, padx=15, pady=5)
        frame_params.columnconfigure(0, weight=1)

        frame_session = tk.Frame(frame_params)
        frame_misc = tk.Frame(frame_params)
        frame_session.grid(row=0, column=0, sticky='e', padx=px, pady=py)
        frame_misc.grid(row=2, column=0, sticky='e', padx=px, pady=py)

        # Arduino frame
        frame_arduino = ttk.LabelFrame(frame_setup_col0, text='Arduino')
        frame_arduino.grid(row=1, column=0, padx=px, pady=py, sticky='we')

        # Notes frame
        frame_notes = tk.Frame(frame_setup_col1)
        frame_notes.grid(row=0, sticky='wens', padx=px, pady=py)
        frame_notes.grid_columnconfigure(0, weight=1)

        # Saved file frame
        frame_file = tk.Frame(frame_setup_col1)
        frame_file.grid(row=1, column=0, padx=px, pady=py, sticky='we')
        frame_file.columnconfigure(0, weight=3)
        frame_file.columnconfigure(1, weight=1)

        # Start-stop frame
        frame_start = tk.Frame(frame_setup_col1)
        frame_start.grid(row=3, column=0, sticky='we', padx=px, pady=py)
        frame_start.grid_columnconfigure(0, weight=1)
        frame_start.grid_columnconfigure(1, weight=1)

        # Monitor frame
        frame_counter = tk.Frame(frame_monitor)
        frame_live = tk.Frame(frame_monitor)
        frame_counter.grid(row=0, column=0, padx=px, pady=py, sticky='we')
        frame_live.grid(row=1, column=0, padx=px, pady=py, sticky='wens')

        # Add GUI components

        ## frame_params

        ### frame_session
        ## UI for trial control
        self.entry_session_dur = ttk.Entry(frame_session,
                                           textvariable=self.var_sess_dur,
                                           width=entry_width)
        tk.Label(frame_session, text='Session duration (min): ',
                 anchor='e').grid(row=0, column=0, sticky='e')
        self.entry_session_dur.grid(row=0, column=1, sticky='w')

        ### frame_misc
        ### UI for miscellaneous parameters
        self.entry_rec_all = ttk.Checkbutton(frame_misc,
                                             variable=self.var_rec_zeros)
        self.entry_track_period = ttk.Entry(frame_misc,
                                            textvariable=self.var_track_per,
                                            width=entry_width)
        tk.Label(frame_misc, text='Record zeros: ',
                 anchor='e').grid(row=0, column=0, sticky='e')
        tk.Label(frame_misc, text='Track period (ms): ',
                 anchor='e').grid(row=1, column=0, sticky='e')
        self.entry_rec_all.grid(row=0, column=1, sticky='w')
        self.entry_track_period.grid(row=1, column=1, sticky='w')

        ### frame_arduino
        ### UI for Arduino
        self.arduino = arduino.Arduino(frame_arduino,
                                       main_window=self.parent,
                                       verbose=self.verbose,
                                       params=self.parameters)
        self.arduino.grid(row=0, column=0, sticky='we')
        self.arduino.var_uploaded.trace_add('write', self.gui_util)

        ## Notes
        self.entry_subject = ttk.Entry(frame_notes)
        self.entry_weight = ttk.Entry(frame_notes)
        self.scrolled_notes = ScrolledText(frame_notes, width=20, height=15)
        tk.Label(frame_notes, text='Subject: ').grid(row=0,
                                                     column=0,
                                                     sticky='e')
        tk.Label(frame_notes, text='Weight (g): ').grid(row=1,
                                                        column=0,
                                                        sticky='e')
        tk.Label(frame_notes, text='Notes:').grid(row=2,
                                                  column=0,
                                                  columnspan=2,
                                                  sticky='w')
        self.entry_subject.grid(row=0, column=1, sticky='w')
        self.entry_weight.grid(row=1, column=1, sticky='w')
        self.scrolled_notes.grid(row=3, column=0, columnspan=2, sticky='wens')

        ## UI for saved file
        self.entry_save_file = ttk.Entry(frame_file)
        self.button_set_file = ttk.Button(frame_file,
                                          command=self.get_save_file)
        tk.Label(frame_file, text='File to save data:',
                 anchor='w').grid(row=0, column=0, columnspan=2, sticky='w')
        self.entry_save_file.grid(row=1, column=0, sticky='wens')
        self.button_set_file.grid(row=1, column=1, sticky='e')

        folder_icon_file = os.path.join(source_path, 'graphics/folder.png')
        icon_folder = ImageTk.PhotoImage(file=folder_icon_file)
        self.button_set_file.config(image=icon_folder)
        self.button_set_file.image = icon_folder

        ## Start frame
        self.button_start = ttk.Button(
            frame_start,
            text='Start',
            command=lambda: self.parent.after(0, self.start))
        self.button_stop = ttk.Button(frame_start,
                                      text='Stop',
                                      command=lambda: self.var_stop.set(True))
        self.button_start.grid(row=2, column=0, sticky='we')
        self.button_stop.grid(row=2, column=1, sticky='we')

        ## Counter frame
        tk.Label(frame_counter, text='Start time: ').grid(row=0,
                                                          column=0,
                                                          sticky='e')
        tk.Label(frame_counter, text='End time: ').grid(row=1,
                                                        column=0,
                                                        sticky='e')
        self.entry_start_time = ttk.Entry(frame_counter,
                                          textvariable=self.var_start_time,
                                          state='readonly',
                                          width=entry_width)
        self.entry_stop_time = ttk.Entry(frame_counter,
                                         textvariable=self.var_stop_time,
                                         state='readonly',
                                         width=entry_width)
        self.entry_start_time.grid(row=0, column=1, sticky='wens')
        self.entry_stop_time.grid(row=1, column=1, sticky='wens')

        ## Live frame
        data_types = {arduino_events[code_wheel]: 'line'}
        # tk.Label(frame_live, text='Also under construction').grid()
        self.live_view = live_data_view.LiveDataView(frame_live,
                                                     x_history=30000,
                                                     scale_x=0.001,
                                                     data_types=data_types,
                                                     ylim=(-25, 50),
                                                     xlabel='Time (s)')

        ###### GUI OBJECTS ORGANIZED BY TIME ACTIVE ######
        # List of components to disable at open
        self.obj_to_disable_on_upload = [
            child for child in (frame_session.winfo_children() +
                                frame_misc.winfo_children())
        ]
        self.obj_to_enable_on_upload = [self.button_start]
        self.obj_to_disable_at_open = [
            self.entry_session_dur,
            self.entry_track_period,
        ]

        self.obj_to_enable_at_open = [
            self.button_start,
        ]
        self.obj_to_disable_at_start = [
            self.entry_subject,
            self.entry_weight,
            self.entry_save_file,
            self.button_set_file,
            self.button_start,
        ]
        self.obj_to_enable_at_start = [self.button_stop]

        # Default values
        self.button_start['state'] = 'disabled'
        self.button_stop['state'] = 'disabled'

        ###### SESSION VARIABLES ######
        self.q_serial = Queue()
コード例 #25
0
ファイル: smart.py プロジェクト: Sicness/SmartHome
            print 'arduino_listen: found terminate flag. Exit'
            return

        line = ard.read()  # read line from arduino
        if line == '':  # if serial timeout is reached
            continue
        print(line)
        dispatch(line)


if __name__ == '__main__':
    #log('Smart home started')
    getWeather()
    #####     Objects configuration      ######
    ard = arduino.Arduino(
        '/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A80090sP-if00-port0',
        onFound=onArduinoFound,
        onLost=onArduinoLost)
    hole_motion.onOn = onHoleMotion
    hole_motion.onOff = onHoleMotionOff
    init_IR_codes()  # init dict: { IR_CODE : function }
    ### Threads creating ###
    sock_thr = Thread(target=sock_listen, args=(), name="sock_thr")
    sock_thr.start()
    glob.get('threads').append(sock_thr)
    ard_thr = Thread(target=arduino_listen, args=(), name="ard_thr")
    ard_thr.start()
    glob.get('threads').append(ard_thr)
    ds = Thread(target=get_T, args=(), name="ds")
    ds.start()  # ds18s20 temerature sensor
    glob.get('threads').append(ds)
コード例 #26
0
import arduino
import constants
from time import sleep, time
import threading
import angle_master

feedback_ard = arduino.Arduino(constants.ID_FEEDBACK_ARDUINO, 57600)
movement_ard = arduino.Arduino(constants.ID_MOVEMENT_ARDUINO, 57600)
sleep(2)
present_angles = [0, 0, 0, 0, 0, 0]


def handle_interrupts(data):
    pass


a1 = 0
a2 = 0


def get_feedbacks():
    global a1
    global a2
    while True:
        data = feedback_ard.readline()
        # print(data)
        if data and 'F' in data and len:
            raw_values = data.strip().split(',')[1:]
            # print(raw_values)
            try:
                a1 = angle_master.get_angle(
コード例 #27
0
    last_error = error - roll_olderror
    roll_olderror = error
    roll_out = error * roll_Kp + roll_sum * roll_Ki + last_error * roll_Kd + roll_MID
    if (roll_out > roll_MAX):
        roll_out = roll_MAX
    elif (roll_out < roll_MIN):
        roll_out = roll_MIN
    return roll_out


# Init
print("[INFO] init_\n")
sum_dir = np.zeros(2)
count_dir = np.zeros((5), dtype=np.int)

Arduino = arduino.Arduino()
cap_count = 0
while True:
    cap = cv2.VideoCapture(cap_count)
    if (cap.isOpened()):
        break
    elif (cap_count == 8):
        cap_count = 0
    else:
        cap_count += 1
print("[INFO] camera_open\n")
print(count_dir)
count_dir[4] = 0
Arduino.send(count_dir)
ret, frame = cap.read()
コード例 #28
0
import sys
import time
import subprocess

from werkzeug.datastructures import MultiDict

import flask
app = flask.Flask(__name__)

import fergboard  # fergboard_motors.py
motors = fergboard.Motors()

import arduino  # arduino.py
arduino_uno = arduino.Arduino()


class MJpegStream():
    def __init__(self):
        self.proc = None
        self.params = MultiDict()

    def start(self, params):
        """
        Start mjpg-streamer, wait until it has warmed up, and return success/failure
        """
        if self.proc:
            self.stop()
        self.proc = subprocess.Popen(self.create_args(params),
                                     stderr=subprocess.PIPE, universal_newlines=True)

        # Block until we have read the line "Encoder Buffer Size" from stderr.
コード例 #29
0
import sys, time

sys.path.append("/home/maslab-team-5/Maslab/tart/Libraries/")
import arduino
from tart.actuators import drive

if __name__ == "__main__":
    try:
        ard = arduino.Arduino(debug=True)
        dt = drive.SimpleDrive(ard, (2, 0), (2, 1))

        ard.start()
        assert ard.waitReady()

        dt.setMotors(127, 127)
        time.sleep(10)
        dt.setMotors(-127, -127)
        time.sleep(10)

        dt.setMotors(0, 0)

    #This is so that when you hit ctrl-C in the terminal, all the arduino threads close. You can do something similar with threads in your program.
    except KeyboardInterrupt:
        print "Ending Program"

    finally:
        ard.stop()