def __init__(self): # initialize the motors self.motors = [ Motor("Azimuth", self.az_pins, positive=1), Motor("Altitude", self.alt_pins, positive=-1) ] # initialize observer and target self._observer = ephem.Observer() self._target = ephem.FixedBody() # insteresting objects in our solar system and main stars self._sky_objects = [ ephem.Sun(), ephem.Moon(), ephem.Mercury(), ephem.Venus(), ephem.Mars(), ephem.Jupiter(), ephem.Saturn() ] for star in sorted([ x.split(',')[0] for x in ephem.stars.db.split('\n') if x ]): self._sky_objects.append( ephem.star(star)) # set boolean variable indicating tracking self._is_tracking = False self.restart = [False, False] self.running = [False, False] # initialize angles/steps lists for calibration self._angles_steps = [[], []] # initialize motor threads self._motor_threads = [ None, None ] az_default_spr=1293009 alt_default_spr=1560660 self.motors[0].steps_per_rev = az_default_spr self.motors[1].steps_per_rev = alt_default_spr # at startup no client is connected self._client_connected = False
def Actuator(type_of_actuator): return_value = None #print('__call_ in actuator') if type_of_actuator == 'switch': return_value = Switch() elif type_of_actuator == 'motor': return_value = Motor() None else: print('type of actuator is underfined') return (return_value)
def __init__(self, r_int = 0, t_int = 0, z_int = 0): # Begins at the origin [0, 0, 0] self.motor = Motor() self.position = Position() self.trajectory = [] self.__dict__['target'] = [] self.plot = [] self.r_steps = r_int self.theta_steps = t_int self.z_steps = z_int # If there were provided coordinates, start there. if r_int + t_int + z_int > 0: self.begin()
def __init__(self): GPIO.setmode(GPIO.BOARD) # Init devices # TODO: Replace these numbers with the correct pins self.motor_l = Motor(3, 4, 5) self.motor_r = Motor(3, 4, 5) self.encoder_l = Encoder(0, 0) self.encoder_r = Encoder(0, 0) self.sensors = [ DistSensor(0), DistSensor(0), DistSensor(0), DistSensor(0), DistSensor(0) ] # Misc state self.move_state = MoveState.STRAIGHT self.spd = 0 self.running = True # Constants, probably gonna rewrite how the bot turns self.outer_ticks = 10 self.inner_ticks = 0 self.max_ticks = 50
def __init__(self): super(MotorController, self).__init__(0, SerialCom(Config.get_serial_port())) nb_motors = Config.get_nb_motors() for id in range(1, nb_motors + 1): self.motors.append( Motor(id, id > nb_motors / 2, self.serial_com, Config.get_speed_ratio()[id - 1], Config.get_position_ratio()[id - 1])) self.serial_com.add_listener(ReportActualPositionResponse, self._on_position_update) self.serial_com.add_listener(ReportStatusResponse, self._on_status_update)
def __init__(self, config): Thread.__init__(self) self.angle = 0 self.K = 0.98 self.logDataSetBuffer = [] self.Kp = config.config.as_float('Kp') self.Ki = config.config.as_float('Ki') self.Kd = config.config.as_float('Kd') self.set_point = config.config.as_float('set_point') self.disable_motors = config.config.as_bool('disable_motors') self.integral_error = 0 self.last_error = 0 self.motor_left = Motor("L", port_motor_left_pwm, port_motor_left_backward, port_motor_left_forward) self.motor_right = Motor("R", port_motor_right_pwm, port_motor_right_backward, port_motor_right_forward) self.accelerometer = MPU6050() self.last_time = time() self.logger = logging.getLogger(__name__) self.setDaemon(True) self.latest_sensor = 0 self.logger.info( 'Initialized ControlThread with the following settings') self.logger.info('disable_motors={}'.format(self.disable_motors)) self.logger.info('set_point={:1.2f}'.format(self.set_point)) self.logger.info('Kp={:1.1f}'.format(self.Kp)) self.logger.info('Ki={:1.1f}'.format(self.Ki)) self.logger.info('Kd={:1.1f}'.format(self.Kd))
def __init__(self, left_wheel_forward, left_wheel_backward, left_wheel_enable, right_wheel_forward, right_wheel_backward, right_wheel_enable): """Constructor. Args: left_wheel_forward (int): GPIO pin connected to left motor's forward pin. left_wheel_backward (int): GPIO pin connected to left motor's backward pin. left_wheel_enable (int): GPIO pin connected to left motor's enable pin. right_wheel_forward (int): GPIO pin connected to right motor's forward pin. right_wheel_backward (int): GPIO pin connected to right motor's backward pin. right_wheel_enable (int): GPIO pin connected to right motor's enable pin. """ # set motors self.left = Motor(left_wheel_forward, left_wheel_backward, left_wheel_enable) self.right = Motor(right_wheel_forward, right_wheel_backward, right_wheel_enable)
def __init__(self): self.d = Dialog(dialog="dialog") self.d.set_background_title(config["GENERAL"]["carName"]) self.code = self.d.OK if config["MOTOR"]["motorEnabled"] == "True": self.motor = Motor(config) if config["FAN"]["fanEnabled"] == "True": self.fan = Fan(config) if config["CAMERA"]["cameraEnabled"] == "True": self.camera = Camera(config) self.camera.start()
def __init__(self, motor_ports: Dict[str, int]): """ Sets up quadcopter. \n Arguments: \n motor_ports Dict: a dict of the ports used by each motor e.g. {"front_left": 3} \n Returns: nothing """ self.pi = pigpio.pi() self.motor_ports = motor_ports # Motor setup: self.front_left = Motor(self.motor_ports["front_left"], self.pi) self.front_right = Motor(self.motor_ports["front_right"], self.pi) self.back_left = Motor(self.motor_ports["back_left"], self.pi) self.back_right = Motor(self.motor_ports["back_right"], self.pi) self.motor_min = 1000 self.motor_max = 2000 self.motor_list = [ self.front_left, self.front_right, self.back_left, self.back_right ] self.throttle = 0
def __init__(self): config = configparser.ConfigParser() config.read("config.ini") IN_1 = config.getint("car","IN1") IN_2 = config.getint("car","IN2") IN_3 = config.getint("car","IN3") IN_4 = config.getint("car","IN4") self.change_speed = ChangeSpeed() self.motor = Motor(IN_1, IN_2, IN_3, IN_4) self.sense = Sense() self.qaudio = QAudio(4000) self.led_light = LED_Light()
def __init__(self, is_debug=False): ''' Car构造器函数 ''' # 电池ADC采样 self.battery_adc = BatteryVoltage(gpio_dict['BATTERY_ADC'], is_debug=False) # 用户按键 self.user_button = Button(0, callback=lambda pin: self.stop_trigger(pin)) try: # 创建一个I2C对象 i2c = I2C(scl=Pin(gpio_dict['I2C_SCL']), sda=Pin(gpio_dict['I2C_SDA']), freq=car_property['I2C_FREQUENCY']) # 创建舵机云台对象 self.cloud_platform = CloudPlatform(i2c) except: print('[ERROR]: pca9885舵机驱动模块初始化失败') print('[Hint]: 请检查接线') self.speed_percent = 70 # 小车默认速度 # 左侧电机 self.left_motor = Motor(0) self.left_motor.stop() # 左侧电机停止 # 右侧电机 self.right_motor = Motor(1) self.right_motor.stop() # 右侧电机停止 # 小车停止标志位 self.stop_flag = False self.is_debug = is_debug # 是否开始调试模式
def __init__(self, event): Thread.__init__(self) self.bt_event = event # instellen van de motoren op de fysieke pins self.motor_r = Motor(6, 5, 13) self.motor_l = Motor(16, 18, 12) # Standaard bluetooth settings self.server_sock = BluetoothSocket(RFCOMM) self.server_sock.bind(("", PORT_ANY)) self.server_sock.listen(1) # port die het zelfde is op de app self.uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee" # aanbieden van de socket advertise_service( self.server_sock, "Gyrosphere_control_server", service_id=self.uuid, service_classes=[self.uuid, SERIAL_PORT_CLASS], profiles=[SERIAL_PORT_PROFILE], )
def __init__(self, model_parameters): self.motor = Motor() self.pid_controller = PidController(model_parameters.kp, model_parameters.Ti, model_parameters.Td) self._rated_voltage = model_parameters.rated_voltage self._rated_current = model_parameters.rated_current self._rated_speed = model_parameters.rated_speed self._resistance = model_parameters.resistance self._input_coefficient = self._rated_voltage / self._rated_speed self._coil_emf = self._rated_voltage - self._rated_current * self._resistance self._electric_coefficient = self._coil_emf / self._rated_speed self._voltage_error = 0.0 self._rotational_speed = 0.0 self._rotor_current = 0.0
def __init__(self, directory, model): self.current_position = 0 self.iteration = 0 self.directory = directory self.predictions = [] self.model = model self.rotation = 0 self.mic_centre = np.array([1.5, 1.5]) self.prediction = 0 self.audio = audio_recorder(self.directory) self.motor = Motor() self.current_model = self.get_model() # init self.motor_offset = 0 self.relative_prediction = 0 self.results = [] self.initial_adjust = False
def threadGianessaCar(): x = None m = Motor() global ruta global banSend while True: with lockRuta: if (len(ruta) > 0): x = ruta.pop(0) if (x): with lockSend: banSend = True #print "Se puede trasmitir la ruta" m.turn(x[1]) m.move(x[0]) x = None with lockSend: banSend = False
def main(): global m global ot global vp global ss global count_down v = None count_start = None broad_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) broad_sock.bind(('', PORT_TO_BROADCAST)) data = None addr = None print 'Wait for broadcast message.' while True: data, addr = broad_sock.recvfrom(4096) if Check_Identity(data) is True: break broad_sock.close() host = addr[0] print 'Get broadcast message from host:', host ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ss.connect((host, PORT_FROM_VIDEO)) sr = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sr.bind(('', PORT_TO_VIDEO)) sr.listen(1) md, addr = sr.accept() print 'Start to instantiate classes.' while True: try: m = Motor() if not m else m ot = Orientation() if not ot else ot if not count_start: count_start = time.time() v = VFFmpeg(host) if not v else v if m and ot and v: # if m and ot: break except Exception, e: print '[FATAL ERROR]', e exit(-1)
def __init__(self): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) self.green_led = LED(5) self.yellow_led = LED(13) self.red_led = LED(21) self.motor = Motor() self.web_cam = cv.VideoCapture(0) self.pi_cam = PiCamera() self.angle = 0.25 self.open = False self.face = None self.server_ip = '10.10.3.21' self.port = 8080 self.threshold = 20000 self.interval = 10
def test_asservissement_ch2_2(): pin_dir = Pin(16) pin_speed = Pin(17) motor = Motor(pin_dir, pin_speed) motor.off() pin_ch_a = Pin(18) pin_ch_b = Pin(19) encoder = Encoder(pin_ch_a, pin_ch_b) Kp = 1 filter = Filter(Kp, 0, 0) controler = Controler(encoder, motor, filter) ramp_inc = generate_ramp(0, 100, 0.2) controler.position_loop(ramp_inc)
def main(): motor = Motor() print("> Motor initialized") presence = Presence() print("> Presence initialized") while True: if presence.has_presence() == True: motor.on() # donaldduck.play(DONALD_TRACK) p = vlc.MediaPlayer(AUDIO_PATH + "/" + DONALD_TRACK) p.play() start = time.time() while audio.info.length > (time.time() - start): if ((time.time() - start) > 0.0) and ( (time.time() - start) < 2.0): motor.on() print("> Motor ON!") elif ((time.time() - start) > 2.1) and ( (time.time() - start) < 20.0): motor.off() print("> Motor OFF!") elif ((time.time() - start) > 20.1) and ( (time.time() - start) < 23.0): motor.on() print("> Motor ON!") elif ((time.time() - start) > 23.1) and ( (time.time() - start) < 30.0): motor.off() print("> Motor OFF!") elif ((time.time() - start) > 39.1) and ( (time.time() - start) < 40.0): motor.on() print("> Motor ON!") elif ((time.time() - start) > 40.1): motor.off() print("> Motor OFF!") print("> Playing Track!") motor.off() print("> Motor OFF!") time.sleep(0.5)
def test_asservissement_ch2_2(): pin_ch_a = Pin(21) pin_ch_b = Pin(20) encoder = Encoder(pin_ch_a, pin_ch_b,reverse_direction = False) pin_dir = Pin(6) pin_speed = Pin(7) motor = Motor(pin_dir, pin_speed,reverse_sense=True) motor.off() Kp = 1 filter = Filter(Kp, 0, 0) controler = Controler(encoder, motor, filter) ramp_inc = generate_ramp(0, 100, 1) controler.position_loop(ramp_inc)
def __init__(self): # Turn off warnings GPIO.setwarnings(False) # Set up GPIO for RPi GPIO.setmode(GPIO.BOARD) forwardPin = 7 backwardPin = 11 leftPin = 13 rightPin = 15 controlStraightPin = 29 # Initialize motor class self.motor = Motor(forwardPin, backwardPin, controlStraightPin, leftPin, rightPin) # Initialize client for streaming camera pictures and receiving driving instructions self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_socket.connect(('192.168.1.11', 8000)) # Make a file-like object out of the client connection self.client_connection = self.client_socket.makefile('wb') # Start the stream self.stream()
def __init__(self, cell): """Initialize variables used by Cell class \n Args: \n cell: dict represents a cell data: cell.id: int cell.location: list cell.coordinates: list cell.code: int cell.motors: list of objects """ self.id = cell['id'] self.location = cell['location'] self.coordinates=cell['coordinates'] self.code = cell['code'] self.motors = [] self.angle = self.magnitude = self.w = -1 for i in range(len(cell['motors'])): self.motors.append( Motor({'id': self.id * 10 + i, **cell['motors'][i], 'code': self.code}))
def __init__(self, master): self.master = master self.db = DB() self.db.abrir() self.mot = Motor() self.son = Sonidos() self.texto = "" self.pilotoAuto = False self.motstop = True self.nvueltajug1 = 0 self.tmpvueltajug1 = "" self.pasoj1 = False self.accJ1 = 0 self.grabavuelta = False self.playvuelta = False master.title("circuito") master.geometry("800x600") self.builder = builder = pygubu.Builder() fpath = os.path.join(os.path.dirname(__file__), "pantalla.ui") builder.add_from_file(fpath) mainwindow = builder.get_object('frmpal', master) self.lsttmp2 = lbox = builder.get_object('lsttiempos') self.cargapilotos() self.cargacoches() self.timerms_ = 0 self.timers_ = 0 self.timerm_ = 0 #~ self.bgTask = BackgroundTask( self.myLongProcess ) #~ self.timer =BackgroundTask (self.onTimer) #~ self.timer = TkRepeatingTask( self.master, self.onTimer, 1) #~ self.xbTask =BackgroundTask (self.procesoMandoXbox ) builder.connect_callbacks(self) self.timer = TkRepeatingTask(self.master, self.onTimer, 1) self.xbTask = BackgroundTask(self.procesoMandoXbox)
def main(): gpio.setmode(gpio.BCM) motor1 = Motor(input1 = 22 , input2 = 27 , input3 = 17 , input4 = 4) for i in range(3): print("Count :{}".format(i)) motor1.forward() time.sleep(1.0) motor1.stop() motor1.reverse() time.sleep(1.0) motor1.stop() time.sleep(0.5) gpio.cleanup()
def __init__(self, bus, adc_addr=0x48, motor_pin1=L293_1, motor_pin2=L293_2, motor_enable = STEREO_L293_ENABLE, dirmult=1, verbose=False): Thread.__init__(self) self.motor = Motor(pin1=motor_pin1, pin2=motor_pin2, enable = motor_enable) self.motor.set_speed(0) self.adc = ADS1015(bus, adc_addr) self.adc.write_config(MUX_AIN0 | PGA_4V | MODE_CONT | DATA_1600 | COMP_MODE_TRAD | COMP_POL_LOW | COMP_NON_LAT | COMP_QUE_DISABLE) self.dirmult = dirmult self.setPoint = None self.newSetPoint = False self.moving = False self.daemon = True self.verbose = verbose self.lastStopTime = time.time() self.start()
def run(): global ultrasonic1, ultrasonic2, ultrasonic3, motors ultrasonic1 = Ultrasonic(TRIG1, ECHO1) ultrasonic2 = Ultrasonic(TRIG2, ECHO2) ultrasonic3 = Ultrasonic(TRIG3, ECHO3) motors = Motor(MOTOR1A, MOTOR1B, MOTOR2A, MOTOR2B) rospy.init_node('controller', anonymous=True) distance_publisher = rospy.Publisher('distance', Distance, queue_size=10) rospy.Subscriber('direction', Direction, steer) rospy.on_shutdown(exit_gracefully) rate = rospy.Rate(5) while not rospy.is_shutdown(): distance1, distance2, distance3 = scan_distance() distance_msg = Distance() distance_msg.distance1 = distance1 distance_msg.distance2 = distance2 distance_msg.distance3 = distance3 rospy.loginfo(distance_msg) distance_publisher.publish(distance_msg) rate.sleep()
def __init__(self, n_motors=1, pwmFreq=100): self.pwmDict = { 60: [260, 276, 457], 100: [434, 481, 761], 400: [1736, 1954, 3047] } self.pwm = Adafruit_PCA9685.PCA9685() self.pwmFreq = int(pwmFreq) self.pwm.set_pwm_freq(self.pwmFreq) self.motor_channels = [] available_channels = [0, 1, 14, 15] for i in range(n_motors): self.motor_channels.append(available_channels[i]) self.no_motors = n_motors self.motors = [] for m in self.motor_channels: self.motors.append( Motor(m, self.pwm, self.pwmDict[self.pwmFreq][0], self.pwmDict[self.pwmFreq][1], self.pwmDict[self.pwmFreq][2]))
def main(): gpio.setmode(gpio.BCM) distance_sensor = DistanceSensor() motor = Motor(input1=22, input2=27, input3=17, input4=4) try: while True: distance = distance_sensor.get_distance() if distance is None: print("None") sleep(DISTANCE_SLEEP) continue if distance_sensor.is_in_range(distance) == False: sleep(DISTANCE_SLEEP) continue if distance_sensor.is_far(distance): print("Forward") motor.forward() sleep(DISTANCE_SLEEP) motor.stop() continue if distance_sensor.is_close(distance): print("Backword") motor.reverse() sleep(DISTANCE_SLEEP) motor.stop() continue print("....") sleep(DISTANCE_SLEEP) except KeyboardInterrupt: gpio.cleanup()
def __init__(self, id, verify=False, bus=1, logger=None): """Create I2C interface, optionally verify DMCC :param id: The cape index or I2C address of the DMCC to initialzie :param verify: Perform an active test to verify the presence of a DMCC """ if logger == None: self.logger = lib.get_logger() else: self.logger = logger if not (0 <= id <= 3) and not (BASE_ADDR <= id <= BASE_ADDR + 3): err_msg = ( "DMCC id can either be an index (0-3) " + "or an address ({}-{})".format(BASE_ADDR, BASE_ADDR + 3)) self.logger.error(err_msg) raise ValueError(err_msg) if (id <= 3): self.cape_num = id else: self.cape_num = id - BASE_ADDR self.i2c = I2CDevice(bus, address=self.address, config='dmcc_i2c.yaml') self.logger.debug("Verifying {:#04x}".format(self.address)) if verify and not self.verify(): msg = "Failed to verify DMCC at {:#04x}".format(self.address) self.logger.warning(msg) raise RuntimeError() self.motors = {} for i in [1, 2]: self.motors[i] = Motor(self.i2c, i) self.logger.debug("DMCC {} ({:#04x}) initialized".format( self.cape_num, self.address))
def test_asservissement_ch1_speed(): pin_ch_a = Pin(21) pin_ch_b = Pin(20) encoder = Encoder(pin_ch_a, pin_ch_b,reverse_direction = False) pin_dir = Pin(6) pin_speed = Pin(7) motor = Motor(pin_dir, pin_speed,reverse_sense=True) motor.off() Kp = 20 filter = Filter(Kp, 0, 0) controler = Controler(encoder, motor, filter) ramp_inc = generate_ramp(0, 5, 1) plateau = generate_plateau(5,5) ramp_dec = generate_ramp(5, -5, 1) controler.speed_loop(ramp_inc) controler.speed_loop(plateau) controler.speed_loop(ramp_dec)