class set_arm_control(): def __init__(self,RELAY_PIN=12): self.arm = SwiftAPI() self.arm.get_power_status() self.RELAY_PIN = RELAY_PIN self.arm.reset() #機械手臂進行初始化動作 def set_arm_origin(self): self.arm.waiting_ready() self.arm.set_position(200, 0, 170, speed=100000) # 機械手臂設定(x, y, z)座標移動 def set_arm_move(self, x, y, z): self.arm.set_position(x, y, z, speed=100000) # 機械手臂切斷連線 def arm_disconnect(self): self.arm.disconnect() def get_position(self): print(self.arm.get_position()) #初始設定繼電器 def origin_pump(self): GPIO.setmode(GPIO.BOARD) # 指定模式BOARD 啟用RPi板子相對應之腳位編號 GPIO.setwarnings(False) # 避免出現警告 GPIO.setup(self.RELAY_PIN, GPIO.OUT) # 設定pin腳為輸出 #打開幫浦=開啟繼電器(使電流流通) def start_pump(self): GPIO.output(self.RELAY_PIN, 0) #關閉幫浦=關閉繼電器(使電流不能流通) def close_pump(self): GPIO.output(self.RELAY_PIN, 1)
class uArmSwift: def __init__(self): self.swift = SwiftAPI(filters={'hwid': 'USB VID:PID=2341:0042'}, cmd_pend_size=2, callback_thread_pool_size=1) if not self.swift.connected: print('lose connect') self.swift.waiting_ready() device_info = self.swift.get_device_info() print(device_info) firmware_version = device_info['firmware_version'] if firmware_version and not firmware_version.startswith( ('0.', '1.', '2.', '3.')): self.swift.set_speed_factor(0.00005) self.swift.set_mode(0) self.speed = 500000 self.swift.set_wrist(angle=90) self.wristAngle = self.swift.get_servo_angle(0, timeout=10) def set_position(self, x=100, y=0, z=100, wait=False): self.swift.set_position(x, y, z, speed=self.speed, wait=wait) def set_polar(self, stretch, rotation, height, wait=False): self.swift.set_polar(stretch, rotation, height, speed=self.speed, wait=wait) def set_servo_angle(self, num, angle, wait=False): if num < 0 and num > 3: print("num is wrong") self.swift.set_servo_angle(num, angle, wait, speed=self.speed, wait=wait) def set_wrist(self, angle=90, wait=False): # 第四电机 self.swift.set_wrist(angle, wait) def set_pump(self, on=False): self.swift.set_pump(on) def set_buzzer(self, freq=1000, duration=1, wait=False): self.swift.set_buzzer(freq, duration, wait) def get_position(self): return self.swift.get_position() def get_servo_angle(self, id=0): return self.swift.get_servo_angle(id, timeout=10) def is_moving(self): return self.swift.get_is_moving() def disconnect(self): self.swift.disconnect()
swift = SwiftAPI(filters={'hwid': 'USB VID:PID=2341:0042'}) # swift2 = SwiftAPI(filters={'hwid': 'USB VID:PID=2341:0042'}) # swift3 = SwiftAPI(filters={'hwid': 'USB VID:PID=2341:0042'}) swift.waiting_ready() device_info = swift.get_device_info() print(swift.port, device_info) firmware_version = device_info['firmware_version'] if firmware_version and not firmware_version.startswith(('0.', '1.', '2.', '3.')): swift.set_speed_factor(0.00001) swift.set_servo_detach() input('A4') swift.set_servo_attach() pos = swift.get_position() print(pos); bias = 23; swift.reset(speed=10000000); seqs = ["F", "G", "E", "A", "D", "G", "C", "C"] # seqs = ["C", "C", "D", "D", "E", "E", "D", "D"] count = 0; while True: count = count + 1 seq = seqs[count % len(seqs)] print(seq);
class uarmRobotClass(object): def __init__(self): self.x_pos = 0 self.y_pos = 0 self.tcp_rot = 0 self.z_pos = 0 self.pick = 0 self.connect = 0 self.swift = SwiftAPI(filters={'hwid': 'USB VID:PID=2341:0042'}) self.swift.waiting_ready(timeout=3) self.swift.set_speed_factor(0.5) self.swift.waiting_ready(timeout=3) self.swift.disconnect() def openPort(self): self.swift.connect() #swift = SwiftAPI(filters={'hwid': 'USB VID:PID=2341:0042'}) self.swift.waiting_ready(timeout=3) self.swift.set_speed_factor(0.5) self.swift.waiting_ready(timeout=3) self.swift.set_position(150, 0, 50, wait=True) def closePort(self): self.swift.disconnect() self.swift.waiting_ready(timeout=3) def move(self): Index = 0 pick = 0 connect = 0 while True: if (dummy == False) and (connect == 0) and (self.connect == 1): self.openPort() ret = self.swift.get_position(wait=True) print("ret values %d, %d, %d" % (ret[0], ret[1], ret[2])) x_pos = ret[0] y_pos = ret[1] tcp_rot = ret[2] print("connected") connect = 1 if (dummy == False) and (connect == 1) and (self.connect == 0): self.closePort() connect = 0 print("disconnnected") if (self.x_pos != 0) or (self.y_pos != 0) or (self.tcp_rot != 0) or (self.z_pos != 0) or (self.pick != 0) or (self.connect != 0): if logLevel > 1: print("index = %d: x_pos = %d; y_pos = %d; z_pos = %d; tcp_rot = %d; pick = %d; connect = %d" % (Index, self.x_pos, self.y_pos, self.z_pos, self.tcp_rot, self.pick, self.connect)) Index = Index + 1 if (dummy == False) and (connect == 1) and ((self.x_pos != 0) or (self.y_pos != 0) or (self.tcp_rot != 0) or (self.z_pos != 0)): self.swift.set_position(x=self.x_pos, y=self.y_pos, z=self.z_pos, wait=True, relative=True); ret = self.swift.get_position(wait=True) if logLevel > 0: print("ret values %d, %d, %d" % (ret[0], ret[1], ret[2])) if (dummy == False) and (pick == 0) and (self.pick != 0): self.swift.set_pump(on=True) pick = 1 if (dummy == False) and (pick == 1) and (self.pick == 0): self.swift.set_pump(on=False) pick = 0 time.sleep(0.001);
class uArm(): def __init__(self): self.scope = 10 self.x0 = 160 self.y0 = 0 self.swift = SwiftAPI(filters={'hwid':'USB VID:PID=2341:0042'}) self.swift.waiting_ready(timeout=3) # self.swift.set_speed_factor(0.005) # if you change this, be prepared for different movements! self.swift.set_mode(mode=0) time.sleep(0.5) self.swift.set_servo_angle(angle=90) self.swift.set_wrist(angle=90) self.swift.set_position(x=200,y=0,z=20) # start it off with a salute self.swift.set_buzzer(frequency=1000, duration=1) # signal ready self.lstValidCharSet = ['?','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',\ '-','0','1','2','3','4','5','6','7','8','9'] self.lstLetter = [self.QuestionMark, self.LetterA, self.LetterB, self.LetterC, self.LetterD, self.LetterE, self.LetterF,\ self.LetterG, self.LetterH, self.LetterI, self.LetterJ, self.LetterK, self.LetterL, self.LetterM, self.LetterN,\ self.LetterO, self.LetterP, self.LetterQ, self.LetterR, self.LetterS, self.LetterT, self.LetterU, self.LetterV,\ self.LetterW, self.LetterX, self.LetterY, self.LetterZ, self.Hyphen, self.Number0, self.Number1, self.Number2,\ self.Number3, self.Number4, self.Number5, self.Number6, self.Number7, self.Number8, self.Number9] def __del__(self): input("PLEASE SUPPORT uARM ARM!!, then strike ENTER to continue ...") self.swift.set_buzzer(frequency=600, duration=2) self.swift.set_position(x=200,y=0,z=20) self.swift.flush_cmd() self.swift.disconnect() del self.swift self.swift = None def arm(self): """ Using this method to allow raw access to the uArm if required """ return self.swift def insert_pen(self): self.swift.set_buzzer(frequency=1000, duration=0.5) # signal ready self.swift.set_servo_angle(angle=90) time.sleep(0.5) self.swift.set_wrist(angle=90) time.sleep(0.5) self.swift.set_position(x=200,y=0,z=0) while (self.swift.get_is_moving()): continue input("Set pen in universal holder, then strike ENTER to continue ...") self.swift.set_position(x=200,y=0,z=10) return def pen_up(self): while (self.swift.get_is_moving()): continue x, y, z = self.swift.get_position() self.swift.set_position(x, y, 10) time.sleep(0.5) return 10 def pen_down(self): while (self.swift.get_is_moving()): continue x, y, z = self.swift.get_position() self.swift.set_position(x, y, 0) time.sleep(0.5) return 0 def setScope(self, strName): """ based upon the length of strName, determine the scope (char width) and starting X, Y positions assuming that the center of the page is 160,0 x extent is 110 - 210, y extent 80 - (-80) (x axis is PARALLEL to the arm, short edge of the paper) """ if type(strName) == str: strName = strName[:26] # going to truncate user input to a 26 characters max intLenName = len(strName) if (intLenName < 4): self.scope = 40.0 # keeping it real else: self.scope = math.floor(160.0/(intLenName * 1.1)) self.x0 = 160 - (0.5 * self.scope) self.y0 = self.scope * intLenName * 1.1 / 2 return def LetterSelect(self, c): """ given char c, return the plotting function index 0 resolves to the question mark character """ index = 0 if type(c) == str: if c == ' ': return self.SpaceBar else: c = c.upper() if c in self.lstValidCharSet: index = self.lstValidCharSet.index(c) - self.lstValidCharSet.index('A') + 1 # 0th item is '?' # if c in ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']: # index = ord(c) - ord('A') + 1 # using question mark as the 0th index item return self.lstLetter[index] # return the function to use
from uarm.wrapper import SwiftAPI swift = SwiftAPI() swift.waiting_ready(timeout=10) swift.set_position(140, 0, 10, wait=True) swift.set_servo_detach() test1 = swift.get_position() print(test1) test2 = swift.get_servo_angle() print(test2) test = input( "now the uArm is detached, that mean you can freely move the arm without the servo-motors blocking it. for the next step, deplace the arm in another position than before and type enter to continue" ) test1 = swift.get_position() print(test1) test2 = swift.get_servo_angle() print(test2) test = input( "has you can see, the arm has moved but the position is the same : after detached the arm, if you move it you can only have the servo-motors angles. type enter to continue BUT be careful : the arm will be attach so don't block it in any way." ) swift.set_servo_attach() swift.set_position(140, 0, 50, wait=True)
class uart: available_pixel = {} #rgb values of all the paints swift = None #robot arm object device_info = None firmware_version = None image = None #image you're trying to paint canvas = None #image of the canvas as you're working on it canvas_corners = None #points of the four corners of the canvas (in robot arm coords) ptransform = None #contains the warped image of M = None #transformation matrix xScale = None yScale = None # # __init__ # im = the image you're trying to paint # pixels = the dictionary of colors you have access to # initialized = a list of booleans determining which values you will initialize # [ True = available_pixel uses pixels parameter otherwise use defaults, # True = set swift to SwiftAPI object otherwise set them to None, # True = set image to a blank white 200x200 image, # True = calibrate canvas_corners using setFourCorners otherwise set to a preset # True = set ptransform using the webcam # ] # def __init__(self, im, pixels, initialized): if initialized[0]: self.available_pixel = pixels else: self.available_pixel = {'red':[255,0,0], 'green':[0,255,0], 'blue':[0,0,255],'magenta':[255,0,255], 'tomato':[255,99,71], 'lawn green':[124,252,0]} if initialized[1]: self.swift = SwiftAPI(filters={'hwid': 'USB VID:PID=2341:0042'}) self.device_info = self.swift.get_device_info() self.firmware_version = self.device_info['firmware_version'] self.swift.set_mode(0) if initialized[2]: self.image = im if initialized[3] and initialized[1]: print("moving") self.swift.set_position(x=150, y=0, z=50, speed = 10000, cmd = "G0") # self.swift.set_wrist(20) # time.sleep(1) # self.swift.set_wrist(90) print("Setting four corners; input tl, tr, bl or br") self.canvas_corners = self.setFourCorners() else: self.swift.set_position(x=150, y=0, z=50, speed = 10000, cmd = "G0") self.canvas_corners = [ [263,50,103], #tl [263,-50,103],#tr [241,50,-12],#bl [241,-50,-12]]#br print("Setting four corners to default coordinates") if initialized[4]: _, cap = cv2.VideoCapture(0).read() self.ptransform = perspective.PerspectiveTransform(cap) self.M = self.get_m(200,200) self.xScale = self.get_scale(len(im[0]),[self.canvas_corners[0],self.canvas_corners[1]]) self.yScale = self.get_scale(len(im),[self.canvas_corners[0],self.canvas_corners[2]]) print("Arm all set up!") # # new xy to xyz function using algebra/geometry # def xy_to_xyz2(self, xy): #print("xy", xy) #print("xscale", self.xScale) #print("yscale", self.yScale) out = np.add(np.multiply(xy[0],self.xScale) + np.multiply(xy[1],self.yScale), self.canvas_corners[0]) print(out) return out # # GET SCALE # def get_scale(self, pix, corners): dif = np.subtract(corners[0], corners[1]) return -(dif/pix) # # HEAT MAP # def generate_heatmap(self): image = self.image.astype(dtype='int32') canvas = self.ptransform.warped.astype(dtype='int32') subtraction = np.subtract(image,canvas) print(subtraction) heatmap = np.full(im.shape,255, dtype='uint8') print(heatmap.shape) for i in range(subtraction.shape[0]): for j in range(subtraction.shape[1]): if (subtraction[i][j] < 0): heatmap[i][j][0] -= abs(subtraction[i][j]) heatmap[i][j][1] -= abs(subtraction[i][j]) elif (subtraction[i][j] > 0): heatmap[i][j][2] -= abs(subtraction[i][j]) heatmap[i][j][1] -= abs(subtraction[i][j]) return heatmap # # GETS CLOSEST COLOR # def get_closest_color(self, chosen_pixel): available_pixel = self.available_pixel distances = [] for key, value in available_pixel.items(): a1 = np.asarray(value) c1 = np.asarray(chosen_pixel) curr_dist = np.linalg.norm(a1 - c1) distances += [curr_dist] if(curr_dist == min(distances)): curr_key = key return curr_key # # move_to_file # def move_to_file(self, filename): var = [] count = 0 lines = open(filename, "r").read().split('\n') x,y,z,f,angle = 0 moveArm,moveWrist = False for i in range(len(lines)): for word in lines[i].split(' '): if(word is 'G0'): moveArm = True if(word[0] is 'X'): x = float(word[1:]) elif(word[0] is 'Y'): y = float(word[1:]) elif(word[0] is 'Z'): z = float(word[1:]) elif(word[0] is 'F'): f = float(word[1:]) elif(word is 'WA'): moveWrist = True angle = float(word[1:]) if(moveArm): self.swift.set_position(x=x, y=y, z=z, speed =f, cmd = "G0") moveArm = False time.sleep(1) if(moveWrist): self.swift.set_wrist(angle) moveWrist = False time.sleep(1) coordinates.close() # # SETTING FOUR CORNERS # def setFourCorners(self): speed_s = 10000 delay = 1 cmd_s = 'G0' todo = 4 coords = [[], [], [], []] while todo >0: key = input() if key == "tr": newCoord = self.swift.get_position() coords[1] = newCoord todo -= 1 print("Top right coordinate saved as ", newCoord) elif key == "tl": newCoord = self.swift.get_position() coords[0] = newCoord todo -= 1 print("Top left coordinate saved as", newCoord) elif key == "bl": newCoord = self.swift.get_position() coords[2] = newCoord todo -= 1 print("Bottom left coordinate saved as", newCoord) elif key == "br": newCoord = self.swift.get_position() coords[3] = newCoord todo -= 1 print("Bottom right coodirnate saved as", newCoord) return coords # # SAVED COORDS TO FILE # def saveCoordsToFile(self, fn): delay = 1 coords = [] while True: key = input() if key == "save": newCoord = swift.get_position() coords.append(newCoord) print("New coordinate saved as" + str(newCoord)) elif key == "done": break elif key.isdigit(): coords.append(int(key)) if os.path.exists(fn + ".uar"): os.remove(fn + ".uar") file = open(fn + ".uar", "w+") for c in coords: if not check(c): file.write("G0 X%f Y%f Z%f F5000\n" %(c[0], c[1], c[2])) else: self.set_wrist(c) file.write("WA " %(c)) coordinates.close() moveTo(fn + ".uar") return coords def check(inp): try: num_float = float(inp) return True except: return False # # GET M # def get_m(self, width, height): A = np.transpose(self.canvas_corners) print(A) B = [[0,0,1],[width,0,1],[0,height,1],[width,height,1]] B = np.transpose(B) print(B) pinvB = np.linalg.pinv(B) print(pinvB) M = np.matmul(A, np.linalg.pinv(B)) print(M) return M # # xytoxyz # def xy_to_xyz(self,xy): xyz = [xy[0],xy[1],1] xyz = np.transpose(xyz) return np.matmul(self.M,xyz) # # go to position # def go_to_position(self, xyz, f): print('going to : ', xyz) self.swift.set_position(x=xyz[0], y=xyz[1], z=xyz[2], speed = f, cmd = "G0") #: time.sleep(1) # # draw a line # # start and end: [x,y] def draw_line(self, start, end): startxyz = self.xy_to_xyz2(start) endxyz = self.xy_to_xyz2(end) start_pre = [startxyz[0]-20, startxyz[1], startxyz[2]] end_post = [endxyz[0]-20, endxyz[1], endxyz[2]] print("going to start pre") self.go_to_position(start_pre, 10000) print("going to start") self.go_to_position(startxyz, 5000) print("going to end") self.go_to_position(endxyz, 5000) print("going to end post") self.go_to_position(end_post, 10000) # # # draws a line, by moving across a list of points # def draw_line2(self, points): startxyz = self.xy_to_xyz2(points[0]) endxyz = self.xy_to_xyz2(points[-1]) start_pre = [startxyz[0]-5, startxyz[1], startxyz[2]] end_post = [endxyz[0]-5, endxyz[1], endxyz[2]] #print("going to start pre") self.go_to_position(start_pre, 10000) for point in points: point_xyz = self.xy_to_xyz2(point) self.go_to_position(point_xyz, 5000) #print("going to end post") self.go_to_position(end_post, 10000) # # # draws a line, by moving across a list of points # does NOT go to pre and post painting position # def draw_line3(self, points): startxyz = self.xy_to_xyz2(points[0]) endxyz = self.xy_to_xyz2(points[-1]) #print("going to start pre") #self.go_to_position(start_pre, 10000) for point in points: point_xyz = self.xy_to_xyz2(point) self.go_to_position(point_xyz, 5000)
class UArmHandler(object): def __init__(self, ui): super(UArmHandler, self).__init__() self.ui = ui self.arm = None self.port = None self.cmd_que = queue.Queue(100) self.cmd_thread = XArmThread(self.cmd_que, check=False) self.cmd_thread.signal.connect(self.run_cmd) self.cmd_thread.start() self.report_que = queue.Queue() self.report_thread = XArmThread(self.report_que, check=True) self.report_thread.signal.connect(self.update_ui) self.report_thread.start() def run_cmd(self, item): try: if self.arm and self.arm.connected: func = getattr(self.arm, item['cmd']) # log(item['cmd']+':', func(*item.get('args', []), **item.get('kwargs', {}))) ret = func(*item.get('args', []), **item.get('kwargs', {})) if item['cmd'] == 'get_position' and isinstance( ret, list) and len(ret) >= 3: self.report_que.put({ 'type': 'location', 'item': { 'position': ret, 'angles': None } }) elif item['cmd'] == 'get_polar' and isinstance( ret, list) and len(ret) >= 3: self.report_que.put({ 'type': 'location', 'item': { 'position': [None, None, None, *ret], 'angles': None } }) elif item['cmd'] == 'get_servo_angle' and isinstance( ret, list) and len(ret) >= 3: self.report_que.put({ 'type': 'location', 'item': { 'position': None, 'angles': ret } }) elif item['cmd'] == 'get_device_info': self.report_que.put({'type': 'info', 'item': ret}) elif item['cmd'] == 'get_mode' or item['cmd'] == 'set_mode': self.report_que.put({ 'type': 'mode', 'item': { 'mode': ret } }) # if isinstance(ret, int) and ret == TCP_OR_JOINT_LIMIT: # self.ui.reset_flag() logger.debug('cmd: {}, ret:{}, args: {}, kwargs: {}'.format( item['cmd'], ret, item.get('args', []), item.get('kwargs', {}))) else: self.cmd_que.queue.clear() self.report_connected_callback({'connected': False}) logger.debug('cmd: {}, ret: xArm is not connected'.format( item['cmd'])) except: pass def connect(self, port): try: logger.debug('try connect to {}'.format(port)) if self.arm and self.arm.connected: logger.info('disconnect from {}'.format(self.port)) self.arm.disconnect() except Exception as e: print(e) threading.Thread(target=self.connnect_thread, args=(port, ), daemon=True).start() def connnect_thread(self, port): try: self.port = port self.arm = SwiftAPI(port=port, do_not_open=True) self.arm.connect() if not self.arm.connected: time.sleep(0.5) self.arm.waiting_ready() self.report_connected_callback({'connected': True}) device_info = self.arm.get_device_info() self.report_que.put({'type': 'info', 'item': device_info}) mode = self.arm.get_mode() self.report_que.put({'type': 'mode', 'item': {'mode': mode}}) position = self.arm.get_position() if isinstance(position, list) and len(position) >= 3: self.report_que.put({ 'type': 'location', 'item': { 'position': position, 'angles': None } }) polar = self.arm.get_polar() if isinstance(polar, list) and len(polar) >= 3: self.report_que.put({ 'type': 'location', 'item': { 'position': [None, None, None, *polar], 'angles': None } }) angles = self.arm.get_servo_angle() if isinstance(angles, list) and len(angles) >= 3: self.report_que.put({ 'type': 'location', 'item': { 'position': None, 'angles': angles } }) return True except Exception as e: # print(e) self.report_connected_callback({'connected': False}) def disconnect(self): try: if self.arm and self.arm.connected: self.arm.disconnect() self.report_connected_callback({'connected': False}) # logger.info('diconnect from {}'.format(self.addr)) except Exception as e: print(e) def update_ui(self, data): item = data['item'] if data['type'] == 'timeout': if not self.arm or not self.arm.connected: self.ui.update_connect_status(False) elif data['type'] == 'connect': self.ui.update_connect_status(item['connected']) elif data['type'] == 'location': pos = item['position'] angles = item['angles'] if angles: self.ui.axis_ui.update_joints(angles) if pos: self.ui.cartesian_ui.update_cartesians(pos) elif data['type'] == 'info': self.ui.update_device_info(item) elif data['type'] == 'mode': self.ui.update_mode(item['mode']) def report_connected_callback(self, item): self.report_que.put({'type': 'connect', 'item': item}) def put_cmd_que(self, item): self.cmd_que.put(item)
ret = swift.get_power_status() print('power status: {}'.format(ret)) ret = swift.get_device_info() print('device info: {}'.format(ret)) ret = swift.get_limit_switch() print('limit switch: {}'.format(ret)) ret = swift.get_gripper_catch() print('gripper catch: {}'.format(ret)) ret = swift.get_mode() print('mode: {}'.format(ret)) print('set mode:', swift.set_mode(1)) ret = swift.get_mode() print('mode: {}'.format(ret)) ret = swift.get_servo_attach(servo_id=2) print('servo attach: {}'.format(ret)) ret = swift.get_servo_angle() print('servo angle: {}'.format(ret)) def print_callback(ret, key=None): print('{}: {}'.format(key, ret)) swift.get_polar(wait=False, callback=functools.partial(print_callback, key='polar')) swift.get_position(wait=False, callback=functools.partial(print_callback, key='position')) swift.flush_cmd() swift.disconnect()
class MinionArm: def __init__(self): self.swift = SwiftAPI(filters={'hwid': 'USB VID:PID=2341:0042'}) self.swift.waiting_ready() device_info = self.swift.get_device_info() print(device_info) firmware_version = device_info['firmware_version'] if firmware_version and not firmware_version.startswith( ('0.', '1.', '2.', '3.')): self.swift.set_speed_factor(0.0005) self.speed = 110000 self.test() self.board = "right" def test(self): # self.swift.set_buzzer(frequency=1000, duration=0.5, wait=True) self.swift.reset(wait=True, speed=self.speed) self.move(1250, 0, 150, self.speed) print(self.swift.get_position()) # self.swift.set_buzzer(frequency=1000, duration=0.5, wait=True) def home(self): print("going home") self.swift.set_position(x=150, y=0, speed=self.speed * 0.5, wait=True) self.move(145, 0, 100, self.speed * 1.5) time.sleep(2) # self.swift.set_buzzer(frequency=1000, duration=0.5, wait=True) def rest(self): print("going to rest position") self.swift.set_position(x=150, speed=self.speed * 0.5, wait=True) self.swift.set_position(x=125, y=0, speed=self.speed * 0.5, wait=True) self.move(125, 0, 40, self.speed * 0.5) time.sleep(2) self.swift.set_buzzer(frequency=1000, duration=0.5) def move(self, x, y, z, speed): self.swift.set_position(x, y, z, speed, wait=True) def flip(self): print("flipping") # self.home() self.swift.set_buzzer(frequency=1000, duration=0.5, wait=True) if self.board == "right": self.flip_left() self.board = "left" else: self.flip_right() self.board = "right" self.home() self.swift.set_buzzer(frequency=500, duration=1.0, wait=True) def flip_left(self): self.move(180, 0, 150, self.speed) self.move(240, 0, 150, self.speed) # self.move(220, 10, 140, self.speed*.2) self.move(220, 40, 150, self.speed * .2) # self.move(220, 40, 110, self.speed*.2) # self.move(220, 60, 100, self.speed*.2) self.move(220, 50, 30, self.speed * .2) time.sleep(1) self.move(180, 50, 20, self.speed * .2) time.sleep(2) def flip_right(self): self.move(180, 0, 150, self.speed) self.move(240, -10, 150, self.speed) # self.move(220, -20, 140, self.speed*.2) self.move(220, -40, 150, self.speed * .2) # self.move(220, -50, 110, self.speed*.2) # self.move(220, -60, 100, self.speed*.2) self.move(220, -60, 20, self.speed * .2) self.move(180, -50, 20, self.speed * .2) time.sleep(2) def move_to_galton_cal_pos(self): self.move(180, 0, 150, self.speed) self.move(240, 0, 150, self.speed) wait = input("waiting") self.home() def disconnect(self): self.swift.disconnect()