def main(): queue_size = 10 # Initialize Myo and create a Hub and our listener. myo.init() hub = myo.Hub() listener = Listener(queue_size) def update(): emgs = np.array([x[1] for x in listener.get_emg_data()]).T for x in emgs: data = x if len(data) < queue_size: data = np.concatenate([np.zeros(queue_size - len(data)), data]) word = 'Mean = %d , vector = ' % (data.mean()) print(word + str(data)) try: threading.Thread( target=lambda: hub.run_forever(listener.on_event)).start() time = TimeInterval(None, 0.1) while True: if time.check_and_reset(): os.system('cls') update() finally: hub.stop() # Will also stop the thread
def main(): myo.init( '/Users/essayas/Downloads/Summer2020ZED/myo/sdk/myo.framework/myo') hub = myo.Hub() listener = EmgCollector(512) with hub.run_in_background(listener.on_event): Plot(listener).main()
def main(): queue_size = 512 # Initialize Myo and create a Hub and our listener. myo.init() hub = myo.Hub() listener = Listener(queue_size) # Create the axes for the plot. fig = plt.figure() axes = [fig.add_subplot('81' + str(i)) for i in range(1, 9)] [(ax.set_ylim([-100, 100])) for ax in axes] graphs = [ax.plot(np.arange(queue_size), np.zeros(queue_size))[0] for ax in axes] plt.ion() def plot_main(): emgs = np.array([x[1] for x in listener.get_emg_data()]).T for g, data in zip(graphs, emgs): if len(data) < queue_size: data = np.concatenate([np.zeros(queue_size - len(data)), data]) g.set_ydata(data) plt.draw() try: threading.Thread(target=lambda: hub.run_forever(listener.on_event)).start() while True: plot_main() plt.pause(1.0 / 30) finally: hub.stop() # Will also stop the thread
def record(self, save_path, recording_time=110, sdk_path='/Users/ashwin/FYP/sdk/myo.framework/myo', plot=False): """ records the sEMG signals for the specified gesture type and saves the recording as a .csv file :param save_path: path where the dataset is saved :param recording_time: the duration of the recording :param sdk_path: the MyoSDK path :param plot: plot the recorded signals or not (boolean) :return: None """ myo.init(sdk_path) hub = myo.Hub() input("PRESS ENTER TO RECORD") start = time.time() listener = EmgCollector(start) hub.run(listener, recording_time * 1000) data = listener.emg_data data = data[1:] if plot: plot_recording(data, self.fs) write_to_csv(save_path, data=listener.emg_data)
def main(): # myo.init() myo.init(sdk_path='../sdk') hub = myo.Hub() listener = EmgCollector(10) with hub.run_in_background(listener.on_event): Plot(listener).main()
def main(): myo.init(sdk_path='/Users/harvinderpower/GitHub/ichealthhack18/myo-sensor-data-analysis/sdk/') hub = myo.Hub() listener = EmgCollector(512) with hub.run_in_background(listener.on_event): Plot(listener).main() '''print emg_data_queue + "\n"
def main(): print(sys.version_info) myo.init(os.getcwd() + '\\services\\myo64.dll') hub = myo.Hub() listener = EmgCollector(512) print("Hello") thread = threading.Thread( target=lambda: hub.run_forever(listener.on_event, 300)) thread.start() average = 0.0 counter = 0 while counter < 50: start_time = datetime.datetime.now() while len(data) < 50: pass end_time = datetime.datetime.now() print("Latency:", (end_time - start_time).total_seconds() * 1000, "ms") data.clear() counter += 1 average += (end_time - start_time).total_seconds() * 1000 print("Average:", average / counter, "ms") hub.stop() thread.join()
def main(): myo.init(sdk_path='./myo-sdk-win-0.9.0/') hub = myo.Hub() listener = EmgRate(n=50) while hub.run(listener.on_event, 500): print("\r\033[KEMG Rate:", listener.rate, end='') sys.stdout.flush()
def start(self): try: libmyo.init("C:/opt/myo-sdk-win-0.9.0/bin") except RuntimeError: print "kr neki" self.hub = libmyo.Hub() self.hub.run(1, self)
def main(): myo.init() hub = myo.Hub() listener = EmgRate(n=50) while hub.run(listener.on_event, 500): print("\r\033[KEMG Rate:", listener.rate, end='') sys.stdout.flush()
def main(): myo.init(os.path.dirname(__file__)) feed = myo.Feed() hub = myo.Hub() hub.run(1000, feed) myo_device = feed.get_devices() print(myo_device) time.sleep(1) print(DATA_PATH) try: myo_device = myo_device[0] myo_device.set_stream_emg(myo.StreamEmg.enabled) wrap_window = Tkinter.Tk() wrap_window.title('手语采集') wrap_window.geometry('720x720') panel = ControlPanel(wrap_window) capture_control = CaptureControl(myo_device, panel) panel.set_control(capture_control) t = CaptureThread(capture_control) t.setDaemon(True) t.start() wrap_window.mainloop() except RuntimeError: print('device didn\'t connected')
def main(): myo.init() hub = myo.Hub() listener = EmgCollector(512) with hub.run_in_background(listener.on_event): Plot(listener).main()
def main(): myo.init(sdk_path='./myo-sdk-win-0.9.0/') hub = myo.Hub() listener = EmgDataRecode(n_Windows=windows_len, f_forcut=threshold) while hub.run(listener.on_event, 500): print('\rAct Num:', listener.active_NUM, '\tSlide mean:', listener.tmpslide, end='') sys.stdout.flush() if listener.active_NUM >= num_act: break print("\nYour Pose:", alllei[motion_Label]) print("\n\033[1;32;mFinish! Please have a rest!") csvfile.close() fileori.close() filesmo.close() # pic for check! f1 = plt.figure(5) d = np.loadtxt(file_pictest_origin) plt.subplot(211) plt.plot(d) newd = np.loadtxt(file_pictest_smooth) plt.subplot(212) plt.plot(newd) plt.savefig('../myodata/oridata/'+peoplename+'_'+alllei[motion_Label]+'.png', dpi=600, bbox_inches='tight') plt.show()
def getOptions(opts, vars): opts['sr'] = 30 myo.init(sdk_path='./myo_sensor/myo_helpers/myo-sdk-win-0.9.0') vars['hub'] = myo.Hub() vars['listener'] = main.MyoListener()
def main(): global wingl global wingr viz.cam.setHandler(vizcam.KeyboardCamera()) myo.init() gyrolist = [[0,0,0]] viz.setMultiSample(4) viz.fov(150) wingl = viz.addChild('basketball.osgb') wingl.setScale([10,0.3,1]) wingl.setCenter([100,100,100]) wingl.setEuler([0,90,0]) wingl.collideSphere(0.5) lStartPOS = [ 0, 2.5, 2 ] wingl.setPosition( lStartPOS ) wingr = viz.addChild('basketball.osgb') wingr.setScale([10,0.3,1]) wingr.setCenter([100,100,100]) wingr.setEuler([0,90,0]) wingr.collideSphere(0.5) rStartPOS = [ 0, 2.5, 2 ] wingr.setPosition( rStartPOS ) #viz.MainView.setPosition([0,2,-15]) hub = myo.Hub() hub.set_locking_policy(myo.locking_policy.none) hub.run(1000, Listener()) vizact.ontimer(0.01 ,updateMyo, [gy, gy2, gy3, wingl, orx, ory, orz, orw, or1x, or1y, or1z, or1w, wingr])
def main(): global wingl global wingr viz.cam.setHandler(vizcam.KeyboardCamera()) myo.init() gyrolist = [[0,0,0]] viz.fov(150) #wingl.setScale([10,0.3,1]) #wingl.setCenter([100,100,100]) wingl.setEuler([0,90,0]) wingl.collideSphere(0.5) lStartPOS = [ 0, 2.5, 2 ] wingl.setPosition( lStartPOS ) #wingr.setScale([10,0.3,1]) #wingr.setCenter([100,100,100]) wingr.setEuler([0,90,0]) wingr.collideSphere(0.5) rStartPOS = [ 0, 2.5, 2 ] wingr.setPosition( rStartPOS ) hub = myo.Hub() hub.set_locking_policy(myo.locking_policy.none) hub.run(1000, Listener()) vizact.ontimer(0.01 ,updateMyo, [gy, gy2, gy3, wingl, orx, ory, orz, orw, or1x, or1y, or1z, or1w, wingr]) vizact.ontimer(0, updateEuler) FileReader() initializeObjectFiles() initializeLocations() getCurrentTestingLocationOrder() vizact.ontimer(0.1, update)
def main(model): numb = 0 queue_size = 10 myo.init() hub = myo.Hub() listener = Listener(queue_size) try: threading.Thread( target=lambda: hub.run_forever(listener.on_event)).start() t = 0 flag = 0 data = [] while True: emgs = step(listener) if len(emgs) != 10: continue if len(data) < 50: emgs = tf.keras.utils.normalize(emgs, axis=0) data.append(emgs.reshape(1, 80)) continue else: predictions = [] for x in data: predictions.append(model.predict(x).argmax()) os.system('cls') #print(predictions) data = [] print(np.bincount(predictions).argmax()) finally: hub.stop()
def main(): myo.init(sdk_path='/Users/egor/Documents/University/myo_sdk') options = "1. Record gesture \n2. Process and exit \n3. Exit \n->" recorded_data = {} labels = {} y = 0 points_number = 1000 while True: choice = int(raw_input(options)) if choice == 1: gesture_name = str(raw_input("Please enter gesture name \n ->")) filename = generate_filename(gesture_name, points_number) proceed = int( raw_input( "File name is " + filename + " \n You will have 3 seconds to prepare. Ready? [1 - Yes/ 0 - No] \n ->" )) if proceed == 1: countdown(3) emg_data = record(points_number, myo, filename=filename) recorded_data[gesture_name] = emg_data labels[gesture_name] = y y += 1 plt.plot(emg_data) plt.show() elif choice == 2: process_recordings(recorded_data, labels) else: return
def main(): # ================== setup myo-python (do not change) ===================== myo.init(sdk_path='../../myo_sdk') # Compile Python binding to Myo's API hub = myo.Hub() # Create a Python instance of MYO API if not ConnectionChecker( ).ok: # Check connection before starting acquisition: quit() # ========================================================================= # Parce command line inputs, if any filename = 'emg' acquisition_len = 10 if len(sys.argv) > 1: acquisition_len = int(sys.argv[1]) if len(sys.argv) > 2: filename = sys.argv[2] listener = Collector(acquisition_len * EMG_SAMPLING_RATE) print('\rStarted recording EMG for', str(acquisition_len), 'seconds. Cancel with ctrl-c.') with hub.run_in_background(listener.on_event): while hub.running: time.sleep(0.5) print('\rRecording ... %d percent done.' % (100 * listener.emg_data.shape[0] / acquisition_len / EMG_SAMPLING_RATE), end='') print() with open(filename + '.csv', 'w') as csvfile: for row in listener.emg_data: csvfile.write(', '.join(map(str, list(row))) + '\n')
def init(self, callback): myo.init() self.hub = myo.Hub() self.hub.set_locking_policy(myo.locking_policy.none) self.myo = self.MyoListener(self) self.myo.callback = callback myo.set_stream_emg(stream_emg.enabled) self.hub.run(1000, self.myo)
def myoimu(): import myo from pydaqs.myo import MyoIMU myo.init(sdk_path=r'C:\Users\nak142\Coding\myo-python\myo-sdk-win-0.9.0') dev = MyoIMU(samples_per_read=5) pipeline = Pipeline([Windower(500)]) channel_names = list('wxyz') run(dev, pipeline, channel_names=channel_names)
def main(): myo.init(sdk_path='../myo-sdk-win-0.9.0') hub = myo.Hub() listener = EmgRate(n=50) # The timeout time in run will determine how often an update will be displaed while hub.run(listener.on_event, 500): print("\r\033[KEMG Rate:", listener.rate, end='') sys.stdout.flush()
def main(): arduino = serial.Serial('COM14', 9600) time.sleep(2) queue_size = 1 temp = 0 check = 0 vector = [0, 0, 0, 0, 0] for x in range(5): vector[x] = random.randrange(100) # Initialize Myo and create a Hub and our listener. send(vector, arduino) myo.init() hub = myo.Hub() listener = Listener(queue_size) # Create the axes for the plot. def plot_main(temp, check): flag = check emgs = np.array([x[1] for x in listener.get_emg_data()]) if temp == 1200: os.system('cls') print(''.join('{}'.format(p) for p in emgs)) print(vector) print(' flag: ' + str(flag)) if keyboard.is_pressed('s') and flag == 0: f = open('InputX.csv', 'a') vectornp = np.asarray(vector) vectornp = vectornp / 100 np.savetxt(f, emgs, delimiter=",") f.close() f = open('OutputY.csv', 'a') vectornp = vectornp.reshape(1, 5) np.savetxt(f, vectornp, delimiter=",") f.close() flag = flag + 10000 for x in range(5): vector[x] = random.randrange(100) send(vector, arduino) if keyboard.is_pressed('q'): hub.stop() send([0, 0, 0, 0, 0], arduino) arduino.close() sys.exit() return flag try: threading.Thread( target=lambda: hub.run_forever(listener.on_event)).start() while True: temp = temp + 1 check = plot_main(temp, check) if temp == 1200: temp = 0 if check > 0: check = check - 1 finally: hub.stop() # Will also stop the thread
def main(): myo.init() hub = myo.Hub() listener = EmgCollector(200) with hub.run_in_background(listener.on_event): time.sleep(5) Plot(listener).print_plot() Plot(listener).main() EmgCollector(myo).vibrate_def()
def conexionMYO(self): print("Realizando Conexión MYO") myo.init() self.hub = myo.Hub() self.listener = EmgCollector(512) self.stopconexion = False self.stopsaved = False print("Conexión MYO Establecida") self.Crear_carpetaMYO()
def main(): # ================== setup myo-python (do not change) ===================== myo.init(sdk_path='../../myo_sdk') # Compile Python binding to Myo's API hub = myo.Hub() # Create a Python instance of MYO API if not ConnectionChecker( ).ok: # Check connection before starting acquisition: quit() # ========================================================================= # Parce command line inputs, if any. When running this script from command line, # you can specify the target data folder: # python scriptname.py foldername if len(sys.argv) > 1: data_folder = sys.argv[1] else: data_folder = 'data' # Setup classification problem and training dataset parameters gestures = collections.OrderedDict() gestures = ['fist', 'radial', 'ulnar', 'extension', 'flextion', 'rest'] #, 'pron', 'supi'] # Classes to acquire data for trials_n = 3 # Number of trials for each class trial_len = 5 # Duration of each trial in seconds print('Starting the EMG data collection ... Press ctrl-c to stop.') # Get to the dataset folder, if doesn't exist, create it: if not os.path.exists(data_folder): os.mkdir(data_folder) os.chdir(data_folder) # EMG data is acquired in the following order: # Class1-Trial1, Class2-Trial1 ... ClassN_Trial1, # Class2_Trial2, Class2-Trial2 ... ... ClassN_TrialM. for trial in range(1, trials_n + 1): for gesture in gestures: # For each class, enter or create a specific folder that contains all of its trials: if not os.path.exists(gesture): os.mkdir(gesture) os.chdir(gesture) # Check if such trial for this class was already recorded (useful when continuing an interrupted acquisition) if os.path.exists(str(trial) + '.csv'): print( 'Trial', str(trial), 'of class %s already exists, moving forward ...' % gesture.upper()) else: # Make new acquisition: emg_data = make_single_acquisition( trial_len, 'Start performing %s gesture.' % gesture.upper()) # ... and save it as Comma-Separated Values (CSV): with open(str(trial) + '.csv', 'w') as csvfile: for row in emg_data: csvfile.write(', '.join(map(str, list(row))) + '\n') os.chdir('..') print('Data acquistion accomplished, signals are saved in', data_folder, 'folder.') os.chdir('..')
def myoemg(): import myo from pydaqs.myo import MyoEMG # Set the dir where myo-sdk is stored myo.init(sdk_path=r'C:\Users\nak142\Coding\myo-python\myo-sdk-win-0.9.0') n_channels = 8 dev = MyoEMG(channels=range(n_channels), samples_per_read=20) pipeline = Pipeline([Windower(2000)]) channel_names = ['EMG ' + str(i) for i in range(1, n_channels + 1)] run(dev, pipeline, channel_names=channel_names, yrange=(-150, 150))
def start_hub(): myo.init('myo-sdk-win-0.9.0/bin/myo64.dll') hub = myo.Hub() listener = Listener() max_time_allowed = 3.5 # in seconds. start = time.time() while hub.run(listener.on_event, 500): if time.time() - start > max_time_allowed: hub.stop() break
def init_connection(self): """ lance un timer toutes les 20ms pour récupérer les données """ # permet de charger la librairie du myo myo.init(sdk_path=os.path.join(os.getcwd(), 'myo-sdk-win-0.9.0')) # connection à un myo self.hub = myo.Hub() # connection à une classe en écoute du myo self.listener = my_myo_arm_band.MyListener() self.startTimer(0.02)
def main(): # ================== setup myo-python (do not change) ===================== myo.init(sdk_path='../../myo_sdk') # Compile Python binding to Myo's API hub = myo.Hub() # Create a Python instance of MYO API if not ConnectionChecker().ok: # Check connection before starting acquisition: quit() # ========================================================================= # Setup our custom processor of MYO's events. # EmgBuffer will acquire new data in a buffer (queue): listener = Buffer(buffer_len = 512) # At sampling rate of 200Hz, 512 samples correspond to ~2.5 seconds of the most recent data. # Setup multichannel plotter for visualisation: plotter = MultichannelPlot(nchan = 8, xlen = 512) # Number of EMG channels in MYO armband is 8 #plotter2 = MultichannelPlot(nchan = 8, xlen = 512) N1 = 0 q = 0 j = 0 # Tell MYO API to start a parallel thread that will collect the data and # command the MYO to start sending EMG data. with hub.run_in_background(listener): # This is the way to associate our listener with the MYO API. print('Streaming EMG ... Press shift-c to stop.') while hub.running: time.sleep(0.040) # Pull recent EMG data from the buffer emg_data = listener.get_emg_data() # Transform it to numpy matrix emg_data = np.array([x[1] for x in emg_data]) # q = q+1 # if q >= 100: # q = 0 # N = 0 # for i in range(1,len(emg_data)): # N[j] = N[j] + emg_data[i] # N1[j] = N[j]/(len(emg_data)) # j = j+1 # print('\rRecording ... %d percent done.' % N[j], end='\n') # Plot it plotter.update_plot(emg_data.T) # Plot Moving Mean Average Value #plotter2.update_plot(N1,j) plt.plot(N1,j, color="r", linestyle="-", linewidth=1) plt.show() if keyboard.is_pressed('C'): print('Stop.') break
def __init__(self, queue_size=8): self.lock = threading.Lock() myo.init() self.hub = myo.Hub() #self.emg_data_queue = collections.deque(maxlen=queue_size) self.EMG = np.empty([0, 8]) self.predictions_array = [] self.prediction_array = np.empty([0]) self.emg_total = np.empty([0, 8]) self.flag_Graph1 = None self.flag_Predict = 0
def listen(): libmyo.init() listener = EmgListen() hub = libmyo.Hub() hub.run(1000, listener) try: while hub.running: time.sleep(0.5) except KeyboardInterrupt: print("Quitting...") finally: hub.shutdown()
def main(): libmyo.init() hub = libmyo.Hub() listener = EmgRate(50) try: while True: hub.run_once(100, listener) print("\r\033[KEMG Rate:", listener.rate, end='') sys.stdout.flush() finally: hub.stop(True) hub.shutdown()
def main(): myo.init() hub = myo.Hub() listener = myo.ApiDeviceListener() with hub.run_in_background(listener.on_event): print("Waiting for a Myo to connect ...") device = listener.wait_for_single_device(2) if not device: print("No Myo connected after 2 seconds.") return print("Hello, Myo! Requesting RSSI ...") device.request_rssi() while hub.running and device.connected and not device.rssi: print("Waiting for RRSI...") time.sleep(0.001) print("RSSI:", device.rssi) print("Goodbye, Myo!")
def stream(): #Initialize libmyo.init() feed = libmyo.device_listener.Feed() hub = libmyo.Hub() hub.run(1000, feed) myo = feed.wait_for_single_device() #Continuously collect and emit data while 1: try: gyro = myo.gyroscope accel = myo.acceleration myo_sock.emit('data', [time.clock(), gyro.x, gyro.y, gyro.z, accel.x, accel.y, accel.z]) time.sleep(0.02) except KeyboardInterrupt: break except: print 'Unexpected error' hub.shutdown()
def main(): global wingl # global wingr viz.cam.setHandler(vizcam.KeyboardCamera()) myo.init() gyrolist = [[0,0,0]] viz.setMultiSample(4) # wingl = viz.addChild('basketball.osgb') wingl.setScale([10,0.3,1]) wingl.setCenter([100,100,100]) wingl.setEuler([0,90,0]) wingl.collideSphere(0.5) lStartPOS = [ 0, 2.5, 2 ] wingl.setPosition( lStartPOS ) # wingr = viz.addChild('basketball.osgb') # wingr.setScale([10,0.3,1]) # wingr.setCenter([100,100,100]) # wingr.setEuler([0,90,0]) # wingr.collideSphere(0.5) # rStartPOS = [ 0, 2.5, 2 ] # wingr.setPosition( rStartPOS ) #viz.MainView.setPosition([0,2,-15]) hub = myo.Hub() hub.set_locking_policy(myo.locking_policy.none) hub.run(1000, Listener()) vizact.ontimer(0.01 ,updateMyo, [gy, gy2, gy3, wingl, orx, ory, orz, orw, or1x, or1y, or1z, or1w]) vizact.onkeydown('p', hub.shutdown) FileReader() initializeObjectFiles() initializeLocations() vizact.ontimer(0.1, update) vizact.onkeydown(' ', statusUpdate) vizact.onkeydown('s', hub.shutdown) # viz.AVIRecorder.maxWidth = 1920; # viz.AVIRecorder.maxHight = 1080; vizact.onkeydown('b', viz.window.startRecording, 'myo_capture.avi' ) vizact.onkeydown('e', viz.window.stopRecording )
yaw = math.atan2(2.0 * (quat.w * quat.z + quat.x * quat.y), 1.0 - 2.0 * (quat.y * quat.y + quat.z * quat.z)) self.mavg = (self.mavg[0]*fac + roll*(1-fac), self.mavg[1]*fac + pitch*(1-fac), self.mavg[2]*fac + yaw*(1-fac)) #print(self.mavg[1]) #print("Orientation:", round(self.mavg[0], 3), round(self.mavg[1], 3), round(self.mavg[2], 3), "*** Direction:", # "+" if self.direction[0] == Up else "-", # "+" if self.direction[1] == Up else "-", # "+" if self.direction[2] == Up else "-") self.direction = (Up if self.mavg[0] - self.prev[0] > 0 else Down, Up if self.mavg[1] - self.prev[1] > 0 else Down, Up if self.mavg[2] - self.prev[2] > 0 else Down) self.prev = self.mavg init("/users/andrew/dev/xcode/myo/myo.framework") hub = Hub() hub.run(1000, Listener()) try: while True: sleep(0.5) except KeyboardInterrupt: print('\nQuit') finally: hub.shutdown() # !! crucial
from __future__ import print_function from pync import Notifier from phue import Bridge from random import randint from os import system import myo as libmyo; libmyo.init('./myo.framework') import time import sys class Jarvis(): hue_bridge_ip = '192.168.0.29' default_bulb_id = 2 request_interval = 0.1 # Output only 0.1 seconds default_voice_names = ["Zarvox", "Ava"] def __init__(self): print("Hi ! I'm Jarvis. Nice to meet you !") self.last_time = 0 self.voiceNameId = 0 self.initHueBridge() self.initMyo() def run(self): # Listen to keyboard interrupts and stop the hub in that case. try: while self.hub.running: time.sleep(0.25) except KeyboardInterrupt: print("\nQuitting ...") finally:
def main(): """ MYO init """ libmyo.init() print("Connecting to Myo ... Use CTRL^C to exit.") hub = libmyo.Hub() hub.set_locking_policy(libmyo.LockingPolicy.none) myo = MyoListener() hub.run(1000, myo) """ Audio engine init """ pygame.mixer.init(44100, channels=1) sounds = samplebank.load_samples(pygame.mixer) State.currentGroup = sounds["single"]["random"] time.sleep(1) say("Welcome to VoCoMi") """ Main loop """ period = (60.0 / BPM) * 1000 try: while hub.running: # # LISTENING for instructions # if State.currentState == State.LISTENING: try: say(random.choice(["What would you like me to do?", "What should we do next?"])) intent = nuance.get_intent() print(intent) if not intent: continue elif intent["intent"] == "Exit": break elif intent["intent"] == "Clear": print("clear score") State.score = [[] for x in range(NBEATS)] say("Your mix has been cleared.") elif intent["intent"] == "List_options": print("list options") if ( "concepts" in intent and "Instruments" in intent["concepts"] and intent["concepts"]["Instruments"] in sounds["double"] ): options = list(sounds["double"][intent["concepts"]["Instruments"]].keys()) else: options = list(sounds["single"].keys()) + list(sounds["double"].keys()) last_option = options[-1] other_options = ",".join(options[:-1]) say("We currently have %s, and %s samples in our database." % (other_options, last_option)) elif intent["intent"] == "Modify_instrument_track": if "concepts" not in intent or "Instruments" not in intent["concepts"]: continue instrument = intent["concepts"]["Instruments"] if instrument in sounds["double"]: say("Please, be more specific. Which %s sample do you want?" % instrument) else: State.currentGroup = sounds["single"][instrument] # fill with selection State.currentSample = random.randint(0, len(State.currentGroup) - 1) State.currentState = State.BROWSING say( "You can now browse the %d %s samples by waving your hand. How about this one?" % (len(State.currentGroup), instrument) ) State.currentGroup[State.currentSample].play() elif intent["intent"] == "Select_drum_track": if ( "concepts" not in intent or "Drum_track" not in intent["concepts"] or len(intent["concepts"]["Drum_track"]) == 0 ): continue instrument = intent["concepts"]["Drum_track"] State.currentGroup = sounds["double"]["drums"][instrument] State.currentSample = random.randint(0, len(State.currentGroup) - 1) State.currentState = State.BROWSING say( "You can now browse the %d %s drum samples by waving your hand. How about this one?" % (len(State.currentGroup), instrument) ) State.currentGroup[State.currentSample].play() elif intent["intent"] == "Select_voice_track": if ( "concepts" not in intent or "Voice_track" not in intent["concepts"] or len(intent["concepts"]["Voice_track"]) == 0 ): continue instrument = intent["concepts"]["Voice_track"] State.currentGroup = sounds["double"]["voice"][instrument] # fill with selection State.currentSample = random.randint(0, len(State.currentGroup) - 1) State.currentState = State.BROWSING say( "You can now browse the %d %s voice samples by waving your hand. How about this one?" % (len(State.currentGroup), instrument) ) State.currentGroup[State.currentSample].play() elif intent["intent"] == "Set_and_modify": if "concepts" not in intent or "Instruments" not in intent["concepts"]: continue instrument = intent["concepts"]["Instruments"] if instrument in sounds["single"]: State.currentGroup = sounds["single"][instrument] elif instrument in sounds["double"]: if ( instrument == "drums" and "Drum_track" in intent["concepts"] and not intent["concepts"]["Drum_track"] == {} ): State.currentGroup = sounds["double"][instrument][intent["concepts"]["Drum_track"]] instrument = "%s drums" % intent["concepts"]["Drum_track"] elif instrument == "voice" and "Voice_track" in intent["concepts"]: State.currentGroup = sounds["double"][instrument][intent["concepts"]["Voice_track"]] instrument = "%s voice" % intent["concepts"]["Voice_track"] else: say("Please, be more specific. Which %s sample do you want?" % instrument) else: continue State.currentSample = random.randint(0, len(State.currentGroup) - 1) State.currentState = State.BROWSING say( "You can now browse the %d %s samples by waving your hand. How about this one?" % (len(State.currentGroup), instrument) ) State.currentGroup[State.currentSample].play() elif intent["intent"] == "Playback": State.currentState = State.PLAYING elif intent["intent"] == "YesNo": if "concepts" not in intent or "Instruments" not in intent["concepts"]: say("No, sorry. Currently this instument is not in our database.") elif "Instruments" in intent["concepts"]: say("Yes") except: say("Ups, something crashed.") # # BROWSE sounds # elif State.currentState == State.BROWSING: if myo.pose == libmyo.Pose.wave_in: myo.pose = None print("next sample") myo.myo.vibrate("short") State.currentSample += 1 while State.currentSample >= len(State.currentGroup): State.currentSample -= len(State.currentGroup) pygame.mixer.stop() State.currentGroup[State.currentSample].play() elif myo.pose == libmyo.Pose.wave_out: myo.pose = None print("previous sample") myo.myo.vibrate("short") pygame.mixer.stop() State.currentSample -= 1 # mod nSamples for current group while State.currentSample < 0: State.currentSample += len(State.currentGroup) State.currentGroup[State.currentSample].play() elif myo.pose == libmyo.Pose.fist: myo.pose = None print("start playback") State.currentBeat = 0 myo.myo.vibrate("medium") pygame.mixer.stop() State.currentState = State.PLAYING else: pass # # PLAY stuff # elif State.currentState == State.PLAYING: currentTime = int(time.time() * 1000.0) delta = currentTime - State.lastTime if delta > period: for s in State.score[State.currentBeat]: s.play() State.lastTime = currentTime State.currentBeat += 1 if State.currentBeat == NBEATS: State.currentBeat = 0 """Check play gesture""" if myo.pose == libmyo.Pose.fingers_spread: myo.pose = None print("add note") myo.myo.vibrate("short") s = State.currentGroup[State.currentSample] State.score[State.currentBeat].append(s) elif myo.pose == libmyo.Pose.double_tap: myo.pose = None print("play note") myo.myo.vibrate("short") State.currentGroup[State.currentSample].play() elif myo.pose == libmyo.Pose.fist: myo.pose = None print("switch note") myo.myo.vibrate("medium") State.currentGroup[State.currentSample].play() pygame.mixer.stop() State.currentState = State.LISTENING else: pass else: pass finally: print("Shutting down...") say("Thank you for using our demo. Vocomi is powered by Nuance speech technologies and the Myo armband.") hub.shutdown() pygame.quit()
from __future__ import print_function import myo as libmyo from firebase import firebase libmyo.init() import time class Listener(libmyo.DeviceListener): """ Listener implementation. Return False from any function to stop the Hub. """ interval = 0.5; # Output only 0.05 seconds firebase = firebase.FirebaseApplication('https://rock-paper-scissors-game.firebaseio.com/', None) def __init__(self): super(Listener, self).__init__() self.orientation = None self.pose = libmyo.Pose.rest self.emg_enabled = False self.locked = False self.rssi = None self.emg = None self.last_time = 0 def post_result(self): result = self.firebase.get('/user1', None)
from __future__ import print_function import myo as libmyo; libmyo.init('E:\\Documents\\Fall 2015\\Fall 2015_\\CSE442\\crazyflie-clients-python\\raf') import time import sys import sling as Crazy import math class Listener(libmyo.DeviceListener): """ Listener implementation. Return False from any function to stop the Hub. """ interval = 0.08 # Output only 0.05 seconds def __init__(self): super(Listener, self).__init__() self.orientation = None self.pose = libmyo.Pose.rest self.emg_enabled = False self.locked = False self.rssi = None self.emg = None self.acceleration = None self.gyroscope = None self.last_time = 0 self.TakeOff = True available = "radio://0/80/2M" self.le = Crazy.Sling(available) self.gotCenterYaw = False;
print("X-axis failure") # myo.vibrate("short") elif quat.y > 0.8: print("Y-axis failure") # myo.vibrate("short") elif quat.z > 0.1: print("Z-axis failure") # myo.vibrate("short") else: print("Good job!") def set(self, keyPress): print('set') if (keyPress == " "): print("hi") #originPoint = [quad.w, quad.x, quad.y, quad.z] libmyo.init('~/Downloads/sdk/myo.framework') #expects list listener = Listener() hub = Hub() hub.run(1000, listener) try: while True: sleep(0.5) except KeyboardInterrupt: print('\nQuit') finally: hub.shutdown() # !! crucial
__author__ = 'James Boggs' __version__ = 'alpha 0.03' # Just reads Myo input and writes it to a serial port for an Arduino # to read. A stand-in for reading a Myo directly from the Arduino, # which will come later. import serial import myo as libmyo libmyo.init('C:\\Users\\James\\Documents\\Coding\\MyoArm\\myo-sdk-win-0.9.0\\bin') from time import sleep HUB_INTERVAL_MS = 1000 SERIAL_OUT_PORT = 2 #COM3 if __name__ == '__main__': # set up myo listener hub = libmyo.Hub() feed = libmyo.device_listener.Feed() hub.run(HUB_INTERVAL_MS, feed) # set up serial communications ser = serial.Serial(SERIAL_OUT_PORT) # begin Myo loop try: myo = feed.wait_for_single_device(timeout=10) if not myo: print("No Myo connected after 10 seconds.") raise
__author__ = "Anderson" import myo as libmyo libmyo.init("sdk/myo.framework") import time import sys import pygame pygame.mixer.init() class Listener(libmyo.DeviceListener): """ Listener implementation. Return False from any function to stop the Hub. """ currentBoard = "cena" cena = "cenaJohn.wav" ironman = "ironman.wav" currentMusic = "cenaJohn.wav" interval = 0.05 # Output only 0.05 seconds def __init__(self): super(Listener, self).__init__() self.orientation = None self.pose = libmyo.Pose.rest self.emg_enabled = False self.locked = False self.rssi = None
self.z1=quat.z self.w1 = quat.w init("/users/dominic/downloads/sdk/myo.framework") hub = Hub() hub.run(1000, Listener(),lil_sleep=0.01) try: while True: sleep(0.5) except KeyboardInterrupt: print('\nQuit') finally: hub.shutdown() # !! crucial
''' Created on 2016.5.21 edited on 2016.5.31 @Author: Gan This program use to get 2 Myos' angle in real time. the imported Myos_angle moudle has some functions that can caculate the angle from both ACC and GRY signals. ''' import Myos_angle from myo import init, Hub, Feed, StreamEmg import time import numpy as np init() # init the Myo feed = Feed() # use feed class hub = Hub() angle = [0,0] # init 2 Myo's angle t_start = 0 # use to store the angle_updata function's start time t_s = 0 # use to store the end time T = 200 # Total time t1 = 0 # to record the runing start time t2 = 0 # to record current time which_MYO = [0,1] # choose which myo to use. threre are 4 types:[0],use the frist Myo; [1]:use the second; [0,1]or[1,0]:use both hub.run(1000, feed) open('Angle&w.txt', 'w').close() T = int(input("input time(s):")) try: while True: myo = feed.get_devices() print(myo) t1 = time.time()
# Copyright (C) 2014 Niklas Rosenstein # All rights reserved. import os, sys sys.path.append(os.path.join('Users', 'raychen', 'Documents', 'Design', 'Hackathons', 'LAHacks', 'LeapCAD', 'myo-python')) import myo from myo.lowlevel import pose_t, stream_emg from myo.six import print_ import random myo.init() SHOW_OUTPUT_CHANCE = 0.01 r""" There can be a lot of output from certain data like acceleration and orientation. This parameter controls the percent of times that data is shown. """ class Listener(myo.DeviceListener): # return False from any method to stop the Hub def on_connect(self, myo, timestamp): print_("Connected to Myo") myo.vibrate('short') myo.request_rssi() # def on_rssi(self, myo, timestamp, rssi): # print_("RSSI:", rssi) def on_event(self, event): r""" Called before any of the event callbacks. """
def on_pose(self, myo, timestamp, pose): print(pose) if pose=="fist": print("FIRED!") queue.publish('fire', json.dumps({ 'fire':True })) #def on_accelerometer_data(self,myo, timestamp, acceleration): # Do something with acceleration data def on_gyroscope_data(self, myo, timestamp, gyroscope): queue.publish('position', json.dumps({ 'th':gyroscope.y })) #print(gyroscope.y) myo.init('C:/myo-sdk-win-0.9.0/bin') hub = Hub() hub.run(1000, Listener()) try: while True: sleep(0.5) except KeyboardInterrupt: print('\nQuit') finally: hub.shutdown() # !! crucial
__author__ = 'e_tak_000' # The work is based over Niklas Rosenstein's myo-python import myo as libmyo; libmyo.init() import time import os import sys import math class Listener(libmyo.DeviceListener): def on_connect(self, myo, timestamp): print("Hello, Myo!") myo.vibrate('short') myo.vibrate('short') myo.vibrate('short') def on_disconnect(self, myo, timestamp): print("Goodbye, Myo!") def on_orientation_data(self, myo, timestamp, quat): print("Orientation:", quat.x, quat.y, quat.z, quat.w) def on_pose(self, myo, timestamp, pose): if pose == libmyo.Pose.fist: print("Don't show me 'ya fist!") return False # Stops the Hub
import myo as libmyo; libmyo.init('/Users/Nicholas/Documents/cs/git/hue-myo/sdk/myo.framework') import time import sys import credentials import LightController class Listener(libmyo.DeviceListener): def __init__(self): # myo super(Listener, self).__init__() self.orientation = None self.pose = libmyo.Pose.rest self.locked = False # hue lights creds = credentials.get_credentials() self.lc = LightController.LightController(creds["ip_addr"],creds["username"]) self.lc.reset_lights_to_white() def on_connect(self,myo,timestamp,firmware_version): """ Is called when the Myo arm band is connected via Bluetooth. """ myo.vibrate('short') time.sleep(1) def on_pose(self,myo,timestamp,pose): """ Is called whenever the Myo arm band detects a new pose. """
Listener.temp = quat.x else: print("Lower your hand/n") sleep(1) Listener.temp = quat.x # newx = 1 # Listener.temp = quat.x # sleep(1) # else: # newx = 15 # Listener.temp = quat.x # sleep(1) # print newx # response = urllib2.urlopen('http://rpi.michaelbailey.co/control?dc='+str(newx)) # html = response.read() init() hub = Hub() hub.run(1000, Listener()) try: while True: sleep(0.5) except KeyboardInterrupt: print('\nQuit') finally: hub.shutdown() # !! crucial
def __init__(self): myo.init() self.collector = Collector() self.hub = myo.Hub() self.hub.set_locking_policy(myo.locking_policy.none) self.hub.run(1000/30, self.collector)
addon_dir = xbmc.translatePath( my_addon.getAddonInfo('path') ) libdir = os.path.join( addon_dir, 'resources', 'lib' ) sys.path.append(libdir ) import myo print '############################################' xbmcgui.Dialog().notification(TITLE,'Module loading') ''' if __name__ == '__main__': monitor = xbmc.Monitor() while not monitor.waitForAbort(10): xbmc.log("hello addon! %s" % time.time(), level=xbmc.LOGDEBUG) ''' myo.init(libdir) xbmcgui.Dialog().notification(TITLE,'Starting 2') class Listener(myo.DeviceListener): # return False from any method to stop the Hub def on_connect(self, myo, timestamp): myo.vibrate('short') myo.request_rssi() def on_rssi(self, myo, timestamp, rssi): pass def on_event(self, event): pass def on_event_finished(self, event):