def main(): print("Starting MyoConnect") # Instantiate myo and listener objects myo = Myo() listener = SendPoseListener() try: # Connect myo and listner myo.connect() myo.add_listener(listener) print("listener added") # Vibrate armband when connected myo.vibrate(VibrationType.SHORT) print("vibrated") # Run myo while True: myo.run() # Error handling except KeyboardInterrupt: pass except ValueError as ex: print(ex) finally: myo.safely_disconnect() print("Finished")
def main(): print('Myo Heating UP') # saving the pose in variable listener = PrintPoseListener() # access to myo via variable obj myo = Myo() try: # connection to myo myo.connect() # adding pose to myo myo.add_listener(listener) #vibration on start myo.vibrate(VibrationType.SHORT) #keep running until program we exit while True: myo.run() except KeyboardInterrupt: pass except ValueError as ex: print(ex) finally: myo.safely_disconnect() print('Myo App is ended.')
def main(): print('Start Myo for Linux') param = 0 if len(sys.argv) > 1: param = sys.argv[1] listener = PrintPoseListener() if param == 1: listener = EmgListener() myo = Myo() try: myo.connect() myo.add_listener(listener) myo.vibrate(VibrationType.SHORT) while True: x = myo.run() if x != [] or None: print(x) except KeyboardInterrupt: pass except ValueError as ex: print(ex) finally: myo.safely_disconnect() print('Finished.')
def main(): print('Start Myo for Linux') listener = PrintPoseListener() myo = Myo() try: myo.connect() myo.add_listener(listener) myo.vibrate(VibrationType.SHORT) while True: myo.run() except KeyboardInterrupt: pass except ValueError as ex: print(ex) finally: myo.safely_disconnect() print('Finished.')
def main(): print('Start Myo for Linux') listener = PrintPoseListener() myo = Myo() try: myo.connect() myo.add_listener(listener) while True: myo.run() except KeyboardInterrupt: pass except ValueError as ex: print(ex) finally: myo.safely_disconnect() print('Finished.')
def main(): print("### ITECH BIYONIK-EL YAZILIMI ###\n#") print('# Myo yazilimi baslatiliyor') # HAREKET TANIMLAMA LISTENERI if(sys.argv[1] == "0"): listener = PrintPoseListener() elif(sys.argv[1] == "1"): listener = RS232Listener() # MYO NESNESI myo = Myo() try: # MYO BAGLANTI myo.connect() # LISTENER EKLEME myo.add_listener(listener) # BASLANGICTA 3 KISA TITRESIM for i in range(0,3): myo.vibrate(VibrationType.SHORT) # PROGRAM BU DONGU ICINDE CALISIR while True: # myo.run() KOMUTU : HAREKETLERI ALGILAR mPose = myo.run() # myo.run() KOMUTUNDAN "-1" DEGERI DONER ISE # YANI HAREKET DEGERI "UNKNOWN" ISE if(mPose == -1): # GUVENLI CIKIS myo.safely_disconnect() # TEKRAR BAGLANTI myo.connect() # TEKRAR LISTENER EKLE myo.add_listener(listener) # TEKRAR 3 TITRESIM for i in range(0,3): myo.vibrate(VibrationType.SHORT) # KLAVYEDEN DURDURMA except KeyboardInterrupt: pass except ValueError as ex: print(ex) except SerialException: system("usbKapat") sleep(1) system("usbAc") sleep(0.5) main() finally: # GUVENLI CIKIS myo.safely_disconnect() print('# Cikis yapildi.\n#') print("### ITECH BIYONIK-EL YAZILIMI ###")
def main(): print('Start Myo for Intel Edison or any Linux and Mac Complient Devices:') listener = PrintPoseListener() crazy_listner = CrazyFlie_listner() myo = Myo() try: myo.connect() myo.add_listener(listener) myo.add_listener(crazy_listner) myo.vibrate(VibrationType.SHORT) while True: myo.run() except KeyboardInterrupt: pass except ValueError as ex: print(ex) finally: myo.safely_disconnect() print('Finished.')
def main(): rospy.loginfo('Start Myo for Linux') gesture_pub = rospy.Publisher('rover1/wheel_vel', WheelVelocity, queue_size=10) listener = PrintPoseListener() myo = Myo() try: myo.connect() myo.add_listener(listener) while True: myo.run() except KeyboardInterrupt: pass except ValueError as ex: print(ex) finally: myo.safely_disconnect() print('Finished.')
class main(object): def __init__(self, dataType=["emg", "imu"]): self.emgDict = dict() self.numberVoter = 3 self.dataType = dataType self.L = threading.Lock() self.modelFilePath = "emg_1535856299.pkl" def start(self): self.listener = PrintPoseListener(dataType=self.dataType) self.mMyo = Myo() self.getSystermType() try: self.mMyo.connect() self.mMyo.add_listener(self.listener) self.mMyo.vibrate(VibrationType.SHORT) except ValueError as ex: print(ex) # self.getTheModelFileName() self.loadModel() #导入模型 self.mMyo.vibrate(VibrationType.MEDIUM) #震动表示模型导入完成 #获取姿态控制的数据 def getAttitudeControlData(self, roll, pitch, yaw): # print("the roll is :" , roll) # print("the pitch is :" , pitch) if pitch > 0: tempData1 = "up" elif pitch < 0: tempData1 = "down" if roll > 0: tempData2 = "left" elif roll < 0: tempData2 = "right" return tempData1, tempData2 #往文件中写入动作字符串 def writeActionFile(self, fileName="actionTempData.dat", actionStr="rest"): '''将最终的动作写入文件中''' if os.path.exists(fileName) == False: with open(fileName, "w") as f: f.write(actionStr) f.close() # print("write over!!") else: pass #采集线程主程序 def myoRun(self): try: while True: self.mMyo.run() time.sleep(0.001) except KeyboardInterrupt: self.mMyo.safely_disconnect() #获取在线分类结果函数(分类线程函数) def onlineClf(self): try: while True: if "emg" in self.dataType: if self.listener.emgDataCount > self.model.mWinWidth + self.numberVoter - 1: #投票数为其加1 self.listener.emgDataCount = 0 self.L.acquire() self.listener.emgData = np.array(self.listener.emgData, dtype=np.int64) self.listener.emgData = self.listener.emgData.T self.emgDict['one'] = self.listener.emgData self.L.release() self.sample = FeatureSpace( rawDict=self.emgDict, moveNames=[ 'one', ], #动作类别 ChList=[0, 1, 2, 3, 4, 5, 6, 7], #传感器的通道数目 features={ 'Names': self.model.mFeatureList, #定义的特征 'LW': self.model.mWinWidth, #定义的窗宽 'LI': self.model.mSlidingLen }, #定义的窗滑动的步长 one_hot=False, trainPercent=[1, 0, 0] #是否进行onehot处理 ) self.L.acquire() self.getTrainData() actionList = self.model.mModel.predict(self.trainX) self.writeActionFile( actionStr=str(self.getTheAction(actionList))) self.L.release() self.listener.emgData = [] self.emgDict.clear() time.sleep(0.001) else: time.sleep(0.001) except KeyboardInterrupt: pass #The feature space is divided into data sets def getTrainData(self): nDimensions = self.sample.trainImageX.shape[1] #训练集 self.trainX = np.reshape(self.sample.trainImageX, (-1, nDimensions)) self.trainY = np.squeeze(self.sample.trainImageY) #测试集 self.testX = np.reshape(self.sample.testImageX, (-1, nDimensions)) self.testY = np.squeeze(self.sample.testImageY) #评估集 self.validateX = np.reshape(self.sample.validateImageX, (-1, nDimensions)) self.validateY = np.squeeze(self.sample.validateImageY) '''导入已经保存的模型''' def loadModel(self): self.model = joblib.load(self.modelFilePath) self.actionNames = self.model.actionNames def getSystermType(self): '''获得系统平台类型''' self.systermType = platform.system() #投票函数 def getTheAction(self, actionList): tempData = np.array(actionList) counts = np.bincount(tempData) actionNumber = np.argmax(counts) return self.actionNames[actionNumber] #返回定义的动作类别字符串 #获取姿态数据 def getTheAttitudeMain(self): if "imu" in self.dataType: while True: tempStr1, tempStr2 = self.getAttitudeControlData( self.listener.roll, self.listener.pitch, self.listener.yaw) attitudeControlStr = tempStr1 + '+' + tempStr2 # print("the attitude is :" , attitudeControlStr) self.L.acquire() self.writeActionFile(fileName="attitudeTempData.dat", actionStr=attitudeControlStr) self.L.release() time.sleep(0.001) else: time.sleep(0.001) pass '''myo主程序的入口''' def run(self): try: self.mThread = myThread() self.mThread.addThread('onlineClf', self.onlineClf, 0) #加入在线识别动作线程 self.mThread.addThread('getData', self.myoRun, 0) #加入数据采集的线程 self.mThread.addThread('getTheAttitudeMain', self.getTheAttitudeMain, 0) #加入数据采集的线程 self.mThread.runThread() except KeyboardInterrupt: self.mMyo.safely_disconnect() self.mThread.forcedStopThread()
class Arm(object): MOTOR_IDLE_TIME = 2 # seconds WRIST_SPEED = 25 # a scalar on the relative rotation speed for the updateWristRotation() callback # This will create the hand and wrist servos in the arm. This will also create the Myo instance. def __init__(self): # Create the actuators self.wristServo = Servo('wrist') self.handServo = Servo('hand') # Create state variables self.handStatus = 'opened' # args can be 'opened', 'closed' self.handResetTimer = None # Used to turn off the motor after 2 seconds of inactivity self.wristResetTimer = None # Center motors (not needed) # self.openHand() # self.setWristPosition(90) # deg # Create the Myo controller sensor (with callbacks) callbacks = { 'toggleHand': self.toggleHand, 'updateWristRotation': self.updateWristRotation, 'isHandClosed': self.isHandClosed } self.myo = Myo(callbacks) # Kill the script if the myo does not connect on time. killTimer = threading.Timer(5, self.killScript) killTimer.start() # Start the Myo sensor. self.myo.connect() # Kill the kill timer killTimer.cancel() # Become slave to the myo sensor while True: self.myo.run() def setHandTimer(self): # Stop the old timer if it exists if self.handResetTimer: self.handResetTimer.cancel() self.handResetTimer = threading.Timer(Arm.MOTOR_IDLE_TIME, self.handServo.disable) self.handResetTimer.start() def setWristTimer(self): if self.wristResetTimer: self.wristResetTimer.cancel() self.wristResetTimer = threading.Timer(Arm.MOTOR_IDLE_TIME, self.wristServo.disable) self.wristResetTimer.start() def openHand(self): # Open the hand, then disable the servo to save power/heat self.handServo.angle(180) self.handServo.enable() # Set a timer to turn off the servo soon self.setHandTimer() def closeHand(self): # Close the hand, then disable the servo after a few minutes to save power/heat self.handServo.angle(0) self.handServo.enable() # Set a timer to turn off the servo soon self.setHandTimer() def toggleHand(self): if self.handStatus is 'opened': self.closeHand() self.handStatus = 'closed' else: self.openHand() self.handStatus = 'opened' def isHandClosed(self): if self.handStatus is 'closed': return True else: return False def setWristPosition(self, deg): # Each time that this is called self.wristServo.angle(deg) self.wristServo.enable() # turn off the servo after a few seconds self.setWristTimer() def updateWristRotation(self, offsetRadians): # Get the current angle of the servo currentAngle = self.wristServo.getAngle() # Figure out where the servo should go newAngle = currentAngle + offsetRadians * Arm.WRIST_SPEED self.wristServo.angle(newAngle) self.wristServo.enable() # turn off the servo after a few seconds self.setWristTimer() def killScript(self): sys.exit(0) # exit with error code
class saveMyoData(object): def __init__(self): self.actionNum = 0 #用于对动作类别进行计数 self.actionList = [ "one", "two", "three", "four", "five", "open_hand", "ok", "low", "love", "good", "fist", "eight", "crasp" ] #保存的动作列表 self.selectActionList = [] #永户选用的动作列表 # self.stopFlag = False #停止采集数据标志 self.actionTime = 0 #动作持续的时间(s) self.restTime = 0 #修息状态持续的时间(s) self.getSystermType() self.setFilePath() #设置肌电数据的存储路径 #开始函数 def start(self): self.listener = PrintPoseListener(dataType=["emg"]) self.mMyo = Myo() # self.getSystermType() # self.setFilePath() #设置肌电数据的存储路径 self.getUserInput() #获得用户输入的信息 pygame.init() #初始化显示窗口 self.screen = pygame.display.set_mode((200, 250)) #设置显示窗口的大小 try: self.mMyo.connect() self.mMyo.add_listener(self.listener) self.mMyo.vibrate(VibrationType.SHORT) except ValueError as ex: print(ex) #获取用户的输入信息 def getUserInput(self): self.actionTime = int(raw_input("请输入动作时间:")) self.restTime = int(raw_input("请输入休息时间:")) print("--------------------------------------------------------") print("目前支持的动作为:" + str(self.actionList)) print("--------------------------------------------------------") print("请输入您想要训练的动作,结束请按“ctrl+c” : ") try: while True: tempAction = raw_input(">>:") #获取用户的动作选择输入 if tempAction in self.actionList: self.selectActionList.append(tempAction) else: print("输入的动作有误,请确认后重新输入!") print( "--------------------------------------------------------" ) print("目前支持的动作为:" + str(self.actionList)) print( "--------------------------------------------------------" ) except KeyboardInterrupt: print("") print('Finished.') #设置图片的显示,图片显示线程主函数 def setActionState(self, actionTime, restTime): global actionCategry, stopFlag currentFilePath = os.getcwd() while True: if self.systermType == "Windows": actionPicPath = currentFilePath + "//pose//" + str( self.selectActionList[self.actionNum]) + ".JPG" restPicPath = currentFilePath + "//pose//" + "rest.JPG" elif self.systermType == "Linux": actionPicPath = currentFilePath + "/pose/" + str( self.selectActionList[self.actionNum]) + ".JPG" restPicPath = currentFilePath + "/pose/" + "rest.JPG" #action img = pygame.image.load(actionPicPath).convert_alpha() img = pygame.transform.scale(img, (200, 250)) actionCategry = self.selectActionList[self.actionNum] pygame.display.set_caption(self.selectActionList[self.actionNum]) font = pygame.font.Font(None, 26) self.screen.blit(img, (0, 0)) pygame.display.update() time.sleep(actionTime) # #rest if self.restTime == 0: pass else: img = pygame.image.load(restPicPath).convert_alpha() img = pygame.transform.scale(img, (200, 250)) actionCategry = "rest" pygame.display.set_caption("rest") font = pygame.font.Font(None, 26) self.screen.blit(img, (0, 0)) pygame.display.update() time.sleep(restTime) self.actionNum += 1 if self.actionNum >= len(self.selectActionList): stopFlag = True pygame.quit() break #设置肌电数据的保存路径 def setFilePath(self): currentFilePath = os.getcwd() timeStr = str(int(time.time())) if self.systermType == "Windows": self.emgDataPath = currentFilePath + '//data//emgData' elif self.systermType == "Linux": self.emgDataPath = currentFilePath + '/data/emgData' #判断文件夹是否存在,不存在则创建 if os.path.exists(self.emgDataPath) == False: os.makedirs(self.emgDataPath) def getSystermType(self): self.systermType = platform.system() #保存肌电数据 def saveEmgData(self, data): timeStr = str(int(time.time())) self.fileName = 'emg_' + timeStr fileExistFlag = os.path.isfile(self.fileName + '.csv') if self.systermType == "Windows": self.emgDataFilePath = self.emgDataPath + "//" + self.fileName + ".csv" elif self.systermType == "Linux": self.emgDataFilePath = self.emgDataPath + "/" + self.fileName + ".csv" #写入数据 with open(self.emgDataFilePath, 'a+') as f: writer = csv.writer(f) if fileExistFlag == False: writer.writerow([ 'ch0', 'ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6', 'ch7', 'label' ]) #为肌电数据设置列索引 writer.writerows(data) #保存数据为csv格式 f.close() #数据采集线程主函数 def myoRun(self): global stopFlag while True: self.mMyo.run() if stopFlag == True: self.mMyo.vibrate(VibrationType.SHORT) self.mMyo.safely_disconnect() self.saveEmgData(self.listener.emgData) break #运行程序 def run(self): global stopFlag try: self.mThread = myThread() self.mThread.addThread('setPic', targetFunc=self.setActionState, haveArgsFlag=1, args=(self.actionTime, self.restTime)) self.mThread.addThread('getData', self.myoRun, 0) #加入数据采集的线程 self.mThread.runThread() if stopFlag == True: self.mThread.stopThread() except KeyboardInterrupt: self.mMyo.safely_disconnect() print('Finished.')
class onLineClf(saveMyoData): def __init__(self, modelFilePath, dataMode=["emg", "imu"]): '''data mode''' self.dataMode = dataMode #采集的数据的种类,主要有:emg 和 imu '''emg data''' self.emgDataLenth = 24 #每次采集多少个数据做一次特征提取和动作的识别 self.emgDict = dict() '''model''' self.modelFilePath = modelFilePath #分类模型保存的路径 self.numberVoter = 3 #投票成员的个数 '''初始化myo相关程序''' def start(self): self.listener = PrintPoseListener(dataType=self.dataMode, trainType="on") self.mMyo = Myo() self.getSystermType() # self.setFilePath() #设置路径 try: self.mMyo.connect() self.mMyo.add_listener(self.listener) self.mMyo.vibrate(VibrationType.SHORT) except ValueError as ex: print(ex) self.loadModel() #导入模型 self.mMyo.vibrate(VibrationType.MEDIUM) #采集线程主程序 def myoRun(self): try: while True: self.mMyo.run() except KeyboardInterrupt: self.mMyo.safely_disconnect() self.mThread.delThread("getData") #获取在线分类结果函数(分类线程函数) def onlineClf(self): try: while True: if self.listener.emgDataCount > self.model.mWinWidth + self.numberVoter - 1: #投票数为其加1 self.listener.emgDataCount = 0 self.listener.emgData = np.array(self.listener.emgData, dtype=np.int64) self.listener.emgData = self.listener.emgData.T self.emgDict['one'] = self.listener.emgData self.sample = FeatureSpace( rawDict=self.emgDict, moveNames=[ 'one', ], #动作类别 ChList=[0, 1, 2, 3, 4, 5, 6, 7], #传感器的通道数目 features={ 'Names': self.model.mFeatureList, #定义的特征 'LW': self.model.mWinWidth, #定义的窗宽 'LI': self.model.mSlidingLen }, #定义的窗滑动的步长 one_hot=False, trainPercent=[1, 0, 0] #是否进行onehot处理 ) self.getTrainData() actionList = self.model.mModel.predict(self.trainX) print("the action is :", self.getTheAction(actionList)) self.listener.emgData = [] self.emgDict.clear() else: time.sleep(0.1) pass except KeyboardInterrupt: self.mThread.delThread("onlineClf") #The feature space is divided into data sets def getTrainData(self): nDimensions = self.sample.trainImageX.shape[1] #训练集 self.trainX = np.reshape(self.sample.trainImageX, (-1, nDimensions)) self.trainY = np.squeeze(self.sample.trainImageY) #测试集 self.testX = np.reshape(self.sample.testImageX, (-1, nDimensions)) self.testY = np.squeeze(self.sample.testImageY) #评估集 self.validateX = np.reshape(self.sample.validateImageX, (-1, nDimensions)) self.validateY = np.squeeze(self.sample.validateImageY) '''导入已经保存的模型''' def loadModel(self): print("path:", self.modelFilePath) self.model = joblib.load(self.modelFilePath) self.actionNames = self.model.actionNames '''设置模型文件的名称''' def setModelFileName(self, fileName): self.modelFileName = fileName def getSystermType(self): self.systermType = platform.system() '''设置模型文件的路径''' def setFilePath(self): currentFilePath = os.getcwd() if self.systermType == "Windows": self.modelFilePath = currentFilePath + '//data//model//' self.filePathName = currentFilePath + '//data//filePathFile.txt' elif self.systermType == "Linux": self.modelFilePath = currentFilePath + '/data/model/' self.filePathName = currentFilePath + '/data/filePathFile.txt' with open(self.filePathName, "r") as fp: self.modelFileName = str(fp.readlines()[1]) + "-model.pkl" fp.close() #判断文件夹是否存在,不存在则创建 if os.path.exists(self.modelFilePath) == True: self.modelFileExitFlag = True else: print( "The model is not saved, please save the model before using the model!!" ) #投票函数 def getTheAction(self, actionList): tempData = np.array(actionList) counts = np.bincount(tempData) actionNumber = np.argmax(counts) return self.actionNames[actionNumber] #返回定义的动作类别字符串 '''myo主程序的入口''' def run(self): try: self.mThread = myThread() self.mThread.addThread('onlineClf', self.onlineClf, 0) #加入在线识别动作线程 self.mThread.addThread('getData', self.myoRun, 0) #加入数据采集的线程 self.mThread.runThread() except KeyboardInterrupt: self.mMyo.safely_disconnect() self.mThread.stopThread() print('Finished.')
# MYO NESNESI myo = Myo() try: # MYO BAGLANTI myo.connect() # LISTENER EKLEME myo.add_listener(listener) # BASLANGICTA 5 KISA TITRESIM for i in range(0, 5): myo.vibrate(VibrationType.SHORT) # PROGRAM BU DONGU ICINDE CALISIR while True: # myo.run() KOMUTU : HAREKETLERI ALGILAR mPose = myo.run() # myo.run() KOMUTUNDAN "-1" DEGERI DONER ISE # YANI HAREKET DEGERI "UNKNOWN" ISE if (mPose == -1): # GUVENLI CIKIS myo.safely_disconnect() # TEKRAR BAGLANTI myo.connect() # TEKRAR LISTENER EKLE myo.add_listener(listener) # TEKRAR 5 TITRESIM for i in range(0, 5): myo.vibrate(VibrationType.SHORT) # KLAVYEDEN DURDURMA except KeyboardInterrupt: break
def on_imu(self, quat, acc, gyro): if "imu" in self.dataType: print("the quat is :" + str(quat)) print("the acc is :" + str(acc)) print("the gyro is :" + str(gyro)) else: pass if __name__ == '__main__': print('Start Myo for Linux') listener = PrintPoseListener(dataType=["emg"]) myo = Myo() try: myo.connect() myo.add_listener(listener) myo.vibrate(VibrationType.SHORT) while True: myo.run() except KeyboardInterrupt: pass except ValueError as ex: print(ex) finally: myo.safely_disconnect() print('Finished.')