Skip to content

Instantly share code, notes, and snippets.

@MexsonFernandes
Created April 5, 2019 13:38
Show Gist options
  • Select an option

  • Save MexsonFernandes/ae332b7575b147c206f74971a4089d09 to your computer and use it in GitHub Desktop.

Select an option

Save MexsonFernandes/ae332b7575b147c206f74971a4089d09 to your computer and use it in GitHub Desktop.
Python code for data collection from Neurosky Mindwave Mobile headset device
import numpy as np
import pandas as pd
import sys
import json
import time
from telnetlib import Telnet
# Initializing the arrays required to store the data.
attention_values = np.array([])
meditation_values = np.array([])
delta_values = np.array([])
theta_values = np.array([])
lowAlpha_values = np.array([])
highAlpha_values = np.array([])
lowBeta_values = np.array([])
highBeta_values = np.array([])
lowGamma_values = np.array([])
highGamma_values = np.array([])
blinkStrength_values = np.array([])
time_array = np.array([])
tn=Telnet('localhost',13854);
start=time.clock();
i=0;
tn.write('{"enableRawOutput": true, "format": "Json"}');
outfile="null";
if len(sys.argv)>1:
outfile=sys.argv[len(sys.argv)-1];
outfptr=open(outfile,'w');
eSenseDict={'attention':0, 'meditation':0};
waveDict={'lowGamma':0, 'highGamma':0, 'highAlpha':0, 'delta':0, 'highBeta':0, 'lowAlpha':0, 'lowBeta':0, 'theta':0};
signalLevel=0;
while time.clock() - start < 30:
blinkStrength=0;
line=tn.read_until('\r');
if len(line) > 20:
timediff=time.clock()-start;
dict=json.loads(str(line));
if "poorSignalLevel" in dict:
signalLevel=dict['poorSignalLevel'];
if "blinkStrength" in dict:
blinkStrength=dict['blinkStrength'];
if "eegPower" in dict:
waveDict=dict['eegPower'];
eSenseDict=dict['eSense'];
outputstr=str(timediff)+ ", "+ str(signalLevel)+", "+str(blinkStrength)+", " + str(eSenseDict['attention']) + ", " + str(eSenseDict['meditation']) + ", "+str(waveDict['lowGamma'])+", " + str(waveDict['highGamma'])+", "+ str(waveDict['highAlpha'])+", "+str(waveDict['delta'])+", "+ str(waveDict['highBeta'])+", "+str(waveDict['lowAlpha'])+", "+str(waveDict['lowBeta'])+ ", "+str(waveDict['theta']);
time_array = np.append(time_array, [timediff]);
blinkStrength_values = np.append(blinkStrength_values, [blinkStrength]);
lowGamma_values = np.append(lowGamma_values, [waveDict['lowGamma']]);
highGamma_values = np.append(highGamma_values, [waveDict['highGamma']]);
highAlpha_values = np.append(highAlpha_values, [waveDict['highAlpha']]);
delta_values = np.append(delta_values, [waveDict['delta']]);
lowBeta_values = np.append(lowBeta_values, [waveDict['lowBeta']]);
highBeta_values = np.append(highBeta_values, [waveDict['highBeta']]);
theta_values = np.append(theta_values, [waveDict['theta']]);
lowAlpha_values = np.append(lowAlpha_values, [waveDict['lowAlpha']]);
attention_values = np.append(attention_values, [eSenseDict['attention']]);
meditation_values = np.append(meditation_values, [eSenseDict['meditation']]);
print (outputstr);
if outfile!="null":
outfptr.write(outputstr+"\n");
person_name = input('Enter the name of the person: ')
blink_label = input('Enter left or right eye blink(1 for left, 2 for right): ')
time_starting = input('When does TGC start: ')
lefty_righty = input('Is the person left-handed or right-handed: ')
time_blinking = input('The time of the blink: ')
# Data Recorded for a single person
data_row = pd.DataFrame({'Name': person_name, 'attention': [attention_values], 'meditation': [meditation_values], 'delta': [delta_values], 'theta': [theta_values], 'lowAlpha': [lowAlpha_values], 'highAlpha': [highAlpha_values], 'lowBeta': [lowBeta_values], 'highBeta': [highBeta_values],
'lowGamma':[lowGamma_values] , 'highGamma': [highGamma_values], 'blinkStrength': [blinkStrength_values], 'time': [time_array], 'LOR': blink_label})
# Reading the data stored till now
dataset = pd.read_csv('data_eeg.csv')
from numpy import nan as Nan
dataset = dataset.append(pd.Series([blink_label, person_name, [attention_values], [blinkStrength_values], [delta_values]
, [highAlpha_values], [highBeta_values], [highGamma_values], [lowAlpha_values], [lowBeta_values], [lowGamma_values], [meditation_values],
[theta_values], [time_array], time_starting, lefty_righty, time_blinking], index=['LOR', 'Name', 'attention', 'blinkStrength', 'delta', 'highAlpha', 'highBeta', 'highGamma', 'lowAlpha', 'lowBeta', 'lowGamma', 'meditation', 'theta', 'time', 'time_start', 'LTYRTY', 'time_blink']), ignore_index = True)
#Appending and storing the data in the same csv
#dataset.append(data_row)
dataset.to_csv('data_eeg.csv')
tn.close();
#outfptr.close();
@miniature-pug

Copy link
Copy Markdown

Hey, this is an amazing piece of code! I'm trying to get raw-wave data (1D data that has not been segregated into various frequency spectrums) from my headset. I tried putting 'enableRawOutput' as false, but it doesn't seem to effect anything. I tried looking into data that the headset sends over and found a few new categories like 'familiarity' and 'mental_strength' but couldn't find raw-wave output/EEG_signal. I know that it is possible via MATLAB(I tried, it worked but ran into a lot of technical issues with thinkgear.dll) but I'm specifically looking for python implementation. If you happen to know something, can you guide me in the right direction?

@MexsonFernandes

Copy link
Copy Markdown
Author

https://github.com/MexsonFernandes/EEG-controlled-Robot-using-Neurosky-Mindwave-Mobile2 kindly check this repo for raw EEG. I have coded it in C# and had got better results with good response time. So try to use it and post your experience.

@svr1998

svr1998 commented Feb 15, 2020

Copy link
Copy Markdown

Hey, I am trying to build an EEG controlled bionic arm. I am trying to run this code but I am stuck at tn=Telnet('localhost',13854);. The error message reads - "Name or service not known". Could you please help me out?

@gmierz

gmierz commented Feb 29, 2020

Copy link
Copy Markdown

@svr1998 that would mean that the ThinkGear Connector is probably not running and/or unable to connect to the headset.

For anyone who makes it to this script, I've built something more formal here (use it with --output path/filename --no-lsl to get all the data into a CSV file without running LSL): https://github.com/gmierz/mindwave-lsl

@kesavsivakumar

Copy link
Copy Markdown

How to increase the samples per second ? As of this code i m hardly getting 1 sample per second . I need around 250+ samples per second .

@gmierz

gmierz commented Feb 9, 2021

Copy link
Copy Markdown

@kesavsivakumar those are the frequency measurements which return data at 1 Hz. You want to look at the raw data to get the higher sampling rate.

@kesavsivakumar

Copy link
Copy Markdown

@kesavsivakumar those are the frequency measurements which return data at 1 Hz. You want to look at the raw data to get the higher sampling rate.

@gmierz How to extract the raw data , lately i have been trying to extract raw eeg data using java script (node-think-gear-socket) but I feel like ,I always lead to a dead end .

@gmierz

gmierz commented Feb 12, 2021

Copy link
Copy Markdown

@kesavsivakumar check out the code I wrote here: https://github.com/gmierz/mindwave-lsl/blob/master/mindwavelsl/outlet.py#L19

There's some examples of how you can use this in test_*.py at the root of the repo.

When you create the MindwaveLSL object, initialize it with run_lsl=False so you can pull the data without needing the LSL bits.

You'll want to use the make_sample function, and then check the data at index 8 of the sample, that will be the raw eeg value. You can see the ordering of the fields here: https://github.com/gmierz/mindwave-lsl/blob/master/mindwavelsl/constants.py#L17

@kesavsivakumar

Copy link
Copy Markdown

@gmierz Thanks mate!

@HakerX-crypto

Copy link
Copy Markdown

Hey, I have questions to ask as i am noob in python (have some knowledge) as i am making fully functional car with raspberry pi which will have rc ,egg, as well internet, (auto pilot) anticrash so lets move to questions no 1) will i have to change the script for eeg control( mean to put a value )2) will there is any errors come when i will run 3 python script simultaneously 3) how to make python script for obstrical avoidance (as i did nt find the way no where )

@urmi2927

urmi2927 commented Mar 7, 2022

Copy link
Copy Markdown

Capture
someone please help

@carlhabib

Copy link
Copy Markdown

It should be
tn.write(str.encode('{"enableRawOutput": true, "format": "Json"}'))

@urmi2927

urmi2927 commented Sep 4, 2022

Copy link
Copy Markdown

Does anyone solve this error?
image

@gmierz

gmierz commented Sep 6, 2022

Copy link
Copy Markdown

@urmi2927 change '\r' to b'\r'

@MahdiAlnaimi

Copy link
Copy Markdown

can you explain this line please
tn=Telnet('localhost',13854);

@gmierz

gmierz commented Nov 30, 2022

Copy link
Copy Markdown

That's the telnet connection used to communicate data between the device and your computer. I suggest using this package so you don't get bogged down by these details: https://github.com/gmierz/mindwave-lsl

@MahdiAlnaimi

Copy link
Copy Markdown

I tried this link thank you for shearing it, but i still not understand how can it work and how I can connect this app with my headset? is there any information should I add it? i hope someone help me in this Issue

@gmierz

gmierz commented Dec 15, 2022

Copy link
Copy Markdown

You need to get the Thinkgear connector working first, then that'll provide you with a host and port to use in the package above (see the help section of the command).

@MahdiAlnaimi

Copy link
Copy Markdown

WHEN i trien the modul I get an error in related with pyxdf

@Deepucdactvm

Copy link
Copy Markdown

is it possible to get raw eeg data

@gmierz

gmierz commented Jul 13, 2023

Copy link
Copy Markdown

@mwahid2001

Copy link
Copy Markdown

is it possible to enable raw eeg data from mindwave neurosky 1, the headset with RF dongle connecting through usb port? and if how can i do that?

@Deepucdactvm

Copy link
Copy Markdown

Yes, but you need to make sure you do a write like this to enable it: https://github.com/gmierz/mindwave-lsl/blob/21827fe80f034e0a1d6b5da6b9165c6d0574ac23/test_mouse_movements.py#L19

but I tried it is not possible to get raw EEG data

@Deepucdactvm

Copy link
Copy Markdown

I'm using another single electrode FT$S mind link EEG Headband, is it any method to receive live raw EEG data from it

@PrinceEGY

Copy link
Copy Markdown

I created this package to ease the connection and data collection with the mindwave mobile 2 headset, you can check and try it here https://github.com/PrinceEGY/pymindwave2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment