def setup_myo(): global myo, myo_initialized print('Setting up myo ...') myo = MyoRaw(None) def emg_handler(emg, moving, times=[]): # store data global emg_data_latest emg_data_latest = emg def imu_handler(quat, acc, gyro): # store data global quat_data_latest, acc_data_latest, gyro_data_latest quat_data_latest = quat acc_data_latest = acc gyro_data_latest = gyro myo.add_emg_handler(emg_handler) myo.add_imu_handler(imu_handler) myo.connect() myo_initialized = True print('Myo connected') myo.sleep_mode(1) _thread.start_new_thread(thread_myo, ()) print('Myo setup.\n')
def __init__(self, fs=200, win_duration=1, num_channels=8): self._stop = False myo = MyoRaw(None) num_samples = win_duration * fs emg_win = np.zeros((num_samples, num_channels)) i = 0 signals_chan = queue.Queue() def collect_data(emg, _moving): nonlocal i if i == num_samples: signals_chan.put(np.copy(emg_win)) i = 0 emg_win[i] = emg i += 1 myo.add_emg_handler(collect_data) myo.connect() self.signals_chan = signals_chan self.myo = myo
def myo_main(self): atexit.register(set_normal_term) set_curses_term() m = MyoRaw(None) m.add_emg_handler(self.proc_emg) m.connect() m.add_arm_handler(lambda arm, xdir: print('arm', arm, 'xdir', xdir)) m.add_pose_handler(lambda p: print('pose', p)) # [EMG0, EMG1, EMG2, EMG3, EMG4, EMG5, EMG6, EMG7, TIME, STATUS] dim_data = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=float) data = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=float) try: t_start = time.time() while True: m.run(1) #stop vibration ever m.write_attr(0x19, b'\x03\x01\x00') emg, self._time = m.plot_emg(t_start) if kbhit(): key = getch() if key == 'r': #print("ROCK") dim_data[-1:] = 1 elif key == 's': #print("SCISSOR") dim_data[-1:] = 2 elif key == 'p': #print("PAPET") dim_data[-1:] = 3 print("\r", end='') else: print("\r{0}".format(dim_data), end="") dim_data[-1:] = 0 continue #グラフは1次元 dim_data[:9] = np.append(emg, self._time) if self._time > 1.: if len(dim_data) == 10: dim2_data = np.expand_dims(dim_data, axis=0) data = np.append(data, dim2_data, axis=0) self.count += 1 except KeyboardInterrupt: pass finally: m.disconnect() if self.save_csv: self.save_data(self.saving_path + ".csv", data[1:]) if self.byn_np: np.save(self.saving_path, data[1:]) if self.plt_graph: self.data_plot(data) print("")
def collect_myo_data(detectedMyos): global dual if (detectedMyos is not None): # Closure function to record EMG data def proc_emg(timestamp, emg, moving, id): emgs = list([e / 2000. for e in emg]) print(id, '--', timestamp, '--', emgs) # Set up first myo m = MyoRaw(detectedMyos[0], '1') m.add_emg_handler(proc_emg) m.connect() m.add_arm_handler(lambda arm, xdir: print('arm', arm, 'xdir', xdir)) m.add_pose_handler(lambda p: print('pose', p)) # Stop Myo from sleeping during data collection m.set_sleep_mode(1) m.vibrate(3) if (len(detectedMyos) == 2): m2 = MyoRaw(detectedMyos[1], '2') m2.add_emg_handler(proc_emg) m2.connect() # Stop myo from sleeping during data collection m2.set_sleep_mode(1) m2.vibrate(3) m2.add_arm_handler( lambda arm, xdir: print('arm', arm, 'xdir', xdir)) m2.add_pose_handler(lambda p: print('pose', p)) dual = True try: while True: if (dual == True): m.run(1) m2.run(1) else: m.run(1) except KeyboardInterrupt: pass finally: m.disconnect() m2.disconnect() print()
def collect_myo_data(detectedMyos): global dual if(detectedMyos is not None): # Closure function to record EMG data def proc_emg(timestamp, emg, moving, id): emgs = list([e / 2000. for e in emg]) print (id, '--', timestamp, '--', emgs) # Set up first myo m = MyoRaw(detectedMyos[0], '1') m.add_emg_handler(proc_emg) m.connect() m.add_arm_handler(lambda arm, xdir: print('arm', arm, 'xdir', xdir)) m.add_pose_handler(lambda p: print('pose', p)) # Stop Myo from sleeping during data collection m.set_sleep_mode(1) m.vibrate(3) if(len(detectedMyos) == 2): m2 = MyoRaw(detectedMyos[1], '2') m2.add_emg_handler(proc_emg) m2.connect() # Stop myo from sleeping during data collection m2.set_sleep_mode(1) m2.vibrate(3) m2.add_arm_handler(lambda arm, xdir: print('arm', arm, 'xdir', xdir)) m2.add_pose_handler(lambda p: print('pose', p)) dual = True try: while True: if(dual == True): m.run(1) m2.run(1) else: m.run(1) except KeyboardInterrupt: pass finally: m.disconnect() m2.disconnect() print()
class myMyo(object): def __init__(self, storedPath): self.m = MyoRaw(sys.argv[1] if len(sys.argv) >= 2 else None) self.storedPath = storedPath self.hnd = EMGHandler(self.m, self.storedPath) self.m.add_emg_handler(self.hnd) self.m.add_emg_handler(proc_emg) # self.m.add_imu_handler(proc_imu) def start(self): self.hnd.recording = 1 print('recording flag --> ' + str(self.hnd.recording)) self.m.connect() def run(self, ActionCategry): global actionCategry self.m.run() actionCategry = ActionCategry def stop(self): self.hnd.recording = -1 print('recording flag --> ' + str(self.hnd.recording)) self.m.disconnect()
times.append(time.time()) if len(times) > 20: # print((len(times) - 1) / (times[-1] - times[0])) times.pop(0) def proc_battery(battery_level): print("Battery level: %d" % battery_level) if battery_level < 5: m.set_leds([255, 0, 0], [255, 0, 0]) else: m.set_leds([128, 128, 255], [128, 128, 255]) m = MyoRaw(sys.argv[1] if len(sys.argv) >= 2 else None) m.add_emg_handler(proc_emg) m.add_battery_handler(proc_battery) m.connect() m.add_arm_handler(lambda arm, xdir: print('arm', arm, 'xdir', xdir)) m.add_pose_handler(lambda p: print('pose', p)) # m.add_imu_handler(lambda quat, acc, gyro: print('quaternion', quat)) m.sleep_mode(1) m.set_leds([128, 128, 255], [128, 128, 255]) # purple logo and bar LEDs m.vibrate(1) try: while True: m.run(1) if HAVE_PYGAME:
#print(oscmsg) #print(data) def imu(quat, acc, gyro): #print(quat,acc,gyro) #print ("quat: ", quat, " type: ", type(quat)) send(quat, wek, "/wek/inputs") def pose(p): print(p) def emg(emg, moving): emgdat = (sum(emg) / float(len(emg)), ) #print ("emgdat: ", emgdat, " type: ", type(emgdat)) send(emgdat, tenta, "/tenta_emg") if __name__ == '__main__': m = MyoRaw() #m.add_imu_handler(print) m.add_imu_handler(imu) #m.add_pose_handler(pose) m.add_emg_handler(emg) m.connect() while True: m.run()
outdir.mkdir(parents=True, exist_ok=True) emg_file = outdir.joinpath(now + '_emg.csv').open(mode='w', newline='') imu_file = outdir.joinpath(now + '_imu.csv').open(mode='w', newline='') emg_writer = csv.writer(emg_file, csv.unix_dialect, quoting=csv.QUOTE_MINIMAL) emg_writer.writerow(emg_header) imu_writer = csv.writer(imu_file, csv.unix_dialect, quoting=csv.QUOTE_MINIMAL) imu_writer.writerow(imu_header) m = MyoRaw(args.tty) m.add_emg_handler(lambda *args: write_data(emg_writer, args)) m.add_imu_handler(lambda *args: write_data(imu_writer, args)) m.connect() # Enable never sleep mode. m.sleep_mode(1) try: while True: m.run(1) except KeyboardInterrupt: pass finally: m.disconnect() print("\nemg data saved to: {}".format(emg_file.name)) print("img data saved to: {}".format(imu_file.name))
# TODO: write file (txt) function if __name__ == '__main__': if HAVE_PYGAME: pygame.init() w, h = 800, 320 scr = pygame.display.set_mode((w, h)) font = pygame.font.Font(None, 30) file_path = './data_set/' file_name = os.path.join(file_path, 'data.pkl') m = MyoRaw(sys.argv[1] if len(sys.argv) >= 2 else None) hnd = DataHandler(m) m.add_emg_handler(hnd.on_emg) m.add_imu_handler(hnd.on_imu) m.connect() data_list = [] try: while True: m.run() if HAVE_PYGAME: for ev in pygame.event.get(): if ev.type == QUIT or (ev.type == KEYDOWN and ev.unicode == 'q'): raise KeyboardInterrupt()
def main(argv): import subprocess # --- say hello! #print('Alive and breathing!\n') global file_handle, save_to_file global plot_graph global simulated, verbose # --- init variables filename = str(time.strftime("%Y.%m.%d.%Hh%M")) # --- parse command-line arguments if verbose: print('Parsing input arguments ...') #print ('Number of arguments:', len(sys.argv), 'argument(s)') #print ('Arguments:', str(sys.argv)) try: opts, args = getopt.getopt(argv, "hsgxf:v", ["filename="]) except getopt.GetoptError: usage() for opt, arg in opts: if opt == '-h': usage() cleanup(1) sys.exit(0) elif opt == '-x': print('Option chosen: Simulated Myo.') simulated = True elif opt == '-g': print('Option chosen: Plotting graphs.') plot_graph = True elif opt == '-s': print('Option chosen: Saving to file.') save_to_file = True elif opt in ("-f", "--filename"): save_to_file = True filename = filename + '_' + arg print('Option chosen: Filename set to: ', filename) elif opt == '-v': print('Option chosen: Running verbose.') verbose = True if verbose: print('Input arguments parsed.\n') # --- open file for storing data if save_to_file: print('Saving data to file: ', filename) file_handle = open(filename, 'w') # --- setup myo global myo, myo_initialized print('Setting up myo ...') if not (simulated): #myo = MyoRaw(sys.argv[1] if len(sys.argv) >= 2 else None) myo = MyoRaw(None) def emg_handler(emg, moving, times=[]): # store data global emg_data_latest emg_data_latest = emg def imu_handler(quat, acc, gyro): # store data global quat_data_latest, acc_data_latest, gyro_data_latest quat_data_latest = quat acc_data_latest = acc gyro_data_latest = gyro myo.add_emg_handler(emg_handler) myo.add_imu_handler(imu_handler) #myo.add_arm_handler(lambda arm, xdir: print('arm', arm, 'xdir', xdir)) #myo.add_pose_handler(lambda p: print('pose', p)) myo.connect() myo_initialized = True print('Myo connected') else: print('Myo simulated') _thread.start_new_thread(thread_myo, ()) print('Myo setup.\n') # --- setup QT if plot_graph: # init window app = QtGui.QApplication([]) print('Starting up plots and QT ...') win = pg.GraphicsWindow(title="Myo data") win.closeEvent = cleanup win.resize(1000, 1000) win.setWindowTitle('Myo data') # pg.setConfigOptions(antialias=True) # Enable antialiasing for prettier plots pg.setConfigOption('background', 'k') #pg.setConfigOption('background', pg.mkColor(255,255,255) ) pg.setConfigOption('foreground', 'w') colors = ['r', 'g', 'b', 'c', 'm', 'y', 'w', 'r'] p_emg = [None] * 8 emg = [None] * 8 for i, color in enumerate(colors): p_emg[i] = win.addPlot(title="EMG " + str(i + 1)) p_emg[i].setXRange(0, BUFFER_SIZE) p_emg[i].setYRange(-150, 150) p_emg[i].enableAutoRange('xy', False) emg[i] = p_emg[i].plot(pen=color, name="emg" + str(i + 1)) win.nextRow() def update(): global emg_data_buffer for i in range(8): emg[i].setData(emg_data_buffer[1:BUFFER_SIZE, i]) timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(10) print('Plots set up.\n') if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() # no graphs else: while (1): #if verbose: # print('whiling.. :D') 1 #do nothing (the threads will perform something, e.g. writing the received values on terminal)