def detect_motors(): global MOTORS MOTORS = [ ev3.Motor('outA'), ev3.Motor('outB'), ev3.Motor('outC'), ev3.Motor('outD') ]
def __move_track(self, distance, speed, track, sleep=True): """ Moves the specified track of the robot based on the motor it's hooked to. The motor that controls the left and right tracks were established on init Keyword arguments: distance -- count of tacho units that the motor will be moved speed -- speed that tacho motor will run at track -- left or right motor sleep -- True makes the program wait until the motor is finished. Otherwise, proceed. This is important for turning vs moving forward. If moving forward, both motors can't be set to sleep or it will just turn instead of move forward """ if self._DEBUG: print("DEBUG: Distance -", distance, "speed:", speed, "track:", track) return None # Execute EV3 action motor = ev3.Motor(track) motor.reset() motor.run_to_abs_pos(position_sp=distance, speed_sp=speed) if sleep: # Waits until the motor is finished running while motor.is_running: time.sleep(1)
def stop_motor(): detect_motors() print("stop motors") for socket in ['outA', 'outB', 'outC', 'outD']: m = ev3.Motor(socket) if m.connected: m.stop(stop_action='brake')
def setUpClass(cls): cls._motor = ev3.Motor('outA') cls._motor.speed_sp = 400 cls._motor.ramp_up_sp = 300 cls._motor.ramp_down_sp = 300 cls._motor.position = 0 cls._motor.position_sp = 180 pass
def __init__(self, mediumMotorOut='outA'): self.mediumMotorOut = mediumMotorOut self.mediumMotor = ev3.Motor(mediumMotorOut) self.touchSensor = ev3.TouchSensor() self.colorSensor = ev3.ColorSensor()
import ev3dev.ev3 as ev3 import time def log(motor): print("speed" + str(motor.speed)) m = ev3.Motor("outA") m2 = ev3.Motor("outB") m3 = ev3.Motor("outD") infrared = ev3.InfraredSensor('in1') color = ev3.ColorSensor('in2') button = ev3.Button() infrared.auto_mode = False infrared.mode = infrared.MODE_IR_PROX print("Ready!") while True: print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAA") if button.any(): break time.sleep(5) velocity = 100 m.run_direct(duty_cycle_sp=velocity) m2.run_direct(duty_cycle_sp=velocity) m3.run_direct(duty_cycle_sp=0) activeMotor = m
#!/usr/bin/env python3 import ev3dev.ev3 as ev3 import time ev3.Sound.beep().wait() btn = ev3.Button() GLightRight = ev3.ColorSensor('in4') GLightRight.mode = 'COL-REFLECT' GMotorLeft = ev3.Motor() GMotorLeft = ev3.LargeMotor('outD') GMotorRight = ev3.Motor() GMotorRight = ev3.LargeMotor('outA') while not btn.backspace: if GLightRight.value() > 40: GMotorLeft.run_forever(speed_sp=450) # equivalent to power=20 in EV3-G GMotorRight.stop(stop_action='brake') else: GMotorRight.run_forever( speed_sp=450) # equivalent to power=20 in EV3-G GMotorLeft.stop(stop_action='brake') time.sleep(0.01)
class Brick: MOTORS = [ ev3.Motor('outA'), ev3.Motor('outB'), ev3.Motor('outC'), ev3.Motor('outD') ] def __init__(self, brick_id): self.stop_action = 'brake' self.client = client.BluetoothClient(brick_id, self.parse_message) client_thread = Thread(target=self.client.connect()) client_thread.start() def send_message(self, socket, title, body=None): if body is not None: message = {title: body} else: message = {title: {}} # message = {'message': {"content": title}} print("sending message: " + json.dumps(message)) socket.send(json.dumps(message)) def parse_message(self, data, socket): json_command = json.loads(data) command_type = list(json_command.keys())[0] command_args = json_command[command_type] # TODO: Add proper support for 'brick' param if (command_type == 'move' and len(command_args) == 4 and 'ports' in command_args.keys() and 'speed' in command_args.keys() and 'brick' in command_args.keys() and 'time' in command_args.keys()): self.rotate_motor(map(self.letter_to_int, command_args['ports']), command_args['speed'], command_args['time']) # Rotate motor # @param string socket Output socket string (0 / 1 / 2 / 3) # @param int speed Speed to rotate motor at (degrees/sec) # @param int time Time to rotate motor for (milliseconds) def rotate_motor(self, sockets, speed, time): for socket in sockets: motor = self.MOTORS[socket] if motor.connected: # Safety checks (1000 speed is cutting it close but should be safe, time check is just for sanity) if -1000 < int(speed) <= 1000 and 0 < int(time) <= 10000: motor.run_timed(speed_sp=speed, time_sp=time) else: print('[ERROR] No motor connected to ' + socket) # Moves motor by specified distance at a certain speed and direction # @param int socket Socket index in MOTORS to use # @param float dist Distance to move motor in centimeters # @param int speed Speed to move motor at (degrees / sec) def move_motor_by_dist(self, motor, dist, speed): if motor.connected: # convert to cm and then to deg angle = int(self.cm_to_deg(float(dist) / 10)) motor.run_to_rel_pos(position_sp=angle, speed_sp=speed, stop_action=self.stop_action) self.wait_for_motor(motor) else: print('[ERROR] No motor connected to ' + str(motor)) def motor_ready(self, motor): # Make sure that motor has time to start time.sleep(0.1) # Motor is ready only when its state is empty according to documentation return motor.state == [] def stop_motors(self, sockets=None): # Stop all the motors by default if sockets is None: sockets = [0, 1, 2, 3] for socket in sockets: m = self.MOTORS[socket] if m.connected: m.stop(stop_action=self.stop_action) def cm_to_deg(self, cm): DEG_PER_CM = 29.0323 return DEG_PER_CM * cm def letter_to_int(self, letter): if letter == 'A': return 0 elif letter == 'B': return 1 elif letter == 'C': return 2 elif letter == 'D': return 3 elif isinstance(letter, int): return letter else: print("Set value to default A: value 0") return 0 def wait_for_motor(self, motor): # Make sure that motor has time to start time.sleep(0.1) while motor.state == ["running"]: print('Motor is still running') time.sleep(0.1)
def run_direct_duty_cycles(self, stop_action, duty_cycles): self._param['motor'].stop_action = stop_action self._param['motor'].command = 'run-direct' for i in duty_cycles: self._param['motor'].duty_cycle_sp = i time.sleep(0.5) self._param['motor'].command = 'stop' def test_stop_coast_duty_cycles(self): self.initialize_motor() self.run_direct_duty_cycles('coast', [0, 20, 40, 60, 80, 100, 66, 33, 0, -20, -40, -60, -80, -100, -66, -33, 0]) # Add all the tests to the suite - some tests apply only to certain drivers! def AddTachoMotorRunDirectTestsToSuite(suite, driver_name, params): suite.addTest(ptc.ParameterizedTestCase.parameterize(TestMotorRunDirect, param=params)) if __name__ == '__main__': params = {'motor': ev3.Motor('outA'), 'port': 'outA', 'driver_name': 'lego-ev3-l-motor'} suite = unittest.TestSuite() AddTachoMotorRunDirectTestsToSuite(suite, 'lego-ev3-l-motor', params) unittest.TextTestRunner(verbosity=1, buffer=True).run(suite)
from threading import Thread import db.main as db import ev3dev.ev3 as ev3 from messages import server PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname( os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) DB_FILE = db.PRODUCTION_DB MOTORS = [ ev3.Motor('outA'), ev3.Motor('outB'), ev3.Motor('outC'), ev3.Motor('outD') ] DEG_PER_CM = 29.0323 def detect_motors(): global MOTORS MOTORS = [ ev3.Motor('outA'), ev3.Motor('outB'), ev3.Motor('outC'), ev3.Motor('outD')
#!/usr/bin/env python3 import os from http.server import BaseHTTPRequestHandler, HTTPServer import urllib import ev3dev.ev3 as ev3 import time import random import sys SPEED = 500 HAND_SPEED = 300 lm1 = ev3.LargeMotor('outD') lm2 = ev3.LargeMotor('outB') m1 = ev3.Motor('outA') def driveMotor(motor, speed): print("speed=", speed) motor.run_forever(speed_sp=speed) def stopMotor(motor): try: motor.stop() except: print("Unexpected error:", sys.exc_info()[0]) def stop():
# This script should be run on the Ev3 P-brick on the Arm brick # It is designed to connect to a web socket and move based on incoming messages from socketIO_client import SocketIO import ev3dev.ev3 as ev3 from time import sleep # Assigns a variable for the claw motor claw = ev3.Motor('outD') # Assigns a variable for the joint motor joint = ev3.LargeMotor('outC') # Assigns a variable for the rotor joint motor rotor = ev3.LargeMotor('outB') # Uses the SocketIO library to connect to the web socket socket = SocketIO("https://a219f029.ngrok.io") # Called when a GrabIntent or ReleaseIntent is sent from the web socket # This function delegates and calls which function should act on the command def clawCommand(action): # Prints out the call and action for testing print('Claw command : ' + action) # Delegating function based on action variable if (action == "grab"): closeClaw() else: openClaw() # Called when the TurnArmIntent is sent from the web socket def armCommand(direction):
from ev3dev.auto import * import ev3dev.ev3 as ev3 from ev3dev.ev3 import TouchSensor from ev3dev.ev3 import ColorSensor COL_VALUE = 50 SPEED = 250 FW = 560 BACK = -140 TURN = 242 map = [] A = ev3.LargeMotor('outA') B = ev3.LargeMotor('outB') C = ev3.Motor('outC') ts = TouchSensor() #~ us = UltrasonicSensor() #~ us.mode='US-DIST-CM' # Put the US sensor into distance mode. cl = ColorSensor() cl.mode='COL-REFLECT' bt = Button() #~ gy = GyroSensor() #~ gy.mode='GYRO-ANG' # Put the gyro sensor into ANGLE mode. def led_ready(): Leds.all_off() def led_start(): Leds.set_color(Leds.LEFT, Leds.GREEN)
def __init__(self, port): self.motor = ev3.Motor(port)
ptc.ParameterizedTestCase.parameterize(TestTachoMotorStateValue, param=params)) suite.addTest( ptc.ParameterizedTestCase.parameterize(TestTachoMotorStopActionValue, param=params)) suite.addTest( ptc.ParameterizedTestCase.parameterize(TestTachoMotorStopActionsValue, param=params)) suite.addTest( ptc.ParameterizedTestCase.parameterize(TestTachoMotorTimeSpValue, param=params)) suite.addTest( ptc.ParameterizedTestCase.parameterize(TestTachoMotorDummy, param=params)) if __name__ == '__main__': for k in motor_info: file = open('/sys/class/lego-port/port4/set_device', 'w') file.write('{0}\n'.format(k)) file.close() time.sleep(0.5) params = {'motor': ev3.Motor('outA'), 'port': 'outA', 'driver_name': k} suite = unittest.TestSuite() AddTachoMotorParameterTestsToSuite(suite, k, params) print('-------------------- TESTING {0} --------------'.format(k)) unittest.TextTestRunner(verbosity=1, buffer=True).run(suite)
#!/usr/bin/env python3 import ev3dev.ev3 as ev3 from ev3dev.ev3 import * from time import sleep mtrEsquerdo = ev3.LargeMotor('outA') mtrDireito = ev3.LargeMotor('outB') m_garra = ev3.Motor('outC') cl = ev3.ColorSensor('in1') cl.mode='COL-AMBIENT' def acelerar(): mtrEsquerdo.run_timed(time_sp=500, speed_sp=-500, stop_action='brake') mtrDireito.run_timed(time_sp=500, speed_sp=-500, stop_action='brake') mtrEsquerdo.wait_while('running') mtrDireito.wait_while('running') while True: acelerar()
import ev3dev.ev3 as ev3 import socket import time send_to_address = '172.16.10.157' send_to_port = 50001 ts = ev3.TouchSensor('in1') mA = ev3.Motor('outA') mD = ev3.Motor('outC') def stop(): mA.stop() mD.stop() stop() usL = ev3.UltrasonicSensor('in3') usR = ev3.UltrasonicSensor('in2') usC = ev3.UltrasonicSensor('in4') def forward(): mA.run_forever(duty_cycle_sp=50) mD.run_forever(duty_cycle_sp=50)
def stop_motor(): m = ev3.Motor('outA') if m.connected: m.stop(stop_action='brake') def move_motor_by_dist(motor, dist, speed): if motor.connected: # convert to cm and then to deg angle = int(cm_to_deg(float(dist) / 10)) motor.run_to_rel_pos( position_sp=angle, speed_sp=speed, ) else: print('[ERROR] No motor connected to ' + str(motor)) move_motor_by_dist(ev3.Motor('outA'), DISPLACEMENT, SPEED) while not motor_ready(ev3.Motor('outA')): decoded_ISBN, offset = vision.read_QR(camera) print(str(decoded_ISBN)) if decoded_ISBN is not None and offset < TOLERABLE_OFFSET: stop_motor() print("HURRAY") else: print("CRAP")
#!/usr/bin/python3 import ev3dev.ev3 as ev3 import time motorHand = ev3.Motor('outA') motorLeft = ev3.LargeMotor('outB') motorRight = ev3.LargeMotor('outC') motorLeft.reset() motorRight.reset()
def test_time_sp_min_positive(self): self._param['motor'].time_sp = 1 self.assertEqual(self._param['motor'].time_sp, 1) def test_time_sp_large_positive(self): self._param['motor'].time_sp = 1000000 self.assertEqual(self._param['motor'].time_sp, 1000000) def test_time_sp_after_reset(self): self._param['motor'].time_sp = 1 self._param['motor'].command = 'reset' self.assertEqual(self._param['motor'].time_sp, 0) ev3_params = { 'motor': ev3.Motor('outA'), 'port': 'outA', 'driver_name': 'lego-ev3-l-motor', 'commands': ['run-forever', 'run-to-abs-pos', 'run-to-rel-pos', 'run-timed', 'run-direct', 'stop', 'reset'], 'stop_actions': ['coast', 'brake', 'hold'], } evb_params = { 'motor': ev3.Motor('evb-ports:outA'), 'port': 'evb-ports:outA', 'driver_name': 'lego-ev3-l-motor', 'commands': ['run-forever', 'run-to-abs-pos', 'run-to-rel-pos', 'run-timed', 'run-direct', 'stop', 'reset'], 'stop_actions': ['coast', 'brake', 'hold'], } brickpi_params = { 'motor': ev3.Motor('ttyAMA0:MA'), 'port': 'ttyAMA0:MA',
def test_stop_coast_duty_cycles(self): self.initialize_motor() self.run_direct_duty_cycles('coast', [ 0, 20, 40, 60, 80, 100, 66, 33, 0, -20, -40, -60, -80, -100, -66, -33, 0 ]) # Add all the tests to the suite - some tests apply only to certain drivers! def AddTachoMotorRunDirectTestsToSuite(suite, driver_name, params): suite.addTest( ptc.ParameterizedTestCase.parameterize(TestMotorRunDirect, param=params)) if __name__ == '__main__': params = { 'motor': ev3.Motor('outA'), 'port': 'outA', 'driver_name': 'lego-ev3-l-motor' } suite = unittest.TestSuite() AddTachoMotorRunDirectTestsToSuite(suite, 'lego-ev3-l-motor', params) unittest.TextTestRunner(verbosity=1, buffer=True).run(suite)
#!/usr/bin/env python3 # coding = utf-8 ''' Created on 2017/2/24 self-propelled vehicle based on EV3 @author: Mark Hsu ''' import time import ev3dev.ev3 as ev3 ev3.Sound.speak("Let's go!") time.sleep(2) motorRight = ev3.Motor('outA') #motorRight.run_timed(time_sp=1000, speed_sp=500) motorLeft = ev3.Motor('outC') #motorLeft.run_timed(time_sp=1000, speed_sp=500) usLeft = ev3.UltrasonicSensor('in4') usRight = ev3.UltrasonicSensor('in2') touch = ev3.TouchSensor() color = ev3.ColorSensor() #ir = ev3.InfraredSensor() #while True: # print(ir.proximity) # print('Right: {} \t Left: {}'.format(usRight.distance_centimeters, usLeft.distance_centimeters))
def stop_motor(): m = ev3.Motor('outA') if m.connected: m.stop(stop_action='brake')
# Mqtt Support https://www.eclipse.org/paho/clients/python/ # pip3 install paho-mqtt import paho.mqtt.client as mqtt import time import helper import sys import json import ev3dev.ev3 as ev3 import threading sensor = hubAddress = deviceId = sharedAccessKey = owmApiKey = owmLocation = None grab_motor = ev3.Motor('outA') left_motor = ev3.Motor('outB') right_motor = ev3.Motor('outC') def config_defaults(): global sensor, hubAddress, deviceId, sharedAccessKey, owmApiKey, owmLocation print('Loading default config settings') def config_load(): global sensor, hubAddress, deviceId, sharedAccessKey, owmApiKey, owmLocation try: if len(sys.argv) == 2: print('Loading {0} settings'.format(sys.argv[1])) config_data = open(sys.argv[1]) config = json.load(config_data)
# Utility Functions def load_config(ini_path): config = configparser.ConfigParser() config.read(ini_path) return config['config']['ip'], int(config['config']['port']) # ev3 Setting # ----------------------------------------------------------------------- # Sensor rConv1EntrySensor = ev3.UltrasonicSensor('in1') rConv2EntrySensor = ev3.UltrasonicSensor('in2') # Motor rconv1_motor = ev3.Motor('outA') rconv2_motor = ev3.Motor('outB') rconv_stopper_motor = ev3.Motor('outC') rconv_push_motor = ev3.Motor('outD') # ev3 Name ev3_name = 'ev3_4' # ----------------------------------------------------------------------- # Socket Setting ip, port = load_config(ev3_name + '.ini') address = (ip, port) # Connecting ev3_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ev3_socket.connect(address)
def __init__(self): self.M_ESQUERDO = ev3.LargeMotor('outA') self.M_DIREITO = ev3.LargeMotor('outB') self.M_GARRA = ev3.Motor('outC')
#!/usr/bin/env python3 from sys import argv import time import ev3dev.ev3 as ev3 lm = ev3.Motor("outA") rm = ev3.Motor("outD") def forward(duration): t = float(dist_convert(duration)) #s = int(speed) lm.reset() rm.reset() lm.run_to_rel_pos(position_sp=t * 1000, speed_sp=120, stop_action="coast") rm.run_to_rel_pos(position_sp=t * 1000, speed_sp=120, stop_action="coast") lm.wait_while('running') rm.wait_while('running') time.sleep(2) lm.reset() rm.reset() def turn_right(duration): #sl = int(speed_left) #sr = int(speed_right) t = turn_convert(int(duration)) lm.reset() rm.reset() lm.reset() rm.reset()
import os import sys import ev3dev.ev3 as ev3 import threading robot_joint_1_motor = ev3.Motor('outA') robot_joint_2_motor = ev3.Motor('outB') robot_hand_motor = ev3.Motor('outC') # robot_joint_1_motor = ev3.Motor('outA') # robot_joint_2_motor = ev3.Motor('outB') # robot_hand_motor = ev3.Motor('outC') # robot_hand_zero_point = ev3_2.robot_hand_zero_point # robot_elbow_zero_point = ev3_2.robot_elbow_zero_point # robot_base_zero_point = ev3_2.robot_base_zero_point def elbow_ini(robotJoint2TargetSpeed, robot_elbow_zero_point): robot_joint_2_motor.run_to_abs_pos(speed_sp=robotJoint2TargetSpeed, position_sp=robot_elbow_zero_point, stop_action='hold') robot_joint_2_motor.wait_while('running') # elbow up to ini def hand_ini(robotHandTargetSpeed, robot_hand_zero_point): robot_hand_motor.run_to_abs_pos(speed_sp=robotHandTargetSpeed, position_sp=robot_hand_zero_point, stop_action='hold')