This page describes a simple circuit which produces ECG-like waveform. The waveform is not very detailed, but it contains a sharp depolarizing (rising) component, a slower hyperpolarizing (falling) component, and a repetition rate of approximately one beat per second making it potentially useful for testing heartbeat detection circuitry.
In 2019 I released a YouTube video and blog post showing how to build an ECG machine using an AD8232 interfaced to a computer's sound card. At the end of the video I discussed how to use a 555 timer to create a waveform roughly like an ECG signal, but I didn't post the circuit at the end of that video. I get questions about it from time to time, so I'll share my best guess at what that circuit was here using LTSpice to simulate it.
The 555 timer generates pulses about once per second.
The diode (D1) causes the 555 to produce very short pulses. The duty of the pulses is controlled by the resistance in series with the diode (R3), with higher resistances resulting in larger duty.
The main purpose of the first op-amp is to invert polarity of the signal emitted by the 555. The signal is a square wave at about 1Hz, but it is mostly high with brief low pulses.
The second op-amp serves as a voltage buffer to stabilize the output, and the final series capacitor shifts the voltage so it's centered around zero.
Unity gain op-amps should have some feedback resistance to improve small-signal stability in production applications, but for messing around here I felt fine omitting them.
Markdown source code last modified on January 18th, 2021
---
title: ECG Simulator Circuit
date: 2020-09-27 17:11:00
tags: circuit, diyECG
---
# ECG Simulator Circuit
**This page describes a simple circuit which produces ECG-like waveform.** The waveform is not very detailed, but it contains a sharp depolarizing (rising) component, a slower hyperpolarizing (falling) component, and a repetition rate of approximately one beat per second making it potentially useful for testing heartbeat detection circuitry.
**In 2019 I released a [YouTube video](https://www.youtube.com/watch?v=sP_-f5nsOEo) and [blog post](https://swharden.com/blog/2019-03-15-sound-card-ecg-with-ad8232/) showing how to build an ECG machine** using an AD8232 interfaced to a computer's sound card. At the end of the video I discussed how to use a 555 timer to create a waveform roughly like an ECG signal, but I didn't post the circuit at the end of that video. I get questions about it from time to time, so I'll share my best guess at what that circuit was here using LTSpice to simulate it.
<div class="text-center img-border">

</div>
## Design Notes
* The 555 timer generates pulses about once per second.
* The diode (D1) causes the 555 to produce very short pulses. The duty of the pulses is controlled by the resistance in series with the diode (R3), with higher resistances resulting in larger duty.
* The main purpose of the first op-amp is to invert polarity of the signal emitted by the 555. The signal is a square wave at about 1Hz, but it is mostly high with brief low pulses.
* The second op-amp serves as a voltage buffer to stabilize the output, and the final series capacitor shifts the voltage so it's centered around zero.
* Unity gain op-amps should have some feedback resistance to improve small-signal stability in production applications, but for messing around here I felt fine omitting them.
## Resources
* LTSpice file for this project: [ecg.asc](ecg.asc)
* You will need the LM741 model found on the [Using MOD Files in LTSpice](https://swharden.com/blog/2020-09-26-ltspice-mod-files/) page
* My [Action Potential Generator Circuit](https://swharden.com/blog/2017-08-12-analog-action-potential-generator-circuit/) and [Microcontroller Action Potential Generator](https://swharden.com/blog/2017-08-20-microcontroller-action-potential-generator/) articles describe method to produce a similar waveform (designed to look more like what firing neurons produce) using transistors to charge/discharge a capacitor rather than op-amps.
Every few years I revisit the idea of building an ECG machine. This time I was very impressed with how easy it is to achieve using the AD8232, a single-lead ECG front-end on a chip. The AD8232 is small (LFCSP package) but breakout boards are easy to obtain online. Many vendors on eBay sell kits that come with electrode cables and pads for under $20. Sparkfun sells a breakout board but you have to buy the cable and electrodes separately. I highly recommend buying bags of electrodes inexpensively on eBay because having plenty will make life much easier as you experiment with this circuit. The signal that comes out of this ECG device (unlike other ECG machines I've built) is remarkably clean! It doesn't require any special spectral filtering (all that is accomplished on the chip), and it can be hooked right up to an oscilloscope or sampled with analog-to-digital converter.
The breakout board is easy to use: Just supply 3.3V, hook-up the chest leads, and a great looking ECG signal appears on the output pin. I prefer using a LD33V to drop arbitrary DC voltages to 3.3V. While using a 9V battery isn't the most power efficient option, it's certainly an easy one. Since the AD8232 claims to only draw 170 µA, inefficient use of a linear voltage regulator probably isn't too much of a concern for desktop experimenters. The low power consumption of this chip raises some interesting possibilities for wireless ECG analysis!
I like inspecting the output of this circuit using my computer sound card. Probing the output pin on an oscilloscope reveals a beautiful ECG signal, but not everybody has an oscilloscope. I've seen some project webpages out there which encourage people to use the ADC of a microcontroller (usually an Arduino) to perform continuous measurements of voltage and transmit them over the USART pins, which then get transferred to a PC via a USB-to-serial USART adapter (often built around a FTDI FT-232 breakout board or similar), only to get graphed using Java software. That sequence certainly works, and if you already have an Arduino, know its sketch language, and are happy writing software in Processing, that's a great solution for you! However I found the sound card option convenient because everyone has one, and with a click-to-run computer program you can visualize your ECG right away. Note that I added a potentiometer to drop the voltage of the ECG output to make it more suitable for my microphone jack. Ideally you'll find a resistance that uses a lot of your sound card's dynamic range without clipping.
The SoundCardECG project on GitHub is a click-to-run Windows program I wrote to display and analyze ECG signals coming into the computer sound card. The screenshot above shows my heart rate as I watched a promotional video for a documentary about free-climbing. You can see where my heart-rate elevated for a couple minutes in the middle as I watched a guy free-climb a cliff a thousand feet in the air without safety gear. This software is written in C# and fully open source. It certainly works, but has many avenues for improvement (such as enhanced QRS detection). Interactive graphing is provided by the ScottPlot library.
Most of the project details are in the video, so I won't type them all out here. However, this is an excellent first step for a variety of projects that could emerge from having an easy way to measure an ECG signal. Immediate ideas are (1) heart rate detection in circuitry (not using a PC), (2) data-logging ECG signals, and (3) adding wireless functionality. I may come back and revisit one or more of these ideas in the future, but if you're interested and inspired to make something yourself I'd love to see what you come up with! Send me an email with a link to your project page and I can share it here.
I built this AD8232 breakout board into a nice enclosure to make it easier to experiment with it in the future. The circuity isn't anything special: a linear voltage regulator with capacitive decoupling on the input and output, and an op-amp serving as a unity gain amplifier to buffer the output accessible through a SMA connector, and a current-limited output attached to a female 1/8" audio for easy connection to my computer sound card.
Personal update: My website posts (and YouTube videos) have slowed dramatically as I've been dealing with some complicated medical issues. I don't intend on posting medical updates on this web page, but anyone interested in following my medical treatments can do so at http://swharden.com/med/
Markdown source code last modified on January 18th, 2021
---
title: Sound Card ECG with AD8232
date: 2019-03-15 23:50:34
tags: diyECG, csharp
---
# Sound Card ECG with AD8232
**Every few years I revisit the idea of building an ECG machine.** This time I was very impressed with how easy it is to achieve using the [AD8232](https://www.analog.com/media/en/technical-documentation/data-sheets/ad8232.pdf), a single-lead ECG front-end on a chip. The AD8232 is small (LFCSP package) but breakout boards are easy to obtain online. Many [vendors on eBay](https://www.ebay.com/sch/ad8232+module) sell kits that come with electrode cables and pads for under $20. Sparkfun [sells a breakout board](https://www.sparkfun.com/products/12650) but you have to buy the [cable](https://www.sparkfun.com/products/12970) and [electrodes](https://www.sparkfun.com/products/12969) separately. I highly recommend buying bags of electrodes inexpensively on eBay because having plenty will make life much easier as you experiment with this circuit. The signal that comes out of this ECG device (unlike [other ECG machines I've built](https://www.swharden.com/wp/2016-08-08-diy-ecg-with-1-op-amp/)) is remarkably clean! It doesn't require any special spectral filtering (all that is accomplished on the chip), and it can be hooked right up to an oscilloscope or sampled with analog-to-digital converter.

**The breakout board is easy to use:** Just supply 3.3V, hook-up the chest leads, and a great looking ECG signal appears on the output pin. I prefer using a [LD33V](https://www.sparkfun.com/datasheets/Components/LD1117V33.pdf) to drop arbitrary DC voltages to 3.3V. While using a 9V battery isn't the most power efficient option, it's certainly an easy one. Since the AD8232 claims to only draw 170 µA, inefficient use of a linear voltage regulator probably isn't too much of a concern for desktop experimenters. The low power consumption of this chip raises some interesting possibilities for wireless ECG analysis!
<div class="text-center img-medium">
[](CIRCUIT.png)
</div>
**I like inspecting the output of this circuit using my computer sound card.** Probing the output pin on an oscilloscope reveals a beautiful ECG signal, but not everybody has an oscilloscope. I've seen some project webpages out there which encourage people to use the ADC of a microcontroller (usually an Arduino) to perform continuous measurements of voltage and transmit them over the USART pins, which then get transferred to a PC via a USB-to-serial USART adapter (often built around a FTDI FT-232 breakout board or similar), only to get graphed using Java software. That sequence certainly works, and if you already have an Arduino, know its sketch language, and are happy writing software in Processing, that's a great solution for you! However I found the sound card option convenient because everyone has one, and with a click-to-run computer program you can visualize your ECG right away. Note that I added a potentiometer to drop the voltage of the ECG output to make it more suitable for my microphone jack. Ideally you'll find a resistance that uses a lot of your sound card's dynamic range without clipping.
<div class="text-center img-border img-medium">
[](screenshot.png)
</div>
**The[ SoundCardECG project](https://github.com/swharden/SoundCardECG) on GitHub** is a click-to-run Windows program I wrote to display and analyze ECG signals coming into the computer sound card. The screenshot above shows my heart rate as I watched a promotional video for a documentary about free-climbing. You can see where my heart-rate elevated for a couple minutes in the middle as I watched a guy free-climb a cliff a thousand feet in the air without safety gear. This software is written in C# and fully open source. It certainly works, but has many avenues for improvement (such as enhanced QRS detection). Interactive graphing is provided by the [ScottPlot](https://github.com/swharden/ScottPlot) library.
**Most of the project details** are in the video, so I won't type them all out here. However, this is an excellent first step for a variety of projects that could emerge from having an easy way to measure an ECG signal. Immediate ideas are (1) heart rate detection in circuitry (not using a PC), (2) data-logging ECG signals, and (3) adding wireless functionality. I may come back and revisit one or more of these ideas in the future, but if you're interested and inspired to make something yourself I'd love to see what you come up with! Send me an email with a link to your project page and I can share it here.
<div class="text-center img-border">
[](DSC_0015_lzn-1.jpg)
</div>
**I built this AD8232 breakout board into a nice enclosure** to make it easier to experiment with it in the future. The circuity isn't anything special: a linear voltage regulator with capacitive decoupling on the input and output, and an op-amp serving as a unity gain amplifier to buffer the output accessible through a SMA connector, and a current-limited output attached to a female 1/8" audio for easy connection to my computer sound card.
<div class="text-center img-border">

</div>
**Personal update:** My website posts (and YouTube videos) have slowed dramatically as I've been dealing with some complicated medical issues. I don't intend on posting medical updates on this web page, but anyone interested in following my medical treatments can do so at http://swharden.com/med/
I made surprisingly good ECG from a single op-amp and 5 resistors! An ECG (electrocardiograph, sometimes called EKG) is a graph of the electrical potential your heart produces as it beats. Seven years ago I posted DIY ECG Machine on the Cheap which showed a discernible ECG I obtained using an op-amp, two resistors, and a capacitor outputting to a PC sound card's microphone input. It didn't work well, but the fact that it worked at all was impressive! It has been one of the most popular posts of my website ever since, and I get 1-2 emails a month from people trying to recreate these results (some of them are during the last week of a college design course and sound pretty desperate). Sometimes people get good results with that old circuit, but more often than not the output isn't what people expected. I decided to revisit this project (with more patience and experience under my belt) and see if I could improve it. My goal was not to create the highest quality ECG machine I could, but rather to create the simplest one I could with emphasis on predictable and reproducible results. The finished project is a blend of improved hardware and custom cross-platform open-source software (which runs on Windows, Linux, and MacOS), and an impressively good ECG considering the circuit is so simple and runs on a breadboard! Furthermore, the schematics and custom software are all open-sourced on my github!
Here's a video demonstrating how the output is shown in real time with custom Python software. The video is quite long, but you can see the device in action immediately, so even if you only watch the first few seconds you will see this circuit in action with the custom software. In short, the amplifier circuit (described in detail below) outputs to the computer's microphone and a Python script I wrote analyzes the audio data, performs low-pass filtering, and graphs the output in real time. The result is a live electrocardiograph!
The circuit is simple, but a lot of time and thought and experimentation went into it. I settled on this design because it produced the best and most reliable results, and it has a few nuances which might not be obvious at first. Although I discuss it in detail in the video, here are the highlights:
The output goes to the microphone jack of your computer.
There's nothing special about the op-amp I used (LM741). A single unit of an LM324 (or any general purpose op-amp) should work just as well.
Resistor values were chosen because I had them on hand. You can probably change them a lot as long as they're in the same ballpark of the values shown here. Just make sure R1 and R2 are matched, and R3 should be at least 10MOhm.
Do not use a bench power supply! "BAT+" and "BAT-" are the leads of a single 9V battery.
Note that the leg electrode is ground (same ground as the computer's microphone ground)
R5 and R4 form a traditional voltage divider like you'd expect for an op-amp with a gain of about 50.
You'd expect R4 to connect to ground, but since your body is grounded, chest 2 is essentially the same
R3 must be extremely high value, but it pulls your body potential near the optimal input voltage for amplification by the op-amp.
R1 and R2 split the 9V battery's voltage in half and center it at ground, creating -4.5V and +4.5V.
altogether, your body stays grounded, and the op-amp becomes powered by -4.5V and +4.5V, and your body is conveniently near the middle and ready to have small signals from CHEST1 amplified. Amplification is with respect to CHEST2 (roughly ground), rather than actual ground, so that a lot of noise (with respect to ground) is eliminated.
For those of you who would rather see a picture than a schematic, here's a diagram of how to assemble it graphically. This should be very easy to reproduce. Although breadboards are typically not recommended for small signal amplification projects, there is so much noise already in these signals that it doesn't really matter much either way. Check out how good the signals look in my video, and consider that I use a breadboard the entire time.
The most comfortable electrodes I used were made for muscle simulators. A friend of mine showed me some muscle stimulator pads he got for a back pain relief device he uses. As soon as I saw those pads, I immediately thought they would be perfect for building an ECG! They're a little bit expensive, but very comfortable, reusable, last a long time, and produce brilliant results. They also have 3.5 mm (headphone jack) connectors which is perfect for DIY projects. On Amazon.com you can get 16 pads for $11 with free shipping. I decided not to include links, because sometimes the pads and cords are sold separately, and sometimes they have barrel connectors and sometimes they have snap connectors. Just get any adhesive reusable electrodes intended for transcutaneous electrical nerve stimulation (TENS) that you can find! They should all work fine.
You can make your own electrodes for $0.03! Okay that's a terrible joke, but it's true. I made not-awful electrodes by soldering wires to copper pennies, adding strength by super-gluing the wire to the penny, and using electrical tape to attach them to my chest. Unless you want a tattoo of an old guy's face on your torso, wait until they cool sufficiently after soldering before proceeding to the adhesion step. I suspect that super gluing the penny to your chest would also work, but please do not do this. Ironically, because the adhesive pads of the TENS electrodes wear away over time, the penny solution is probably "more reusable" than the commercial electrode option.
This ECG was recorded using pennies as electrodes:
It would have required extra components, which goes against the theme of this project
It would require specific value components, which is also undesirable for a junkbox project
I'm partial to the Chebyshev filter, but getting an extremely sharp roll-off a few Hz shy of 50Hz would take multiple poles (of closely matched passive components) and not be as trivial as it sounds.
Notes on software: This a really cool use of Python! I lean on some of my favorite packages numpy, scipy, matplotlib, pyqrgraph, and PyQt4. I've recently made posts describing how to perform real-time data graphing in Python using these libraries, so I won't go into that here. If you're interested, check out my real-time audio monitor, notes on using PlotWidget, and notes on using MatPlotLib widget. I tried using PyInstaller to package this project into a single .EXE for all my windows readers who might want to recreate this project, but the resulting EXE was over 160MB! That's crazy! It makes sense considering packagers like PyInstaller and Py2EXE work by building your entire python interpreter and all imported libraries. With all those fun libraries I listed above, it's no wonder it came out so huge. It may be convenient for local quick-fixes, but not a good way to distribute code over the internet. To use this software, just run it in Python. It was tested to work with out-of-the-box WinPython-64bit-3.5.2.1 (not the Qt5 version), so if you want to run it yourself start there.
Notes on safety. How safe is this project? I'm conflicted on this subject. I want to be as conservative as I can (leaning on the side of caution), but I also want to be as realistic as possible. I'm going to play it safe and say "this may not be safe, so don't build or use it". As an exercise, let's consider the pros and cons:
PROS:
It's powered from a 9V battery which is safer than a bench power supply (but see the matching con).
The only connections to your body are:
leg - ground. you ground yourself all the time. using a wrist grounding strap is the same thing.
chest 1 - extremely high impedance. You're attaching your chest to the high impedance input of an op-amp (which I feel fine with), and also to a floating battery through a 10MOhm resistor (which also I feel fine with)
chest 2 - raises an eyebrow. In addition to a high impedance input, you're connected to an op-amp through a 100k resistor. Even if the op-amp were putting out a full 4.5V, that's 0.045mA (which doesn't concern me a whole lot).
I don't know where to stick this, but I wonder what type of voltages / currents TENS actually provide.
CONS / WARNINGS:
It's powered from a 9V battery. So are many stun guns.
If the op-amp oscillates, oscillations may enter your body. Personally I feel this may be the most concerning issue.
Small currents can kill. I found a curiously colored website that describes this. It seems like the most dangerous potential effect is induction of cardiac fibrillation, which can occur around 100mA.
Improving safety through optical isolation: The safety of this device may be improved (albeit with increased complexity) through the implementation of opto-isolators. I may consider a follow-up post demonstrating how I do this. Unlike digital signals which I've optically isolated before, I've never personally isolated analog signals. Although I'm sure there are fully analog means to do this, I suspect I'd accomplish it by turning it into a digital signal (with a voltage-to-frequency converter), pulsing the output across the optoisolator, and turning it back into voltage with a frequency-to-voltage converter or perhaps even a passive low-pass filter. Analog Devices has a good write-up about optical isolation techniques.
Do you have comments regarding the safety of this device? Write your thoughts concisely and send them to me in an email! I'd be happy to share your knowledge with everyone by posting it here.
Did you build this or a device similar to it? Send me some pictures! I'll post them here.
LEGAL: This website is for educational purposes only. Do not build or use any electrical devices shown. Attaching non-compliant electronic devices to your body may be dangerous. Consult a physician regarding proper usage of medical equipment.
Markdown source code last modified on January 18th, 2021
---
title: DIY ECG with 1 op-amp
date: 2016-08-08 01:49:24
tags: diyECG, python, circuit
---
# DIY ECG with 1 op-amp
> **⚠️ Check out my newer ECG design:**
* [**Sound Card ECG with AD8232**](https://swharden.com/blog/2019-03-15-sound-card-ecg-with-ad8232/)
__I made surprisingly good ECG from a single op-amp and 5 resistors! __An ECG (electrocardiograph, sometimes called EKG) is a graph of the electrical potential your heart produces as it beats. Seven years ago I posted _[DIY ECG Machine on the Cheap](https://www.swharden.com/wp/2009-08-14-diy-ecg-machine-on-the-cheap/)_ which showed a discernible ECG I obtained using an op-amp, two resistors, and a capacitor outputting to a PC sound card's microphone input. It didn't work well, but the fact that it worked at all was impressive! It has been one of the most popular posts of my website ever since, and I get 1-2 emails a month from people trying to recreate these results (some of them are during the last week of a college design course and sound pretty desperate). Sometimes people get good results with that old circuit, but more often than not the output isn't what people expected. I decided to revisit this project (with more patience and experience under my belt) and see if I could improve it. My goal was not to create the highest quality ECG machine I could, but rather to create the _simplest_ one I could with emphasis on predictable and reproducible results. The finished project is a blend of improved hardware and custom cross-platform open-source software (which runs on Windows, Linux, and MacOS), and an impressively good ECG considering the circuit is so simple and runs on a breadboard! Furthermore, the schematics and custom software are all [open-sourced on my github](https://github.com/swharden/diyECG-1opAmp/)!

__Here's a video demonstrating how the output is shown in real time with custom Python software.__ The video is quite long, but you can see the device in action immediately, so even if you only watch the first few seconds you will see this circuit in action with the custom software. In short, the amplifier circuit (described in detail below) outputs to the computer's microphone and a Python script I wrote analyzes the audio data, performs low-pass filtering, and graphs the output in real time. The result is a live electrocardiograph!
<div class="text-center">
[](ECG_1470609065.png)
</div>
### ECG Circuit
<div class="text-center">
[](circuit.jpg)
</div>
__The circuit is simple, but a lot of time and thought and experimentation went into it.__ I settled on this design because it produced the best and most reliable results, and it has a few nuances which might not be obvious at first. Although I discuss it in detail in the video, here are the highlights:
* The output goes to the microphone jack of your computer.
* There's nothing special about the op-amp I used ([LM741](http://www.ti.com/lit/ds/symlink/lm741.pdf)). A single unit of an [LM324](http://www.ti.com.cn/cn/lit/ds/symlink/lm2902-n.pdf) (or any general purpose op-amp) should work just as well.
* Resistor values were chosen because I had them on hand. You can probably change them a lot as long as they're in the same ballpark of the values shown here. Just make sure R1 and R2 are matched, and R3 should be at least 10MOhm.
* <span style="color: #ff0000;">Do not use a bench power supply!</span> "BAT+" and "BAT-" are the leads of a single 9V battery.
* Note that the leg electrode is ground (same ground as the computer's microphone ground)
* R5 and R4 form a traditional voltage divider like you'd expect for an op-amp with a gain of about 50.
* You'd expect R4 to connect to ground, but since your body is grounded, chest 2 is essentially the same
* R3 must be extremely high value, but it pulls your body potential near the optimal input voltage for amplification by the op-amp.
* R1 and R2 split the 9V battery's voltage in half and center it at ground, creating -4.5V and +4.5V.
* altogether, your body stays grounded, and the op-amp becomes powered by -4.5V and +4.5V, and your body is conveniently near the middle and ready to have small signals from CHEST1 amplified. Amplification is with respect to CHEST2 (roughly ground), rather than actual ground, so that a lot of noise (with respect to ground) is eliminated.
<div class="text-center img-border">
[](IMG_7574.jpg)
</div>
__For those of you who would rather see a picture than a schematic__, here's a diagram of how to assemble it graphically. This should be very easy to reproduce. Although breadboards are typically not recommended for small signal amplification projects, there is so much noise already in these signals that it doesn't really matter much either way. Check out how good the signals look in my video, and consider that I use a breadboard the entire time.
<div class="text-center">
[](design.jpg)
</div>
__The most comfortable electrodes I used were made for muscle simulators.__ A friend of mine showed me some muscle stimulator pads he got for a back pain relief device he uses. As soon as I saw those pads, I immediately thought they would be perfect for building an ECG! They're a little bit expensive, but very comfortable, reusable, last a long time, and produce brilliant results. They also have 3.5 mm (headphone jack) connectors which is perfect for DIY projects. On Amazon.com you can get 16 pads for $11 with free shipping. I decided not to include links, because sometimes the pads and cords are sold separately, and sometimes they have barrel connectors and sometimes they have snap connectors. Just get any adhesive reusable electrodes intended for [transcutaneous electrical nerve stimulation (TENS)](https://en.wikipedia.org/wiki/Transcutaneous_electrical_nerve_stimulation) that you can find! They should all work fine.
<div class="text-center img-border">
[](IMG_7576.jpg)
</div>
### Pennies as Electrodes
__You can make your own electrodes for $0.03!__ Okay that's a terrible joke, but it's true. I made not-awful electrodes by soldering wires to copper pennies, adding strength by super-gluing the wire to the penny, and using electrical tape to attach them to my chest. Unless you want a tattoo of an old guy's face on your torso, wait until they cool sufficiently after soldering before proceeding to the adhesion step. I suspect that super gluing the penny to your chest would also work, but please do not do this. Ironically, because the adhesive pads of the TENS electrodes wear away over time, the penny solution is probably "more reusable" than the commercial electrode option.
<div class="text-center img-border img-small">
[](IMG_7527.jpg)
[](IMG_7570-1.jpg)
</div>
This ECG was recorded using pennies as electrodes:
<div class="text-center">
[](ECG_1470611901.png)
</div>
__Notes on filtering:__ Why didn't I just use a [hardware low-pass filter](https://en.wikipedia.org/wiki/Low-pass_filter)?
1. It would have required extra components, which goes against the theme of this project
2. It would require _specific value_ components, which is also undesirable for a junkbox project
3. I'm partial to the [Chebyshev filter](https://en.wikipedia.org/wiki/Chebyshev_filter), but getting an extremely sharp roll-off a few Hz shy of 50Hz would take multiple poles (of closely matched passive components) and [not be as trivial as it sounds](http://www.analog.com/library/analogDialogue/archives/43-09/EDCh%208%20filter.pdf?doc=ADA4661-2.pdf).
__Notes on software:__ This a really cool use of Python! I lean on some of my favorite packages [numpy](http://www.numpy.org/), [scipy](https://www.scipy.org/), [matplotlib](http://matplotlib.org/), [pyqrgraph](http://www.pyqtgraph.org/), and [PyQt4](https://wiki.python.org/moin/PyQt4). I've recently made posts describing how to perform real-time data graphing in Python using these libraries, so I won't go into that here. If you're interested, check out my [real-time audio monitor](https://www.swharden.com/wp/2016-07-31-real-time-audio-monitor-with-pyqt/), notes on using [PlotWidget](https://www.swharden.com/wp/2016-07-31-live-data-in-pyqt4-with-plotwidget/), and notes on using [MatPlotLib widget](https://www.swharden.com/wp/2016-07-30-live-data-in-pyqt4-with-matplotlibwidget/). I tried using [PyInstaller](http://www.pyinstaller.org/) to package this project into a single .EXE for all my windows readers who might want to recreate this project, but the resulting EXE was over 160MB! That's crazy! It makes sense considering packagers like PyInstaller and Py2EXE work by building your entire python interpreter and all imported libraries. With all those fun libraries I listed above, it's no wonder it came out so huge. It may be convenient for local quick-fixes, but not a good way to distribute code over the internet. To use this software, just run it in Python. It was tested to work with out-of-the-box [WinPython-64bit-3.5.2.1](https://sourceforge.net/projects/winpython/files/) (not the Qt5 version), so if you want to run it yourself start there.
__Notes on safety.__ How safe is this project? I'm conflicted on this subject. I want to be as conservative as I can (leaning on the side of caution), but I also want to be as realistic as possible. I'm going to play it safe and say "this may not be safe, so don't build or use it". As an exercise, let's consider the pros and cons:
* __PROS:__
* It's powered from a 9V battery which is safer than a bench power supply (but see the matching con).
* The only connections to your body are:
* leg - ground. you ground yourself all the time. using a wrist grounding strap is the same thing.
* chest 1 - extremely high impedance. You're attaching your chest to the high impedance input of an op-amp (which I feel fine with), and also to a floating battery through a 10MOhm resistor (which also I feel fine with)
* chest 2 - raises an eyebrow. In addition to a high impedance input, you're connected to an op-amp through a 100k resistor. Even if the op-amp were putting out a full 4.5V, that's 0.045mA (which doesn't concern me a whole lot).
* I don't know where to stick this, but I wonder what type of voltages / currents [TENS](https://en.wikipedia.org/wiki/Transcutaneous_electrical_nerve_stimulation) actually provide.
* __CONS / WARNINGS:__
* It's powered from a 9V battery. So are many stun guns.
* If the op-amp oscillates, oscillations may enter your body. Personally I feel this may be the most concerning issue.
* Small currents can kill. I found a [curiously colored website](https://www.physics.ohio-state.edu/~p616/safety/fatal_current.html) that describes this. It seems like the most dangerous potential effect is induction of cardiac fibrillation, which can occur around 100mA.
__Improving safety through optical isolation:__ The safety of this device may be improved (albeit with increased complexity) through the implementation of [opto-isolators](https://en.wikipedia.org/wiki/Opto-isolator). I may consider a follow-up post demonstrating how I do this. Unlike digital signals which I've [optically isolated before](https://www.swharden.com/wp/2016-07-28-opto-isolated-laser-controller-build/), I've never personally isolated analog signals. Although I'm sure there are fully analog means to do this, I suspect I'd accomplish it by turning it into a digital signal (with a voltage-to-frequency converter), pulsing the output across the optoisolator, and turning it back into voltage with a frequency-to-voltage converter or perhaps even a passive low-pass filter. Analog Devices has a good write-up about [optical isolation techniques](http://www.analog.com/media/en/training-seminars/tutorials/MT-071.pdf).
__Do you have comments regarding the safety of this device?__ Write your thoughts concisely and send them to me in an email! I'd be happy to share your knowledge with everyone by posting it here.
__Did you build this or a device similar to it?__ Send me some pictures! I'll post them here.
__Source code and project files:__ <https://github.com/swharden/diyECG-1opAmp/>
___LEGAL__: This website is for educational purposes only. Do not build or use any electrical devices shown. Attaching non-compliant electronic devices to your body may be dangerous. Consult a physician regarding proper usage of medical equipment._
⚠️ 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.
Of the hundreds of projects I've shared over the years, none has attracted more attention than my DIY ECG machine on the cheap posted almost 4 years ago. This weekend I re-visited the project and made something I'm excited to share! The original project was immensely popular, my first featured article on Hack-A-Day, and today "ECG" still represents the second most searched term by people who land on my site. My gmail account also has had 194 incoming emails from people asking details about the project. A lot of it was by frustrated students trying to recreate the project running into trouble because it was somewhat poorly documented. Clearly, it's a project that a wide range of people are interested in, and I'm happy to revisit it bringing new knowledge and insight to the project. I will do my best to document it thoroughly so anyone can recreate it!
The goal of this project is to collect heartbeat information on a computer with minimal cost and minimal complexity. I accomplished this with fewer than a dozen components (all of which can be purchased at RadioShack). It serves both as a light-based heartbeat monitor (similar to a pulse oximeter, though it's not designed to quantitatively measure blood oxygen saturation), and an electrocardiogram (ECG) to visualize electrical activity generated by heart while it contracts. Let's jump right to the good part - this is what comes out of the machine:
That's my actual heartbeat. Cool, right? Before I go into how the circuit works, let's touch on how we measure heartbeat with ECG vs. light (like a pulse oximeter). To form a heartbeat, the pacemaker region of the heart (called the SA node, which is near the upper right of the heart) begins to fire and the atria (the two top chambers of the heart) contract. The SA node generates a little electrical shock which stimulated a synchronized contraction. This is exactly what defibrillators do when a heart has stopped beating. When a heart attack is occurring and a patient is undergoing ventricular fibrillation, it means that heart muscle cells are contracting randomly and not in unison, so the heart quivers instead of pumping as an organ. Defibrillators synchronize the heart beat with a sudden rush of current over the heart to reset all of the cells to begin firing at the same time (thanks Ron for requesting a more technical description). If a current is run over the muscle, the cells (cardiomyocytes) all contract at the same time, and blood moves. The AV node (closer to the center of the heart) in combination with a slow conducting pathway (called the bundle of His) control contraction of the ventricles (the really large chambers at the bottom of the heart), which produce the really large spikes we see on an ECG. To measure ECG, optimally we'd place electrodes on the surface of the heart. Since that would be painful, we do the best we can by measuring voltage changes (often in the mV range) on the surface of the skin. If we amplify it enough, we can visualize it. Depending on where the pads are placed, we can see different regions of the heart contract by their unique electrophysiological signature. ECG requires sticky pads on your chest and is extremely sensitive to small fluctuations in voltage. Alternatively, a pulse oximeter measures blood oxygenation and can monitor heartbeat by clipping onto a finger tip. It does this by shining light through your finger and measuring how much light is absorbed. This goes up and down as blood is pumped through your finger. If you look at the relationship between absorbency in the red vs. infrared wavelengths, you can infer the oxygenation state of the blood. I'm not doing that today because I'm mostly interested in detecting heart beats.
For operation as a pulse oximeter-type optical heartbeat detector (a photoplethysmograph which produces a photoplethysmogram), I use a bright red LED to shine light through my finger and be detected by a phototransistor (bottom left of the diagram). I talk about how this works in more detail in a previous post. Basically the phototransistor acts like a variable resistor which conducts different amounts of current depending on how much light it sees. This changes the voltage above it in a way that changes with heartbeats. If this small signal is used as the input, this device acts like a pulse oximeter.
For operation as an electrocardiograph (ECG), I attach the (in) directly to a lead on my chest. One of them is grounded (it doesn't matter which for this circuit - if they're switched the ECG just looks upside down), and the other is recording. In my original article, I used pennies with wires soldered to them taped to my chest as leads. Today, I'm using fancier sticky pads which are a little more conductive. In either case, one lead goes in the center of your chest, and the other goes to your left side under your arm pit. I like these sticky pads because they stick to my skin better than pennies taped on with electrical tape. I got 100 Nikomed Nikotabs EKG Electrodes 0315 on eBay for $5.51 with free shipping (score!). Just gator clip to them and you're good to go!
In both cases, I need to build a device to amplify small signals. This is accomplished with the following circuit. The core of the circuit is an LM324 quad operational amplifier. These chips are everywhere, and extremely cheap. It looks like Thai Shine sells 10 for $2.86 (with free shipping). That's about a quarter each. Nice! A lot of ECG projects use instrumentation amplifiers like the AD620 (which I have used with fantastic results), but these are expensive (about $5.00 each). The main difference is that instrumentation amplifiers amplify the difference between two points (which reduces noise and probably makes for a better ECG machine), but for today an operational amplifier will do a good enough job amplifying a small signal with respect to ground. I get around the noise issue by some simple filtering techniques. Let's take a look at the circuit.
This project utilizes one of the op-amps as a virtual ground. One complaint of using op-amps in simple projects is that they often need + and - voltages. Yeah, this could be done with two 9V batteries to generate +9V and -9V, but I think it's easier to use a single power source (+ and GND). A way to get around that is to use one of the op-amps as a current source and feed it half of the power supply voltage (VCC), and use the output as a virtual ground (allowing VCC to be your + and 0V GND to be your -). For a good description of how to do this intelligently, read the single supply op amps web page. The caveat is that your signals should remain around VCC/2, which can be done if it is decoupled by feeding it through a series capacitor. The project works at 12V or 5V, but was designed for (and has much better output) at 12V. The remaining 3 op-amps of the LM324 serve three unique functions:
STAGE 1: High gain amplifier. The input signals from either the ECG or pulse oximeter are fed into a chain of 3 opamp stages. The first is a preamplifier. The output is decoupled through a series capacitor to place it near VCC/2, and amplified greatly thanks to the 1.8Mohm negative feedback resistor. Changing this value changes initial gain.
STAGE 2: active low-pass filter. The 10kOhm variable resistor lets you adjust the frequency cutoff. The opamp serves as a unity gain current source / voltage follower that has high input impedance when measuring the output f the low-pass filter and reproduces its voltage with a low impedance output. There's some more information about active filtering on this page. It's best to look at the output of this stage and adjust the potentiometer until the 60Hz noise (caused by the AC wiring in the walls) is most reduced while the lower-frequency component of your heartbeat is retained. With the oximeter, virtually no noise gets through. Because the ECG signal is much smaller, this filter has to be less aggressive, and this noise is filtered-out by software (more on this later).
STAGE 3: final amplifier with low-pass filter. It has a gain of ~20 (determined by the ratio of the 1.8kOhm to 100Ohm resistors) and lowpass filtering components are provided by the 22uF capacitor across the negative feedback resistor. If you try to run this circuit at 5V and want more gain (more voltage swing), consider increasing the value of the 1.8kOhm resistor (wit the capacitor removed). Once you have a good gain, add different capacitor values until your signal is left but the noise reduced. For 12V, these values work fine. Let's see it in action!
Now for the second half - getting it into the computer. The cheapest and easiest way to do this is to simply feed the output into a sound card! A sound card is an analog-to-digital converter (ADC) that everybody has and can sample up to 48 thousand samples a second! (overkill for this application) The first thing you should do is add an output potentiometer to allow you to drop the voltage down if it's too big for the sound card (in the case of the oximeter) but but also allow full-volume in the case of sensitive measurements (like ECG). Then open-up sound editing software (I like GoldWave for Windows or Audacity for Linux, both of which are free) and record the input. You can do filtering (low-pass filter at 40Hz with a sharp cutoff) to further eliminate any noise that may have sneaked through. Re-sample at 1,000 Hz (1kHz) and save the output as a text file and you're ready to graph it! Check it out.
Here are the results of some actual data recorded and processed with the method shown in the video. let's look at the pulse oximeter first.
That looks pretty good, certainly enough for heartbeat detection. There's obvious room for improvement, but as a proof of concept it's clearly working. Let's switch gears and look at the ECG. It's much more challenging because it's signal is a couple orders of magnitude smaller than the pulse oximeter, so a lot more noise gets through. Filtering it out offers dramatic improvements!
Here's the code I used to generate the graphs from the text files that GoldWave saves. It requires Python, Matplotlib (pylab), and Numpy. In my case, I'm using 32-bit 2.6 versions of everything.
# DIY Sound Card ECG/Pulse Oximeter
# by Scott Harden (2013) http://www.SWHarden.com
import pylab
import numpy
f=open("light.txt")
raw=f.readlines()[1:]
f.close()
data = numpy.array(raw,dtype=float)
data = data-min(data) #make all points positive
data = data/max(data)*100.0 #normalize
times = numpy.array(range(len(data)))/1000.0
pylab.figure(figsize=(15,5))
pylab.plot(times,data)
pylab.xlabel("Time Elapsed (seconds)")
pylab.ylabel("Amplitude (% max)")
pylab.title("Pulse Oximeter - filtered")
pylab.subplots_adjust(left=.05,right=.98)
pylab.show()
Future directions involve several projects I hope to work on soon. First, it would be cool to miniaturize everything with surface mount technology (SMT) to bring these things down to the size of a postage stamp. Second, improved finger, toe, or ear clips (or even taped-on sensors) over long duration would provide a pretty interesting way to analyze heart rate variability or modulation in response to stress, sleep apnea, etc. Instead of feeding the signal into a computer, one could send it to a micro-controller for processing. I've made some darn-good progress making multi-channel cross-platform USB option for getting physiology data into a computer, but have some work still to do. Alternatively, this data could be graphed on a graphical LCD for an all-in-one little device that doesn't require a computer. Yep, lots of possible projects can use this as a starting point.
Notes about safety: If you're worried about electrical shock, or unsure of your ability to make a safe device, don't attempt to build an ECG machine. For an ECG to work, you have to make good electrical contact with your skin near your heart, and some people feel this is potentially dangerous. Actually, some people like to argue about how dangerous it actually is, as seen on Hack-A-Day comments and my previous post comments. Some people have suggested the danger is negligible and pointed-out that it's similar to inserting ear-bud headphones into your ears. Others have suggested that it's dangerous and pointed-out that milliamps can kill a person. Others contest that pulses of current are far more dangerous than a continuous applied current. Realists speculate that virtually no current would be delivered by this circuit if it is wired properly. Rational, cautionary people worried about it reduce risk of accidental current by applying bidirectional diodes at the level of the chest leads, which short any current (above 0.7V) similar to that shown here. Electrically-savvy folks would design an optically decoupled solution. Intelligent folks who abstain from arguing on the internet would probably consult the datasheets regarding ECG input protection. In all cases, don't attach electrical devices to your body unless you are confident in their safety. As a catch-all, I present the ECG circuit for educational purposes only, and state that it may not be safe and should not be replicated There, will that cover me in court in case someone tapes wires to their chest and plugs them in the wall socket?
LET ME KNOW WHAT YOU THINK! If you make this, I'm especially interested to see how it came out. Take pictures of your projects and send them my way! If you make improvements, or take this project further, I'd be happy to link to it on this page. I hope this page describes the project well enough that anyone can recreate it, regardless of electronics experience. Finally, I hope that people are inspired by the cool things that can be done with surprisingly simple electronics. Get out there, be creative, and go build something cool!
Markdown source code last modified on August 23rd, 2022
---
title: Simple DIY ECG + Pulse Oximeter (version 2)
date: 2013-04-14 16:00:14
tags: diyECG, microcontroller, old
---
# Simple DIY ECG + Pulse Oximeter (version 2)
> **⚠️ Check out my newer ECG designs:**
* [**Sound Card ECG with AD8232**](https://swharden.com/blog/2019-03-15-sound-card-ecg-with-ad8232/)
* [**Single op-amp ECG**](https://swharden.com/blog/2016-08-08-diy-ecg-with-1-op-amp/)
__Of the hundreds of projects I've shared over the years, none has attracted more attention than my [DIY ECG machine on the cheap](http://www.swharden.com/blog/2009-08-14-diy-ecg-machine-on-the-cheap/) posted almost 4 years ago. This weekend I re-visited the project and made something I'm excited to share!__ The original project was immensely popular, my [first featured article on Hack-A-Day](http://hackaday.com/2009/08/22/collect-and-analyze-ecg-data/), and today "ECG" still represents the second most searched term by people who land on my site. My gmail account also has had 194 incoming emails from people asking details about the project. A lot of it was by frustrated students trying to recreate the project running into trouble because it was somewhat poorly documented. Clearly, it's a project that a wide range of people are interested in, and I'm happy to revisit it bringing new knowledge and insight to the project. I will do my best to document it thoroughly so anyone can recreate it!
<div class="text-center img-border">
[](diy-ecg-pulse-oximeter-lm324-opamp-sound-card.jpg)
</div>
__The goal of this project is to collect heartbeat information on a computer with minimal cost and minimal complexity.__ I accomplished this with fewer than a dozen components (all of which can be purchased at RadioShack). It serves both as a light-based heartbeat monitor (similar to a pulse oximeter, though it's not designed to quantitatively measure blood oxygen saturation), and an electrocardiogram (ECG) to visualize electrical activity generated by heart while it contracts. Let's jump right to the good part - this is what comes out of the machine:
<div class="text-center">
[](pulse-ecg-filtered-a.png)
</div>
<strong>That's <em>my</em> actual heartbeat. Cool, right? Before I go into how the circuit works, let's touch on how we measure heartbeat with ECG vs. light (like a pulse oximeter).</strong> To form a heartbeat, the pacemaker region of the heart (called the SA node, which is near the upper right of the heart) begins to fire and the atria (the two top chambers of the heart) contract. The SA node generates a little electrical shock which stimulated a synchronized contraction. <span style="text-decoration: line-through;">This is exactly what defibrillators do when a heart has stopped beating.</span> When a heart attack is occurring and a patient is undergoing ventricular fibrillation, it means that heart muscle cells are contracting randomly and not in unison, so the heart quivers instead of pumping as an organ. Defibrillators synchronize the heart beat with a sudden rush of current over the heart to reset all of the cells to begin firing at the same time (thanks Ron for requesting a more technical description). If a current is run over the muscle, the cells (cardiomyocytes) all contract at the same time, and blood moves. The AV node (closer to the center of the heart) in combination with a slow conducting pathway (called the bundle of His) control contraction of the ventricles (the really large chambers at the bottom of the heart), which produce the really large spikes we see on an ECG. <strong>To measure ECG</strong>, optimally we'd place electrodes on the surface of the heart. Since that would be painful, we do the best we can by measuring voltage changes (often in the mV range) on the surface of the skin. If we amplify it enough, we can visualize it. Depending on where the pads are placed, we can see different regions of the heart contract by their unique electrophysiological signature. ECG requires sticky pads on your chest and is extremely sensitive to small fluctuations in voltage. Alternatively, <strong>a pulse oximeter measures blood oxygenation and can monitor heartbeat by clipping onto a finger tip</strong>. It does this by shining light through your finger and measuring how much light is absorbed. This goes up and down as blood is pumped through your finger. If you look at the relationship between absorbency in the red vs. infrared wavelengths, you can infer the oxygenation state of the blood. I'm not doing that today because I'm mostly interested in detecting heart beats.
<strong>For operation as a pulse oximeter-type optical heartbeat detector (a <em>photoplethysmograph</em> which produces a <a href="http://en.wikipedia.org/wiki/Photoplethysmogram"><em>photoplethysmogram</em></a>),</strong> I use a bright red LED to shine light through my finger and be detected by a phototransistor (bottom left of the diagram). I talk about how this works in more detail <a href="http://www.swharden.com/blog/2012-12-06-single-wavelength-pulse-oximeter/">in a previous post</a>. Basically the phototransistor acts like a variable resistor which conducts different amounts of current depending on how much light it sees. This changes the voltage above it in a way that changes with heartbeats. If this small signal is used as the input, this device acts like a pulse oximeter.
<div class="text-center img-border">
[](2013-04-14-11.36.39.jpg)
</div>
<strong>For operation as an electrocardiograph (ECG)</strong>, I attach the (in) directly to a lead on my chest. One of them is grounded (it doesn't matter which for this circuit - if they're switched the ECG just looks upside down), and the other is recording. In my <a href="http://www.swharden.com/blog/2009-08-14-diy-ecg-machine-on-the-cheap/">original article</a>, I used pennies with wires soldered to them taped to my chest as leads. Today, I'm using fancier sticky pads which are a little more conductive. In either case, one lead goes in the center of your chest, and the other goes to your left side under your arm pit. I like these sticky pads because they stick to my skin better than pennies taped on with electrical tape. I got <a href="http://www.ebay.com/sch/i.html?_trksid=m570.l3201&_nkw=100+NIKOMED+NIKOTABS+EKG+ELECTRODES+0315&_sacat=0">100 Nikomed Nikotabs EKG Electrodes 0315</a> on eBay for $5.51 with free shipping (score!). Just gator clip to them and you're good to go!
<div class="text-center img-border">
[](2013-04-14-15.06.20.jpg)
</div>
__In both cases, I need to build a device to amplify small signals__. This is accomplished with the following circuit. The core of the circuit is an [LM324 quad operational amplifier](http://www.ti.com/lit/ds/symlink/lm124-n.pdf). These chips are everywhere, and extremely cheap. It looks like [Thai Shine sells 10 for $2.86](http://www.thaishine.com/servlet/the-910/10-x-LM324N-LM324/Detail) (with free shipping). That's about a quarter each. Nice! A lot of ECG projects use instrumentation amplifiers like the AD620 (which I have used with [fantastic results](http://www.swharden.com/blog/2012-06-14-multichannel-usb-analog-sensor-with-atmega48/)), but these are expensive (about $5.00 each). The main difference is that instrumentation amplifiers amplify the difference between two points (which reduces noise and probably makes for a better ECG machine), but for today an operational amplifier will do a good enough job amplifying a small signal with respect to ground. I get around the noise issue by some simple filtering techniques. Let's take a look at the circuit.
<div class="text-center img-border">
[](lm324-opamp-pulse-oximeter-ecg-schematic.jpg)
</div>
<strong>This project utilizes one of the op-amps as a <a href="http://en.wikipedia.org/wiki/Virtual_ground">virtual ground</a>.</strong> One complaint of using op-amps in simple projects is that they often need + and - voltages. Yeah, this <a href="http://cdn.head-fi.org/8/80/801b6a4a_principle.gif">could be done with two 9V batteries</a> to generate +9V and -9V, but I think it's easier to use a single power source (+ and GND). A way to get around that is to use one of the op-amps as a current source and feed it half of the power supply voltage (VCC), and use the output as a virtual ground (allowing VCC to be your + and 0V GND to be your -). For a good description of how to do this intelligently, read the <a href="http://www.swarthmore.edu/NatSci/echeeve1/Ref/SingleSupply/SingleSupply.html">single supply op amps web page</a>. The caveat is that your signals should remain around VCC/2, which can be done if it is decoupled by feeding it through a series capacitor. The project works at 12V or 5V, but was designed for (and has much better output) at 12V. The remaining 3 op-amps of the LM324 serve three unique functions:
<strong>STAGE 1: High gain amplifier.</strong> The input signals from either the ECG or pulse oximeter are fed into a chain of 3 opamp stages. The first is a preamplifier. The output is decoupled through a series capacitor to place it near VCC/2, and amplified greatly thanks to the 1.8Mohm negative feedback resistor. Changing this value changes initial gain.
<strong>STAGE 2: active low-pass filter.</strong> The 10kOhm variable resistor lets you adjust the frequency cutoff. The opamp serves as a unity gain current source / voltage follower that has high input impedance when measuring the output f the low-pass filter and reproduces its voltage with a low impedance output. There's some <a href="http://www.electronics-tutorials.ws/filter/filter_5.html">more information about active filtering on this page</a>. It's best to look at the output of this stage and adjust the potentiometer until the 60Hz noise (caused by the AC wiring in the walls) is most reduced while the lower-frequency component of your heartbeat is retained. With the oximeter, virtually no noise gets through. Because the ECG signal is much smaller, this filter has to be less aggressive, and this noise is filtered-out by software (more on this later).
<strong>STAGE 3: final amplifier with low-pass filter.</strong> It has a gain of ~20 (determined by the ratio of the 1.8kOhm to 100Ohm resistors) and lowpass filtering components are provided by the 22uF capacitor across the negative feedback resistor. If you try to run this circuit at 5V and want more gain (more voltage swing), consider increasing the value of the 1.8kOhm resistor (wit the capacitor removed). Once you have a good gain, add different capacitor values until your signal is left but the noise reduced. For 12V, these values work fine. Let's see it in action!

<strong>Now for the second half - getting it into the computer.</strong> The cheapest and easiest way to do this is to simply feed the output into a sound card! A sound card is an analog-to-digital converter (ADC) that <em>everybody</em> has and can sample up to 48 thousand samples a second! (overkill for this application) The first thing you should do is add an output potentiometer to allow you to drop the voltage down if it's too big for the sound card (in the case of the oximeter) but but also allow full-volume in the case of sensitive measurements (like ECG). Then open-up sound editing software (I like <a href="http://www.goldwave.com/">GoldWave</a> for Windows or <a href="http://audacity.sourceforge.net/">Audacity</a> for Linux, both of which are free) and record the input. You can do filtering (low-pass filter at 40Hz with a sharp cutoff) to further eliminate any noise that may have sneaked through. Re-sample at 1,000 Hz (1kHz) and save the output as a text file and you're ready to graph it! Check it out.

__Here are the results__ of some actual data recorded and processed with the method shown in the video. let's look at the pulse oximeter first.
<div class="text-center">
[](pulse-ecg-filtered-a.png)
</div>
<strong>That looks pretty good, certainly enough for heartbeat detection.</strong> There's obvious room for improvement, but as a proof of concept it's clearly working. Let's switch gears and look at the ECG. It's much more challenging because it's signal is a couple orders of magnitude smaller than the pulse oximeter, so a lot more noise gets through. Filtering it out offers dramatic improvements!
<div class="text-center">
[](pulse-oximeter-a.png)
[](pulse-oximeter-b.png)
</div>
<strong>Here's the code</strong> I used to generate the graphs from the text files that GoldWave saves. It requires <a href="http://www.Python.org">Python</a>, <a href="http://matplotlib.org/">Matplotlib (pylab)</a>, and <a href="http://www.scipy.org/Download">Numpy</a>. In my case, I'm using 32-bit 2.6 versions of everything.
```python
# DIY Sound Card ECG/Pulse Oximeter
# by Scott Harden (2013) http://www.SWHarden.com
import pylab
import numpy
f=open("light.txt")
raw=f.readlines()[1:]
f.close()
data = numpy.array(raw,dtype=float)
data = data-min(data) #make all points positive
data = data/max(data)*100.0 #normalize
times = numpy.array(range(len(data)))/1000.0
pylab.figure(figsize=(15,5))
pylab.plot(times,data)
pylab.xlabel("Time Elapsed (seconds)")
pylab.ylabel("Amplitude (% max)")
pylab.title("Pulse Oximeter - filtered")
pylab.subplots_adjust(left=.05,right=.98)
pylab.show()
```
<strong>Future directions involve several projects</strong> I hope to work on soon. First, it would be cool to miniaturize everything with surface mount technology (SMT) to bring these things down to the size of a postage stamp. Second, improved finger, toe, or ear clips (or even taped-on sensors) over long duration would provide a pretty interesting way to analyze heart rate variability or modulation in response to stress, sleep apnea, etc. Instead of feeding the signal into a computer, one could send it to a micro-controller for processing. I've made some <a href="http://www.swharden.com/blog/2012-06-14-multichannel-usb-analog-sensor-with-atmega48/">darn-good progress making multi-channel cross-platform USB option for getting physiology data into a computer</a>, but have some work still to do. Alternatively, this data could be graphed on a <a href="http://learn.adafruit.com/system/assets/assets/000/000/899/medium800/graphiclcd.jpg?1342115751">graphical LCD</a> for an all-in-one little device that doesn't require a computer. Yep, lots of possible projects can use this as a starting point.
<strong>Notes about safety:</strong> If you're worried about electrical shock, or unsure of your ability to make a safe device, don't attempt to build an ECG machine. For an ECG to work, you have to make good electrical contact with your skin near your heart, and some people feel this is potentially dangerous. Actually, some people like to argue about how dangerous it actually is, as seen on <a href="http://hackaday.com/2009/08/22/collect-and-analyze-ecg-data/#comments">Hack-A-Day comments</a> and my <a href="http://www.swharden.com/blog/2009-08-14-diy-ecg-machine-on-the-cheap/#comments">previous post comments</a>. Some people have suggested the danger is negligible and pointed-out that it's similar to inserting ear-bud headphones into your ears. Others have suggested that it's dangerous and pointed-out that <a href="http://hypertextbook.com/facts/2000/JackHsu.shtml">milliamps can kill a person</a>. Others contest that pulses of current are far more dangerous than a continuous applied current. Realists speculate that virtually no current would be delivered by this circuit if it is wired properly. Rational, cautionary people worried about it reduce risk of accidental current by applying bidirectional diodes at the level of the chest leads, which short any current (above 0.7V) similar to <a href="http://www.extremecircuits.net/2010/07/ecg-amplifier-by-tlc274.html">that shown here</a>. Electrically-savvy folks would design an optically decoupled solution. Intelligent folks who abstain from arguing on the internet would probably consult the <a href="http://www.analog.com/static/imported-files/tech_articles/MS-2160.pdf">datasheets regarding ECG input protection</a>. In all cases, don't attach electrical devices to your body unless you are confident in their safety. As a catch-all, I present the ECG circuit for educational purposes only, and state that it may not be safe and should not be replicated There, will that cover me in court in case someone tapes wires to their chest and plugs them in the wall socket?
<strong>LET ME KNOW WHAT YOU THINK!</strong> If you make this, I'm especially interested to see how it came out. Take pictures of your projects and send them my way! If you make improvements, or take this project further, I'd be happy to link to it on this page. I hope this page describes the project well enough that anyone can recreate it, regardless of electronics experience. Finally, I hope that people are inspired by the cool things that can be done with surprisingly simple electronics. Get out there, be creative, and go build something cool!
⚠️ 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.
I want to create a microcontroller application which will utilize information obtained from a home-brew pulse oximeter. Everybody and their cousin seems to have their own slant how to make DIY pulse detectors, but I might as well share my experience. Traditionally, pulse oximeters calculate blood oxygen saturation by comparing absorbance of blood to different wavelengths of light. In the graph below (from Dildy et al., 1996 that deoxygenated blood (dark line) absorbs light differently than oxygenated blood (thin line), especially at 660nm (red) and 920nm (infrared). Therefore, the ratio of the difference of absorption at 660nm vs 920nm is an indication of blood oxygenation. Fancy (or at least well-designed) pulse oximeters continuously look at the ratio of these two wavelengths. Analog devices has a nice pulse oximeter design using an ADuC7024 microconverter. A more hackerish version was made and described on this non-english forum. A fail-at-the-end page of a simpler project is also shown here, but not well documented IMO.
That's not how mine works. I only use a single illumination source (~660nm) and watch it change with respect to time. Variability is due to a recombination effect of blood volume changes and blood oxygen saturation changes as blood pulses through my finger. Although it's not quite as good, it's a bit simpler, and it definitely works. Embedded-lab has a similar project but the output is only a pulsing LED (not what I want) and a voltage output that only varies by a few mV (not what I want).
Here's what the device looks like assembled in a breadboard:
I made a sensor by drilling appropriately-sized holes in a clothespin for the emitter (LED) and sensor (phototransistor). I had to bend the metal spring to make it more comfortable to wear. Light pressure is better than firm pressure, not only because it doesn't hurt as much, but because a firm pinch restricts blood flow considerably.
An obvious next step is microcontroller + LCD (or computer) digitization, but for now all you can do is check it out on my old-school analog oscilloscope. Vertical squares represent 1V (nice!). You can see the pulse provides a solid 2V spike.
Here's some video of it in action:
I'm holding-back the circuit diagram until I work through it a little more. I don't want to mislead people by having them re-create ill-conceived ideas on how to create analog amplifiers. I'll post more as I develop it.
Markdown source code last modified on January 18th, 2021
---
title: Single Wavelength Pulse Oximeter
date: 2012-12-06 08:13:41
tags: circuit, diyECG, old
---
# Single Wavelength Pulse Oximeter
> **⚠️ Check out my newer ECG designs:**
* [**Sound Card ECG with AD8232**](https://swharden.com/blog/2019-03-15-sound-card-ecg-with-ad8232/)
* [**Single op-amp ECG**](https://swharden.com/blog/2016-08-08-diy-ecg-with-1-op-amp/)
__I want to create a microcontroller application__ which will utilize information obtained from a home-brew pulse oximeter. Everybody and their cousin seems to have their own slant how to make DIY pulse detectors, but I might as well share my experience. Traditionally, pulse oximeters calculate blood oxygen saturation by comparing absorbance of blood to different wavelengths of light. In the graph below (from [Dildy et al., 1996](http://www.ncbi.nlm.nih.gov/pubmed/8694032) that deoxygenated blood (dark line) absorbs light differently than oxygenated blood (thin line), especially at 660nm (red) and 920nm (infrared). Therefore, the ratio of the difference of absorption at 660nm vs 920nm is an indication of blood oxygenation. Fancy (or at least well-designed) pulse oximeters continuously look at the ratio of these two wavelengths. Analog devices has a [nice pulse oximeter design using an ADuC7024 microconverter](http://www.analog.com/library/analogDialogue/archives/41-01/pulse_oximeter.html). A more hackerish version was made and described [on this non-english forum](http://www.elektroda.pl/rtvforum/viewtopic.php?p=8025042). A fail-at-the-end page of a simpler project is also shown [here](http://blog.energymicro.com/2012/11/21/create-a-simple-pulse-oximeter-with-tiny-gecko/), but not well documented IMO.
<div class="text-center">

</div>
That's not how mine works. I only use a single illumination source (~660nm) and watch it change with respect to time. Variability is due to a recombination effect of blood volume changes and blood oxygen saturation changes as blood pulses through my finger. Although it's not quite as good, it's a bit simpler, and it definitely works. [Embedded-lab has a similar project](http://embedded-lab.com/blog/?p=5508) but the output is only a pulsing LED (not what I want) and a voltage output that only varies by a few mV (not what I want).
__Here's what the device looks like assembled in a breadboard:__
<div class="text-center img-border img-medium">
[](IMG_5919.jpg)
</div>
__I made a sensor__ by drilling appropriately-sized holes in a clothespin for the emitter (LED) and sensor (phototransistor). I had to bend the metal spring to make it more comfortable to wear. Light pressure is better than firm pressure, not only because it doesn't hurt as much, but because a firm pinch restricts blood flow considerably.
<div class="text-center img-border img-small">
[](IMG_5920.jpg)
[](IMG_5924.jpg)
</div>
__An obvious next step__ is microcontroller + LCD (or computer) digitization, but for now all you can do is check it out on my old-school analog oscilloscope. Vertical squares represent 1V (nice!). You can see the pulse provides a solid 2V spike.
<div class="text-center img-border img-medium">

</div>
__Here's some video of it in action:__

I'm holding-back the circuit diagram until I work through it a little more. I don't want to mislead people by having them re-create ill-conceived ideas on how to create analog amplifiers. I'll post more as I develop it.