Monday, November 18, 2013

OpenBCI Alpha Wave Detector

Part of what excites me so much about EEG hacking is the idea that maybe I can control things with just my mind.  Once you gain any experience at all with EEG signals, however, you realize just how hard a task that can be.  So, start simple.  Start with what's easy.  Build from there.  With EEG, "easy" are Alpha waves.  Alpha waves is nice a simple EEG waveform that shows up fairly strongly around 10 Hz.  It is a great target for making one's first brain controlled hack.  And I just did it myself...check it out!  It's completely computer-free and feels like magic!


Electronics Setup

For this hack, I used the parts shown in the picture below.  It's an OpenBCI board sitting on an Arduino Uno (the Uno is completely hidden in this photo under the white OpenBCI board), a cheap peizo buzzer, and a basic red LED.  I put a 330 ohm resistor in series with the LED and in series with the buzzer to limit the current (a practice recommended in all of the Arduino learning examples).  Because I wanted to be completely computer-free, the whole thing is powered by a 9V battery adapter.

OpenBCI plus Arduino Uno plus LED, Piezo Buzzer, and 9V Battery.

EEG Setup

This hack uses two off-the-shelf reusable EEG electrodes.  I plug them into my Open BCI board using the adapter cable that I made.  I placed the first electrode (the reference) on the top of my head, a little towards the front ("Fz").  I placed the second electrode on the back of my head, just above the bump on the back of the head (the "inion") and a little to my left (aka "O1").  I worked the electrodes under my hair and stuck them in place using ten20 conductive paste.  This time, I used the small jar of it instead of the tube...the jar is much easier to work with.

My setup, including the colorful homemade adapter cable for
attaching my two EEG electrodes.
Arduino Processing Software

Unlike all of my previous experience with EEG hacking, where a PC was involved for doing the signal processing, today I will be doing all of the EEG processing on the Arduino itself.  The Arduino is not a computational power house, so we have to be reasonable in our expectations when doing signal processing on the Arduino.

To detect Alpha waves in EEG signals, there are several things that you need to do:

  1. Filter to remove strong interfering signals (60 Hz and DC drift)
  2. Filter to focus on the frequencies of interest (in this case, Alpha are ~10 Hz)
  3. Decide if there is enough Alpha (and just Alpha) to activate the LED and buzzer

The full details of my signal processing chain is a long story that will get its own post.  The Arduino's limited bit depth (32-bits is the maximum data type) and limited speed with floating point operations means that you cannot use sharp filters.  Instead, you have to use relatively gentle filters such as "biquad" filters (which are a form of 2nd order IIR filter).  To generate the filter coefficients, I used code that I found here.

After doing my filtering, I then compute the RMS power of the signal.  I simply square the single, apply a low-pass filter (another biquad from the code above), and take the square root.  This gives you a running RMS estimate of the signal amplitude.  Because of my filtering, this gives me a running estimate of the Alpha amplitude.  I then light my LED and sound my buzzer based on the amount of Alpha energy.

Thinking Things to Action

So, with this setup, you've got yourself a self-contained device that responds to your brain waves.  It doesn't have to be just an LED or buzzer, either.  It could be a robotic arm swinging a sword (to fight off pirates, of course), or a cool flashing hat for dance parties, or an animatronic flower that blooms with your thoughts.  Or maybe you like the idea of getting this kind of neurofeedback to see what is happening when you meditate (change the filter from 10 Hz Alpha up to 20 Hz Beta).  Or, maybe you could use it simply for weirding-out your friends and co-workers...what with the strange wires coming out of your head and all.  There are so many possibilities.

To me, controlling things with your brain in this way seems a bit magical...but I made this thing myself, so I know that it's not magic...it's hacking!

Follow-Up: A long time has passed, but I think that I found the code for this hack.  This was prompted by folks on the OpenBCI forum trying to do it themselves!  Cool!

Follow-Up:  I extended this work to control a six-legged robot with my brain waves!

Tuesday, November 12, 2013

Measuring EOG with my EEG Setup

In a previous post, I discussed how you can use your EEG electronics to measure ECG to see the changing electrical potential in your body due to your heart beats.  In this post, I'm going to use my EEG electronics to measure EOG to see the changing electrical potential in your head due to eye motion.  "Eye artifact" is a commonly-seen type of corruption seen in EEG, so it is important to have a feeling for the effect of the eye when trying to study the brain.

Electrodes on my face to measure my EOG due to eye motion.
Setup

As you can see in the picture above, I used three electrodes: one above my eye, one below my eye, and one to the side of my eye.  I have no experience recording EOG, so I don't know what standard practice is.  This is just what I happened to try.

In my setup, the primary electrodes were the ones above and below my eye.  The electrode on the side was used only as my driven ground (or "bias" if that is your preferred language).  It turns out that this connection wasn't really necessary (EOG signals are very strong), so you might be able to omit it.

The electrodes themselves are reusable gold-plated electrodes commonly used in EEG.  Mine are similar to these.  I stuck them to my skin using standard Ten20 EEG paste.

I plugged these electrodes into my OpenBCI electronics using my new, homemade adapter cable.  My OpenBCI board was mounted to an Arduino Uno, which was pumping the data to my PC for logging and post-test analysis.


Results

Once I turned everything on and started collecting data, I found some really interesting things.  Again, I have no experience doing this, so I had no idea what to expect.  Below is a graph of the voltage recorded during a period of time where I was looking forward, I then turned my eyes to look upward (keeping my head itself fixed), and then returned my eyes to looking forward.  As you can see, the voltage clearly tracks the motion of my eye.  When my eye was "up", the voltage was up.  While that seems so sensible, it was not what I expected at all.

Voltage recorded between an electrode above my eye and an electrode below my eye.

What was I expecting?  Well, I do have some experience seeing muscle artfiact in EEG signals due to clenching my jaw.  Muscle artifact shows itself as a hashy, noisy, high-frequency signal.  Since it takes muscles to move your eye, I assumed that "eye artifact" would also be hashy and noisy.  I was wrong.   It is a low frequency signal that reflects the actual position of the eye...not the changing position of the eye.  Even a quick jump over to read about EOG on Wikipedia would have told me that.

To paraphrase Wiki, EOG measures the local effect of the electrical potential that always exists between the front and back of your retina.  So, changing the orientation of your eye changes the how much each electrode "sees" the positive side of the retina versus how much it sees the negative side of the retina.  Cool!

Zooming out on my data, let's look at a longer time span with more eye motion.  The plot below shows the EOG data recorded for a variety of eye positions...looking forward, looking up, and looking down.  As you can see, there is a clear relationship between the measured voltage and the eye position.  Clearly, this system could be used as an eye tracker to tell (roughly) where your eyes are looking.  I find this very exciting.

EOG data recorded for multiple eye positions.
Effect of Filtering

The signals shown above were plotted after filtering.  Whenever I present EEG/ECG/EOG data, I filter it to get rid of very high frequency noise and to get rid of drifting of the DC component of the signal.  For EEG, I often filter away the signal energy that is below 0.5 Hz.  Since I do not care about EEG signals this low, removing these low-frequency components makes the plots much easier to follow.  But, if you use these filter settings for EOG, you get a completely different type of EOG plot than the nice ones shown above.

My previous EOG plots were bandpass filtered to only include energy between 0.02 Hz and 50 Hz.  Below is a plot of the same EOG data, but using my typical EEG passband (0.5 Hz to 50 Hz).  Notice that the plot looks very different.

Same EOG data but filtered to remove low-frequency energy below 0.5 Hz.
In this plot, you basically only seen the moment of change from one eye position to the next.  So, if all you cared about whether the eye is *moving*, this filter setting is good.  But, if you want to know where the eye is pointing, this is the wrong filter setting...you really need to lower that low-frequency cutoff from the 0.5 Hz value down to something like the 0.02 Hz value that I showed in the previous graphs.

To be truthful, the graph above is what I first saw when looking at my EOG data.  This is the graph I saw because I was viewing the data using my usual EEG filters (0.5-50 Hz).  As a result, I thought EOG was only good for measuring eye motion.  It wasn't until I started exploring the data in greater detail (changing one's normal filter settings is a great way to explore the data) that I discovered the plots that I show at the top.  When I lowered my low-frequency cutoff to 0.02 Hz and got those plots, that's when I discovered that  EOG is really about measuring the change in DC potentials due to your eye position.  What a fun discovery!

Next Steps

So, that's my story of recording EOG with my EEG setup.  It was really fun.  My next step is to put electrodes to the sides of my eyes so measure side-to-side motion in addition to up-and-down motion.  Also, I might try my homemade electrodes to see how well they do.

The real challenge with EOG is to keep the electrodes stuck on your face as you move your head around.  One thing that I did try was to use my self-adhesive ECG electrodes.  These stuck great!  But, they sure did look silly...

ECG electrodes stick better, but look much more silly.
I think that I'll just stick with the small EEG electrodes.

Follow-Up: Want to get the data used in this post?  Try my github!

Making an EEG Electrode Adapter

My earlier post on making my own EEG electrodes was surprisingly popular.  Thanks, all!  But, for some folks, it might just be easier to purchase EEG electrodes off the shelf.  If you buy your electrodes, they're likely to come with connectors on the ends.  In order to use these electrodes with an OpenBCI board, you'll need to either cut the connectors off, or you'll need to make an adapter cable.  Since I tend to play with a variety of electrodes (both EEG and ECG) and since many types of electrodes use this same connector, I thought that it would be good to make an adapter.  This post is about how I made my adapter cable.  Here's what it looks like when I was done.



Parts

To make the adapter cable, you need the connectors that mate to the EEG electrode, you need some wires, and you need some connectors that mate to the OpenBCI board.

The OpenBCI board simply uses pin headers with a 0.1" spacing.  Therefore, for "connectors", you can use any of the inexpensive jumper wires that are used throughout the hobby world for connecting to Arduino.  For this adapter cable, you need female pin headers.  Adafruit sells a fine pack of 40 female/female jumper wires (P/N 266) for $6.95.  The 40 wires come with the connectors already attached.  The wires also come attached to each other as a ribbon cable, which is very convenient for keeping the cables in order.

Female/Female Jumper Wires from Adafruit
For the EEG electrodes, they usually use "touchproof" connectors.  This are simple singe-conductor connectors where the metal part is completely shrouded in plastic.  They are fairly standardized, though the diameter of the connection can vary between 1mm and 2mm.  All of my electrodes are 1.5mm.  The jacks that mate to these electrodes can be purchased from Plastics One.  Specially, I chose to buy the panel mount, front-loaded, threaded connectors (P/N 36145) shown in the pictures below.  When bought in small numbers, they're $3.14 each.  That's pricey!

Jacks for Touchproof Connectors.  From Plastics One.
Assembly

The OpenBCI board has 11 connections that I might want to use.  So, I took the ribbon of 40 jumper wires and peeled off a single strip that contained 11 wires.  I then cut it in half to that one end had the female pin headers and the other end was just wire.


Then, I peeled apart the ends of the wire and stripped the ends.  As I prepared to solder on the touchproof jack, I slipped a piece of shrink tube over the end of the wire so that I could make it look nice when I was done.  I'm proud of myself for remembering to do the shrink tube.  I nearly always forget.  Not this time!

Preparing to solder the first jack.

After I soldered it on, I pulled the shrink tube up over the joint, applied some heat, and got a nice looking connection.

First jack is attached.  Nice use of shrink tube!
I then repeated the process for all the other wires that I was going to use.  Here's a picture of me soldering on the second jack.

Preparing to solder the second jack.
Completion

For my immediate testing, I did not need all 11 connections...I only needed four.  So, I only soldered on four jacks.  You can see my "completed" adapter cable assembly below.

My adapter cable with 4 connections.  I'll add the others when I need them.
Note that I added a piece of electrical tape around the ribbon cable to help keep it together.  I had overly separated one of the individual wires and it was threatening to come loose.  I little electrical tape saved the day!  And it makes it look fancy.

Using It

As you can tell by the photo at the top of this post, the adapter cable works great for interfacing OpenBCI to off-the-shelf electrodes.  I've used it with my EEG electrodes for follow-on measurements of my Mu-waves and with my ECG electrodes for checking my heart signals.  It's a great adapter cable to have in my EEG Hacker toolbox!


Wednesday, November 6, 2013

Waveforms from Homemade Electrodes

As follow-up to my surprisingly popular post on my homemade electrodes, ERPOLOGY asked to see the EEG traces.  Well, since making graphs is one of my most favorite things to do (NERD ALERT!), I'm happy to oblige.

First, as a reminder of what I did, I built some EEG electrodes out of really cheap materials.  To see how well they worked, I stuck them to my head using Ten20 conductive paste in locations approximating Cz (top of head) and C3 (side of head).  The spectrogram above shows the data that I recorded.  As you can see, the test contains several test conditions:
  1. Closed Eyes (to see Alpha Waves)
  2. Open Eyes and Relaxed (to see Mu Waves)
  3. Open Eyes While Moving Hand (to suppress my Mu Waves)
Time-Domain Plots

OK, now let's make the new plots.  First, I've chosen short excerpts from each of the three periods.  I've plotted them below.  Note that these plots are zoomed way in so that you can count the period of the Alpha waves and of the Mu waves.

First, below, I show a trace from when my eyes were closed and I was generating Alpha Waves due to my Posterior Dominant Rhythm (PDR).  Remember, my electrodes were not on the back of my head -- they were on the side of my head.  So the PDR Alpha waves are not as pure looking as you might expect.  If you count the peaks, though, you'll see that there are about 9-10 cycles per second (ie, 9-10 Hz), which is what we saw in the spectrogram at the top.


Next, below, I show a trace from when my eyes were open and I was trying very hard to be relaxed (an oxymoron).  I was successful in generating some Mu waves.  They're shown below.  If you could the peaks, you'll get 10-12 waves per second (depending on how you count).  Based on the spectrogram, the frequency of my Mu waves is a little bit higher than my PDR Alpha waves.  This is probably confirmed by the peak-counting in the plot below.


The last time-domain plot, below, is for when I open and close my hand.  This should suppress my Mu waves.  In the spectrogram, they do appear to be absent.  In the plot below, they appear to be absent as well.  Good.



Frequency-Domain Plot

Before we finish, let's go back to the frequency domain...but let's plot a regular spectrum and not a spectrogram.  While the spectrogram is great for getting a sense of what is happening throughout the test, it is not the best tool for being quantitative.  Sometimes a simple spectrum plot is better.  

For the spectrum plot below, I took a long sample of each activity (10s of seconds, several thousand data points), I performed a series of 512-point FFTs and I averaged the FFT results together to get a nice, smooth spectrum for each condition.  By plotting the averaged spectrum for each condition all on the same graph, I can quantify the differences between the three conditions.  Here are the results:


As you can see, the Alpha waves were definitely at a lower frequency (9.3-9.8 Hz using my data reading cursor) than my Mu waves (11.7 Hz).  As I mentioned during the discussion of the time-domain plots, the spectrogram showed this fairly well.  But, a basic spectrum plot like this one makes it much easier to see and quantify the difference between the two.

Also, this graph implies that the Mu waves were about half the amplitude of the Alpha waves.  While it is true that Alpha are clearer in the spectrogram, which suggests that the Alpha were stronger, the primary reason that the Alpha were clearer is because I was able to sustain the Alpha waves more steadily than the Mu waves.  Detailed examination of the data shows that my Mu waves came and went every few seconds.  Therefore, in the averaged FFT plot, the apparent amplitude of the Mu waves will appear to be smaller simply because it includes all those short periods where the Mu waves temporarily went away.  That's a risk with using a heavily-averaged spectrum plot.  You gotta know your tool.

Finally, this spectrum plot nicely shows how clenching my hand (the red trace) suppresses the Mu waves completely.  Again, that was clear in the spectrogram, but this plot shows it very nicely as well.

Implications

With this extra detailed view of the data, you can start to see how you could design a signal processing chain to detect Mu waves.  Looking at the frequency plot, it is clear that you would need a really tight filter...maybe about 1 Hz wide.  For me, the filter would need to be centered on 11.7 Hz.  You might have your own special frequency.  Finally, because this plot shows that the energy in my PDR Alpha overlap with my Mu, you might want to sense the frequencies on either side of your Mu waves.  If there is energy on either side of Mu, then it's likely that the energy inside your Mu frequency band is from something else...such as PDR Alpha.

Without a graph like this, designing the signal processing would be much harder.  With this graph, I get all sorts of ideas.  This is why I like graphs so much...they can give quick insight into complex data.

If you've made it this far...thanks for reading!  You're awesome!

Follow-Up: Want to see my data from this experiment?  Check out my github!

Tuesday, November 5, 2013

Homemade Passive Electrodes

After the challenge of getting oneself some decent EEG electronics, the next hardest part is getting some decent EEG electrodes.  Sure, there are lots out there that can be bought, but some folks have no interest in paying $8-$20 per electrode (plus shipping) because they know that they need to buy 6-10 of these electrodes and, well, that becomes a lot of money.  So, I decided to try to build my own homemade EEG electrodes.  Here's my story...(and for you impatient folks...yes, there's a fairly happy ending)

Wearing my homemade passive EEG electrodes.
(Beware of cheap cameras and flourescent lights)

The Idea: Use Cheap Bits from the Hardware Drawer

When I look at passive EEG electrodes, I just see a piece of flat metal with a wire attached.  Sure, I see the use of fancy metals (gold, silver / silver-chloride), but is that really necessary?  For EEG research or EEG medicine, the quality and repeatability provided by the fancy metals is necessary.  For EEG Hacking?  I'm not so sure.  So, if an electrode is just a piece of flat metal with a wire attached, it seems like I should be able to build one myself.

I started by searching through my hardware drawer to find a suitable piece of metal that is small and flat.  I found some lock washers with a solder tab (see picture below-left).  It is a very basic and inexpensive component.  I'm pretty sure that mine are from Mouser and cost $0.24 each.  You can probably get them cheaper.



I then grabbed a piece of wire, stripped the end, and inserted it into the tab on the washer.  Looks like it'll do nicely (see picture above-right).  To soldered the wire to washer, I simply placed it in my plastic-gripped vice and applied heat and solder (pics below).  If you don't have a vice, a traditional "3rd hand" soldering fixture would have worked fine, too.  This is not fancy work that we're doing here.


Once the wire was soldered to the washer, I realized that I should have added a piece of shrink tube over the wire to cover the solder joint.  But, once it was soldered together, it was too late to add the shrink tube (the other end of my wire already had a connector on it).  Dang!  When I made a second electrode, I remembered to add the shrink tube on that one.  As you can see below, the black shrink tube makes the second electrode look much nicer than the first one.

My First and Second Homemade Passive Electrodes.  On the second one, I remembered to add a piece of shrink tube to cover the solder joint.  It looks much better.
With the working end of the electrode complete, I could consider the other end of the wire...the end where normally on would add a connector for plugging into the EEG electronics.  Since I stole my wire from an old ECG lead wire, I have the "touchproof" connectors on the end of my electrodes.  But, you don't need anything that fancy if you want to spend less money.

The least expensive approach for "connectors" would be to solder on a male or female pin header, which are only about $0.04 per connection.  This kind of connection is perfect for connecting to OpenBCI, which is built around traditional 0.1" spaced pin headers.  So, if you put the mating gender of pin header on your homemade electrodes, they could plug right into the OpenBCI board.  Great!  Alternatively, if you use OpenEEG, you will want to terminate your electrode's wire with a 3.5 mm stereo phono plug.   That is what the OpenEEG is built around.  These pieces about $0.50 each.

So, overall, I estimate that cost of each one of these electrodes is: $0.24 for the washer, about $0.36 for a meter of stranded wire (it's more flexible than solid wire), and $0.50 for a 3.5mm connector.  That's $1.10 in parts, which is a nice reduction compared to commercially available electrodes linked at the top of this post.

But do my homemade electrodes work?

Homemade Electrodes for ECG

As discussed in my previous post, I always like to start my testing by doing ECG measurements.  Because the heart signals are so strong, it is an easy way to confirm that your EEG system (and EEG electrodes) are working to some degree.  So, I got out my tube of Ten20 conductive paste and stuck my electrode to my wrist.  I attached one electrode to my left wrist and the other electrode to my right wrist.

Attaching my homemade electrodes to my wrists to measure my ECG.
The shiny stuff on my skin is Ten20 conductive paste

 How well did they stick?  Well, not nearly as well as the self-adhesive disposable ECG electrodes.  But, the surface area on those sticky ECG electrodes is HUGE, so of course my little electrodes won't stick as well.  Given how small my electrodes were, though, I think that they adhered adequately well.  I think that the big hole in the middle of the washer is not helpful.  If it were solid, I think that these electrodes would stick better.  I'll remember that when I go to make my next set of homemade electrodes.

Once I got the electrodes attached to my wrists, I connected plugged them into my OpenBCI board and had the Arduino pipe the data to my computer, as usual.  Example ECG data from these electrodes is shown below.  I'm showing 6 heart beats.  As you can see, the sharp R-waves and the broad T-waves are both very clear.  The amplitude of the ECG is similar to what I showed in my post yesterday when I used real ECG electrodes.  So, while my signal trace does look a bit noisier than yesterday, I'd say that this is a successful test!

My ECG As Recorded through OpenBCI Using my Homemade Electrodes

Homemade Electrodes for EEG

Since I was successful with the ECG, I made the next step and used my homemade electrodes to acquire some EEG signals.  I am still pretty fixated on my Mu waves, so I decided to use my electrodes to see if I could pick up my Mu waves.

Following a simplified version of my previous procedure, I put one electrode near the top of my head near Cz and one the left side of my head near C3.  As you can see in the photo, it is very tricky to accurately place electrodes on one's own head.  In retrospect, it looks like the one on the top of my head was a bit too far forward for Cz and the one on the side of my head was a bit too far back and a bit too low for C3.  Regardless, they should be good enough to record *something*, so let's see what I got.


Placing my homemade electrodes near
Cz (top of head) and near C3 (side of head).

Using my OpenBCI electronics, I started recording data from my brain.  I spent some time with my eyes closed to generate Alpha waves (Posterior Dominant Rhythm), I spent some time with my eyes open and my right arm and hand relaxed (to hopefully generate Mu waves), and I spent some time with my eyes open and my right hand clenching and un-clenching.  The results are plotted below as a spectrogram.  Unfortunately, it is not very clear where the boundaries were between these different activities, so it is not clear what we *should* be seeing.  We do clearly see the Alpha waves caused by my eyes being closed.  In the middle of the plot, we might also see some Mu waves, but they are very weak.  I would say that these results are fine for Alpha and bad for Mu.


To try to get better results, I moved the homemade electrode that was on the side of my head.  I moved it a little higher to be closer to where C3 is supposed to be.  Then, I repeated my recordings.  This time, I pressed a button on my computer to mark the boundary between each activities to make my post-test analysis easier.  It turns out that the simple act of pressing the button caused my EEG wires to jiggle, which shows up as artifacts within the data.  It makes it clear when I shifted my activity.  See the results below.


As before, the Alpha waves are quite clear.  This time, though, I do think that I see Mu waves during those periods when my eyes were open and my hand and arm were relaxed.  Then, when I moved my hand, I think that I see that the Mu waves go away.  That's exactly what should happen!  At the end, when I relax again, I think that it is interesting that it takes a while for my Mu waves to come back.  Clearly, I am not very good at relaxing.  That's not much of a surprise to me.  I can be quite excitable...especially when I'm EEG HACKING!

Homemade Electrodes Seem to be Good!

So, with this second test, I'm quite pleased with my homemade electrodes.  The signals that I recorded were pretty good.  There was a lot of 60 Hz noise (not shown in these graphs) but that could be due to me not using the traditional 3rd electrode connection (variously named the "bias" or "driven ground" or "driven right leg") for these recordings.  I also felt that these electrodes did not stick to my head as securely as the gold electrodes that I used previously.  I think that the stickiness can be improved by using a piece of metal with more surface area...maybe a regular flat washer instead of the skinny lock washer.  Still, for about a dollar per electrode, I think that the results are pretty darned good.  I'm pleased.

How about you...have you made your own electrodes before?  How did you do it?  Did they work?


Follow-Up: More graphs and discussion of the data is in this post
Follow-Up: Want to see my data from this experiment?  Check out my github!

Monday, November 4, 2013

Collecting ECG with my EEG setup

When playing with a new EEG system (home-built or purchased), it is important to start with signals that are easy to obtain.  By starting with easy signals, you can more readily confirm that your system is working, or you an more readily trouble-shoot it until it is working.  It is for this reason that I always start my EEG hacking by measuring signals from my heart rather than from my brain.  The electrocardiogram (ECG, or EKG) is a far stronger signal with a much easier to see structure than the EEG.  Plus, to measure ECG, you do not need to put sticky, goopy electrodes in your hair.  Yay!

If you have never recorded your own ECG, here I'm going to give a photo tour of how I do it.  I happen to be using the OpenBCI system, but you can do the same thing with nearly any EEG system.  For example, when I first got my OpenEEG board from Olimex, I tested with ECG.  It worked just fine.

Using OpenBCI to Record my Heart Signals (ECG) from my Left Wrist and Right Wrist (my right wrist not shown because it is holding the camera!)

ECG Overview

EEG is the measurement of the electrical signals generated by your brain.  By contrast, ECG is the measurement of the electrical signals generated by your heart.  When the heart contracts, it generates a relatively strong electrical gradient in your body.  With electrodes on your skin, you can measure the difference in potential (ie, voltage) across your body caused by your heart.  That's what the ECG records.

ECG Can Be Measured Across Many Locations.  I'm going to use my two wrists.
Any measurement of electric voltage is a comparison of electrical potential between two different locations in space.  Therefore, to record one's ECG (or EEG), you need to attach at least two electrodes to your body.  Given that ECG signals are so strong, you have lots of choices of where to put your electrodes.  The only requirement is that your two measurement locations are on either side of the heart.  For me, my wrists are a very convenient, so that's where I'm going to attach my electrodes.

Hardware Needed

To measure one's ECG, you need electrodes to attach to your skin, you need wires to connect the electrodes to your electronics, you need some signal acquisition electronics that are appropriate for biosignals, and you need a computer and some software to record and visualize the ECG signals.  I'm going to talk about each of these elements in the sections that follow.

Electrodes:  Electrodes are simply pieces of metal that are electrically connected to your skin.  As long as you make good contact, nearly anything can be used as an electrode...they do not have to be specific to ECG.  If you don't want to get ECG electrodes, you could use EEG electrodes, you could use a piece of copper tape, or you can even use a piece of bare wire (if you can keep it attached to your skin).  But, I want to make this easy for myself, so I'm going to use cheap, disposable ECG electrodes.

I like the disposable ECG electrodes because they are self-adhesive, they come with conductive gel already attached, and they have a nice little button snap for attaching lead wires. They can be purchased from many, many places on-line.  One source is BioPac, where they are $0.38 each.  You can find them even cheaper, if you search around.


To put them on your skin, many websites talk about preparing your skin with an abrasive rub followed by alcohol.  While this is important if you want high-fidelity signals, we don't need this kind of quality.  We're just trying to see if our electronics work.  Therefore, no preparation is necessary.  Simply find a piece of skin without too much hair (for me, that's the inside of my wrists), peel off the paper backing, and stick them to your skin.  Easy!

Self-Adhesive Disposable ECG Electrodes Stuck to my Wrists.
ECG Lead Wires:  With the electrodes on the wrists, you need wires to bring the signals back to your electronics.  Again, there is no magic here.  You can use any wire.  Because I'm making life easy for myself, I bought some ECG lead wires that are made to connect to the button snaps on the ECG electrodes.  There are several different styles of these wires...some with snaps and some with clips.  I happened to get the ones with clips, but it doesn't really matter.  As when buying the electrodes, you can buy lead wires lots of different places.  I don't remember where I got mine.  Some are available from Biopac, or you can just check out Amazon.

The ECG lead wires that I use.  They have nice clips on the ends (picture on right) for attaching to ECG electrodes.  They also have the "touchproof" connectors on the other end for connecting to standard ECG electrodes.  Alternatively, you can use plain wire, if you prefer.
When selecting which lead wires to buy/make, the only trick is in the connector that attaches to the electronics.  Most ECG leads come with these nice little push-plugs that are referred to as "touchproof connectors".  They have this name because the electrical contacts are fully shrouded by plastic and can't be touched.  Note that EEG electrodes often come with the same type of connectors, too, which makes the ECG/EEG transition easy.  While you can always just cut off the connectors and use the raw wire, I like these connectors.  The challenge with the touchproof connectors is that they come in a few different diameters.  So, if you want to use the connectors, it's good to know what diameter connectors are on your wires so that you can buy the correct mating jacks.  My lead wires happened to have 1.5 mm connectors.

Since my EEG electrodes have the same 1.5 mm touchproof plugs as my ECG lead wires, it made sense to me to invest the time and money to buy the mating touchproof jacks.  I bought some 1.5 mm touchproof jacks from PlasticsOne.  I happened to buy the panel-mount version, but PCB mount would also be a good choice.  At over $3 each, these are not cheap.  They are convenient, though.  I mounted the jacks to a scrap piece of plastic and soldered on some wires to go to my electronics.  Easy.


Electronics:  The whole point of this exercise is to use my heart signals as a way of testing my EEG electronics.  So, for me, I'll be using EEG electronics (OpenBCI, OpenEEG, whatever).  But, if you were just doing ECG, ECG signals are generally stronger, which means that the electronics do not need to have such low self-noise.  As a result, ECG electronics tend to be cheaper than EEG electronics.  Regardless, I'm using EEG electronics.  In this case, I'm using OpenBCI.

For my setup, I connect one lead wire to "Input 1" (the "+" input) and one lead wire to the common reference input, "SRB" (the "-" input).  See the picture below.


Computer and Software:  Obviously, any computer will work...you just need one that will connect to your ECG/EEG electronics.  OpenBCI interfaces to the computer via an Arduino Uno.  That part is easy.  The harder part is what software to use on the PC.  You could use the custom displays that we have made for OpenBCI.  Or, following up from my last post, you could use BrainBay, which is an open source biosignal analysis program for Windows.  I recently wrote a software interface for OpenBCI to allow its data to be received and processed by BrainBay.  That's what I'm going to use here.

ECG Results

With the setup that I described above, I started BrainBay, relaxed my wrists (muscle contractions make electricity, too, which can mask the ECG signal), and watched my ECG data scroll by on the BrainBay display.  Some example data is shown below.  It should the ECG signal recorded for four heart beats.  It's always comforting to scientifically confirm that one's heart is beating.

ECG Signal Recorded using OpenBCI and Visualized using BrainBay.
I find the ECG signal itself to be fascinating.  Each component of the waveform corresponds to action in a different part of the heart.  Below, I've excerpted one heart beat from the waveform above and have shown it with annotations.  The little bump (downward in my data above) is the "P-wave", which is the atria contracting to push blood to the ventricles.  The sharp spike is the "R-wave", which is main contraction of the ventricles to push blood out to the body.  The big long bump is the "T-wave", which is the ventricles relaxing and re-polarizing to get ready for the next heart beat.  Note that usually the R-wave is much bigger and that the P- and T-waves are inverted compared to this trace, so I probably just had some wires plugged in backwards.  Still, all the components are there and they look pretty good.

Compared to the challenges in measuring EEG signals from the scalp, I find that ECG is way easier to measure reliably.  That's why I use it as my first test of an EEG system.  If I stick electrodes on my wrists  and don't see a signal like that shown above, I know that something is wrong with the electronics and not my body.  If you find yourself hacking EEG systems for fun, you might want to consider using this technique as well.  Plus, you might learn something about ECG and your heart, which is cool, too!


Follow-Up: In trying my homemade electrodes, I used ECG as my first test.
Follow-Up: I also was able to measure EOG using a similar setup.
Follow-Up: I've now tried to share the data from this post on my github.  Try it!

Saturday, November 2, 2013

BrainBay - EEG Visualization Software

When I got started with EEG, I started with the OpenEEG project and the excellent information that they have available.  That led to me buying the SMT version of the OpenEEG hardware available from Olimex.  Once I got that hardware, it led me to downloading and using BrainBay, which is an open source software for receiving, processing, and visualizing biosignals, especially EEG signals.  While the interface feels a little quirky when you first start using it, it is surprisingly flexible and powerful.  I decided that I wanted to be able to inject data from our OpenBCI EEG system into BrainBay so that I could use its processing and display tools.

Screenshot from BrainBay's Website of One Person's Processing and Visualization Configuration.  The configurations are completely user defined, which is powerful...and confusing to a new person.

>>> Getting Data into BrainBay

By default, BrainBay can be configured to receive data streamed from a few different EEG systems.  It seems that most people probably use the OpenEEG hardware (such as the Olimex unit linked earlier).  The OpenEEG hardware communicates to the PC using a binary data format.  If I want to inject OpenBCI data into BrainBay, the easiest way is to make my OpenBCI system look like an OpenEEG system.  This means that I need to alter my Arduino software (which is what my OpenBCI is connected to) to output the EEG data in the same format as used by OpenEEG.  Easy!

Um, but what is the OpenEEG data transfer format?

Well, the core of the OpenEEG hardware is an AVR processor like the Arduino, so the embedded software running on the OpenEEG hardware should be intelligible to someone with experience in Arduino.  You could download the software, read it (if you were suitably skilled) and figure out the data format.  Given the number of AVR macros employed in that code, however, figuring out what's going on can be challenging for a lot of folks (including myself).

Alternatively, if you look in BrainBay's own Developer Manual and jump to Section 6, it discusses the data format in actual words.  Very nice.  I chose to target the "P2" data format.

You may notice that this format has a couple of limitations relative to the capabilities of OpenBCI.  First, this data format only allows for 6 EEG channels, whereas OpenBCI has 8 channels.  So, we'll lose two EEG channels, which is unfortunate but not horrible.  Second, note that this format only allows for 16-bit EEG values, whereas OpenBCI generates EEG data samples at 24-bit resolution.  So, I'll have to cut 8 bits of resolution, which means that I'll lose some dynamic range.  A 16-bit value still has a lot of dynamic range, so this will probably be OK.

(Super-technical aside:   I'll need to decide whether to truncate the lowest bits (and lose resolution at the lowest signal levels) or to cut the highest bits and lose the ability to handle large DC offsets.  I think that I'll split the difference and cut some from both the high and low sides of my dynamic range.  For the moment, I do this by dividing my 24-bit sample by 32 and cast from my 32-bit data type to a 16-bit data type.  The "divide by 32" step, in effect, drops 5 bits of resolution from the low end of my dynamic range, which means that the casting drops 3 bits of headroom on the high end of my dynamic range.)

>>> Configuring BrainBay for OpenBCI

So, after writing a small extension to my existing Arduino software for translating the OpenBCI data into this new format, I can successfully get my OpenBCI data into BrainBay.  Yay!  There are, however, a couple of small changes to the settings in BrainBay to get the most out of the OpenBCI data.  Specially, in the "EEG Block" used by BrainBay to get data from the EEG hardware, you'll need to alter the "Baud Rate"," Sampling Rate", and "Resolution".  With my current settings in the Arduino software (which might change in the future), here's how I configured the EEG input block in BrainBay:

To Use OpenBCI in BrainBay, select "Modular EEG P2" and then change the Baud Rate to 115200, change the Resolution to 1432 and (not shown) change the Sampling Rate to 250 Hz.
Baud Rate:  OpenEEG defaults to 56000 bps whereas I configured my OpenBCI Arduino software to run at 115200 bps.  If you don't change this value, BrainBay probably will not be able to receive the data from OpenBCI.

Sampling Rate:  OpenEEG runs at 256 Hz.  The sampling rate for OpenBCI has several different settings, but my Arduino software has it running at 250 Hz.  In BrainBay, you should change the value to 250 Hz so that BrainBay shows the graphs with the correct time and frequency scales.

Resolution:  OpenEEG samples have a resolution of 10-bits (ie 1024 counts).  Full-scale is 512 uV (ie, +/- 256 uV).  BrainBay always assumes that full scale is 512 uV and, in this window, it is asking how many counts correspond to 512 uV.  For OpenEEG, you enter 1024 because it spans 512 uV with its 10-bit (ie 1024 count) digitizer.  For OpenBCI, it's a little more complicated.  The correct value (for now) is to enter 1432.

(Second super-technical aside:  I get this value by finding OpenBCI's internal scale factor, which is (2^24) / (4.5 V / 24x Gain) = 89.5 counts / microVolt.  I then cut this down by by 32x bit-reduction divisor discussed earlier, which yields 2.796 counts / microVolt.  Finally, BrainBay expects "full scale" to be 512 uV, so to find out the number of "counts" it takes to represent this value, you take 512 uV * 2.796 counts / microVolt and get 1432 counts.  Viola!)

>>> Example: OpenBCI Data in BrainBay

Once you get all of those settings correct, you can setup a simple data flow in BrainBay and start watching your OpenBCI data flow smoothly and beautifully.  Below is an example of using OpenBCI for ECG (see here for the setup).  You can see the four blocks: (1) the EEG block to receive the data from OpenBCI via serial link, (2) a sharp 60 Hz notch filter to eliminate line noise, (3) a gentle bandpass filter to remove low frequency drift, and (4) an oscilloscope block to graph the data.  Look at how nice and clear my ECG is!

Using BrainBay to Receive Data from OpenBCI and Plot the Results in Real Time.  Awesome!
My favorite part of getting my data into BrainBay is that the filtering and graphs all run in real-time.  There are signal detection blocks that you can insert which can then be connected blocks that play sounds for feedback (or launch video or animation).  It's quite powerful.  Sure, I could write all of this in Matlab (which I did for Maker Faire NYC) or in Processing (which I just completed) or in Python (which we're still working on), but those programs are not as easy to reconfigure quickly as BrainBay.  BrainBay is very nice for that.

>>> Next Steps

The major downside of BrainBay is that it is only on Windows.  In the future, I'm going to look into interfacing OpenBCI with OpenViBE, which is another powerful open source software platform for receiving, processing, and visualizing EEG data.  It looks like it is also primarily aimed at Windows, but it is nice to have another choice in addition BrainBay and in addition to my own Matlab and Processing and Python interfaces.


Follow-Up: Here's a post where I describe how to make ECG measurements.
Follow-Up: Chris (the developer of BrainBay) wrote a BrainBay driver for OpenBCI.  Check it out!