The personal website of Scott W Harden

Homemade ECG Machine: Improving Daily

⚠️ Check out my newer ECG designs:

I've been working on a homemade ECG machine over the last month. This is the most basic circuit I'm currently using, designed using two quad op-amps. I've produced some surprisingly good ECG traces and even identified an arrhythmic heartbeat. Currently the device is limited because you have to be attached to your computer, I'm working toward making it a mobile device (powered by a 9V battery) which records voltage data to a minidisc recorder . There's one problem - I need to optimally adjust the gain, but how if I cannot see the trace of the wave on a monitor? I could a VU meter to monitor the output... My minidisc recorder can take mic-in and echo it the line-out at the same time, so I'll just put the VU meter on the line-out and it shouldn't affect my trace. The result is that I can walk around for 24 hours, recording my ECG, with a device I hope to get down to the size of a cell phone. (Maybe a 1990s cell phone?)

Here's a simple LED-based digital VU meter circuit I found, along with some sample images of its (bread-boarded) construction. I have all the parts at home I think, so it should be straightforward to make. The pain now is the electrodes (which are still the junky ones made from scissor-cut aluminum cans), and I think I might splurge and buy some actual disposable ECG electrodes. I think the total cost of my device as it stands is about $4, so I don't want to spend more than I have to on electrodes.

In other news it appears I've been accepted into dental school. I got a voicemail this morning at 8am, another one at 12:30pm, and apparently one on my parents' answering machine (I listed them as an alternate number), then they sent me an email! Naturally it was the email I noticed first. Here's a snapshot from my inbox, phone call 1 and phone call 2.

The Internet was Moved?

I'm working late in lab (as usual) and I went to open Firefox (my default web browser), so I clicked Start and selected "Mozilla Firefox" at the top (where your default browser usually goes in XP). Nothing happened... then this message popped up! I had to take a screen shot because it's so bizarre.

I swear this is straight from my screen (PrntScrn -> mspaint (pasted) -> PNG) with no modifications. I especially love how the computer is trying to tell me what could have gone wrong; the internet might have been moved, renamed, or removed. Slick.

⚠️ Warning: This article is obsolete.
Articles typically receive this designation when the technology they describe is no longer relevant, code provided is later deemed to be of poor quality, or the topics discussed are better presented in future articles. Articles like this are retained for the sake of preservation, but their content should be critically assessed.

Analyzing my Writings with Python

I had some free time in lab today (between steps while of an immunohistochemistry experiment) so I decided to further investigate the field of bioinformatics. I was curious if it may be worth seeking a PhD in bioinformatics if I don't get into dental school. UCF offers a PhD in bioinformatics but it's a new and small department (I think there are only 4 faculty). A degree in bioinformatics combines molecular biology (DNA, proteins, etc), computer science (programming), and statistics.

I came across a paper today: Structural Alignment of Pseudoknotted RNA which is a good example of the practice of bioinformatics. Think about what goes on in a cell... the sequence of a gene (a short region of DNA) is copied (letter-by-letter) onto an RNA molecule. The RNA molecule is later read by an enzyme (called a ribosome) and converted into a protein based on its sequence. (This process is the central dogma of molecular biology) Traditionally, it was believed that RNA molecules' only function was to copy gene sequences from DNA to ribosomes, but recently (the last several years) it was discovered that some small RNA molecules are never read and turned into proteins, but rather serve their own unique functions! For example, some RNA molecules (siRNAs) can actually turn genes on and off, and have been associated with cancer development and other immune diseases. Given the human genome (the ~3 billion letter long sequence all of our DNA), how can we determine what regions form these functional RNA molecules which don't get converted into proteins? The paper I mentioned earlier addresses this. An algorithm was developed and used to test regions of DNA and predict its probability of forming small RNA molecules. Spikes in this trace (figure 7 of the paper) represent areas of the DNA which are likely to form these RNA molecules. (Is this useful? What if you were to compare these results between normal person and someone with cancer?)

After reading the article I considered how similar my current programming projects are with this one (e.g., my recent DIY ECG projects). The paper shows a trace of score (likelihood that a region of DNA forms an RNA molecule) where peaks represent likely locations of RNA formation. Just generate the trace, determine the positions of the peaks, and you're golden. How similar is this to the work I've been doing with my homemade ECG machine, where I perform signal analysis to eliminate electrical noise and then analyze the resulting trace to isolate and identify peaks corresponding to heartbeats?

I got the itch to write my own string-analysis program. It reads the content of my website (exported from a SQL query), splits it up by date, and analyzes it. Ultimately I want to track the usage of certain words, but for now I wrote a script which plots the number of words I wrote.

Pretty cool huh? Check out all those spikes between 2004 and 2005! Not only are they numerous (meaning many posts), but they're also high (meaning many words per post). As you can see by the top trace, the most significant contribution to my site occurred during this time. So, let's zoom in on it.

Here is the code I used to produce this image.

"""Convert SQL backups of my WordPress blog into charts"""

import datetime, pylab, numpy

class blogChrono():
    def __init__(self,fname):
    def load(self):
        print "loading [%s]..."%self.fname,
        for line in raw:
            if "INSERT INTO" in line
            and';' in line[-2:-1]
            and " 'post'," in line[-20:-1]:
                line=line.replace(', NULL',', None')
                line=line.replace(", '',",", None,")
                c= line.split(',',4)[4][::-1]
                c= c.split(" ,",21)
                line=line.replace(', ,',', None,')
                if len(line[4])>len('blogtext'):
                    x=str(line[4].split(', '))[2:-2]
                                                        "%Y-%m-%d %H:%M:%S")
                post["text"]=eval('"""'+text+' """')
                post["words"]=post["text"].count(" ")
        while len(self.posts)>0:
            for post in self.posts:
                if post["date"]==die:
        print "read %d posts!n"%len(self.posts)


for post in d.posts:

pylab.title("Total Blogged Words")
pylab.title("Words Per Entry")

print "DONE"

I wrote a Python script to analyze the word frequency of the blogs in my website (extracted from an SQL query WordPress backup file) for frequency, then I took the list to Wordie and created a word jumble. Neat, huh?

import datetime, pylab, numpy
body=body.split(" ")
for word in body:
    for i in word:
        if 65< =ord(i)<=90 or 97<=ord(i)<=122: pass
        else: word=None
    if word:
        if not word in words:words[word]=0
for word in words: data.append([words[word],word])
out= "<b>Out of %d words...n"%tot
for i in range(1000):
    out += '<b>"%s"</b> ranks #%d used <b>%d</b> times (%.05f%%)
print "DONE"</b>

⚠️ Warning: This article is obsolete.
Articles typically receive this designation when the technology they describe is no longer relevant, code provided is later deemed to be of poor quality, or the topics discussed are better presented in future articles. Articles like this are retained for the sake of preservation, but their content should be critically assessed.

Signal Filtering with Python

⚠️ SEE UPDATED POST: Signal Filtering in Python

I've been spending a lot of time creating a DIY ECGs which produce fairly noisy signals. I have researched the ways to clean-up these signals, and the results are very useful! I document some of these findings here.

This example shows how I take a noisy recording and turn it into a smooth trace. This is achieved by eliminating excess high-frequency components which are in the original recording due to electromagnetic noise. A major source of noise can be from the AC passing through wires traveling through the walls of my apartment. My original ECG circuit was highly susceptible to this kind of interference, but my improved ECG circuit eliminates much of this noise. However, noise is still in the trace and it needs to be removed.

One method of reducing noise uses the FFT (Fast Fourier Transformation) and its inverse (iFFT) algorithm. Let's say you have a trace with repeating sine-wave noise. The output of the FFT is the breakdown of the signal by frequency. Check out this FFT trace of a noisy signal from a few posts ago. High peaks represent frequencies which are common. See the enormous peak around 60 Hz? That's noise from AC power lines. Other peaks (shown in colored bands) are other electromagnetic noise sources, such as wireless networks, TVs, telephones, and maybe my computer. The heart produces changes in electricity that are very slow (a heartbeat is about 1 Hz), so if we can eliminate higher-frequency sine waves we can get a pretty clear trace. This is called a band-stop filter (we block-out certain bands of frequencies). A band-pass filter is the opposite, where we only allow frequencies which are below (low-pass) or above (high-pass) a given frequency. By eliminating each of the peaks in the colored regions (setting each value to 0), then performing an inverse fast Fourier transformation (going backwards from frequency back to time), the result is the signal trace (seen as light gray on the bottom graph) with those high-frequency sine waves removed! (the gray trace on the bottom graph). A little touch-up smoothing makes a great trace (black trace on the bottom graph).

Here's some Python code you may find useful. The image below is the output of the Python code at the bottom of this entry. This python file requires that test.wav (an actual ECG recording of my heartbeat) exist in the same folder.

  • (A) The original signal we want to isolate. (IE: our actual heart signal)

  • (B) Some electrical noise. (3 sine waves of different amplitudes and periods)

  • (C) Electrical noise (what happens when you add those 3 sine waves together)

  • (D) Static (random noise generated by a random number generator)

  • (E) Signal (A) plus static (D)

  • (F) Signal (A) plus static (D) plus electrical noise (C)

  • (G) Total FFT trace of (F). Note the low frequency peak due to the signal and electrical noise (near 0) and the high frequency peak due to static (near 10,000)

  • (H) This is a zoomed-in region of (F) showing 4 peaks (one for the original signal and 3 for high frequency noise). By blocking-out (set it to 0) everything above 10Hz (red), we isolate the peak we want (signal). This is a low-pass filter.

  • (I) Performing an inverse FFT (iFFT) on the low-pass iFFT, we get a nice trace which is our original signal!

  • (J) Comparison of our iFFT with our original signal shows that the amplitude is kinda messed up. If we normalize each of these (set minimum to 0, maximum to 1) they line up. Awesome!

  • (K) How close were we? Graphing the difference of iFFT and the original signal shows that usually we're not far off. The ends are a problem though, but if our data analysis trims off these ends then our center looks great.

  • Note: these ends can be fixed by applying a windowing function to the original data. The FFT works best if the input data starts and ends at zero.

import numpy, scipy, pylab, random

# This script demonstrates how to use band-pass (low-pass)
# filtering to eliminate electrical noise and static
# from signal data!


xs=numpy.arange(1,100,.01) #generate Xs (0.00,0.01,0.02,0.03,...,100.0)
signal = sin1=numpy.sin(xs*.3) #(A)
sin1=numpy.sin(xs) # (B) sin1
sin2=numpy.sin(xs*2.33)*.333 # (B) sin2
sin3=numpy.sin(xs*2.77)*.777 # (B) sin3
noise=sin1+sin2+sin3 # (C)
static = (numpy.random.random_sample((len(xs)))-.5)*.2 # (D)
sigstat=static+signal # (E)
rawsignal=sigstat+noise # (F)
fft=scipy.fft(rawsignal) # (G) and (H)
for i in range(len(bp)): # (H-red)
    if i>=10:bp[i]=0
ibp=scipy.ifft(bp) # (I), (J), (K) and (L)

### GRAPHING ###


pylab.subplot(h,w,1);pylab.title("(A) Original Signal")

pylab.subplot(h,w,3);pylab.title("(B) Electrical Noise Sources (3 Sine Waves)")

pylab.subplot(h,w,5);pylab.title("(C) Electrical Noise (3 sine waves added together)")

pylab.subplot(h,w,7);pylab.title("(D) Static (random noise)")

pylab.subplot(h,w,9);pylab.title("(E) Signal + Static")

pylab.subplot(h,w,11);pylab.title("(F) Recording (Signal + Static + Electrical Noise)")

pylab.subplot(h,w,2);pylab.title("(G) FFT of Recording")

pylab.subplot(h,w,4);pylab.title("(H) Low-Pass FFT")

pylab.subplot(h,w,6);pylab.title("(I) Inverse FFT")

pylab.subplot(h,w,8);pylab.title("(J) Signal vs. iFFT")

pylab.subplot(h,w,10);pylab.title("(K) Normalized Signal vs. iFFT")

pylab.subplot(h,w,12);pylab.title("(L) Difference / Error")


DIY ECG Improvements

⚠️ Check out my newer ECG designs:

Instead of using a single op-amp circuit like the previous entries which gave me decent but staticky traces, I decided to build a more advanced ECG circuit documented by Jason Nguyen which used 6 op amps! (I'd only been using one). Luckily I got a few couple LM324 quad op-amps from radioshack ($1.40 each), so I had everything I needed.

The results look great! Noise is almost zero, so true details of the trace are visible. I can now clearly see the PQRST features in the wave. I'll detail how I did this in a later entry. For now, here are some photos of the little device.

UPDATE: After analyzing ~20 minutes of heartbeat data I found a peculiarity. Technically this could be some kind of noise (a 'pop' in the microphone signal), but because this peculiarity happened only once in 20 minutes I'm not ruling out the possibility that this is the first irregular heartbeat I captured with my DIY ECG. Note that single-beat irregularities are common in healthy people, and that this does not alarm me so much as fascinate me.

page 1, page 2, page 3, page 4, page 5, page 6, page 7, page 8, page 9, page 10, page 11, page 12, page 13, page 14, page 15, page 16, page 17, page 18, page 19, page 20, page 21, page 22, page 23, page 24, page 25, page 26, page 27, page 28, page 29, page 30, page 31, page 32, page 33, page 34, page 35, page 36, page 37, page 38, page 39, page 40, page 41, page 42, page 43, page 44, page 45, page 46, page 47, page 48, page 49
All Blog Posts