Posts with «bioengineering» label

Capacitive sensing with Schmitt trigger

Capacitive sensing with op amps and Capacitive sensing with op amps, continued used a rather complicated circuit to make a Schmitt-trigger oscillator out of op amps:

Modified circuit for longer period. C1 is just the stray capacitance of the touch sensor, with no deliberately added capacitance.

But if we use an off-the-shelf Schmitt trigger chip (like a 74HC14), then a very simple circuit can be made to oscillate:

Schmitt-trigger oscillator.

Without a touch sensor, it oscillates at about 10 kHz. With an untouched touch sensor, the frequency drops to about 9.5 kHz. With a touched sensor, the frequency drops further to around 6.7 kHz. I can make the touch sensor have a bigger relative frequency change by reducing the capacitor to 157pF (3 470pF in series), from 15kHz down to 8kHz. This oscillator works fine with the code I wrote for the op-amp oscillator. Neither the resistor nor the capacitor values are particularly critical (as long as the addition of about 140pF from the touch drops the frequency enough to be measurable).

The Schmitt trigger is a useful device for students to learn about, since hysteresis is an important concept in detecting signals. In fact, it might not be a bad idea to have the code that detects the frequency and turns the LED on or off have some hysteresis, as code that just uses a time-out for debouncing tends to make the LED flash on and off when a near-touch is done.

This circuit is too simple for a full 3-hour lab. It can be wired in a couple of minutes and tested in a few more. I’ll have to think of other things to do with a Schmitt trigger to make this into a full lab.  Perhaps this could be an Arduino programming lab, where they start with just a simple pulseIn program and make some modifications:

void setup(void)
{  pinMode(2,INPUT);
   pinMode(13,OUTPUT);
}

void loop(void)
{
    uint8_t on = (pulseIn(2,HIGH) >= 50) ;
    digitalWrite(13, on);
}

Perhaps a simple hysteresis program:

void setup(void)
{  pinMode(2,INPUT);
   pinMode(13,OUTPUT);
}

void loop(void)
{   digitalWrite(13, LOW);
    while (pulseIn(2,HIGH) <= 50) {}
    digitalWrite(13, HIGH);
    while (pulseIn(2,HIGH) >= 40) {}
}

Students would have to measure their oscillator waveforms on the oscilloscope, then play with the constants in the code to get reliable switching. It’s still not a 3-hour lab, but it gives another view of hysteresis.

I’ll have to think about this some more.


Filed under: Circuits course Tagged: Arduino, bioengineering, capacitive touch sensor, circuits, course design, op amp, Schmitt trigger, sensors, teaching

Order and topics for labs

I had a good discussion with Steve P. this afternoon about the order and purpose of the labs I’ve designed so far.  He’ll be putting together a list of EE topics we have to cover to coordinate with the labs, so that students will have enough theory to do each lab, but not be overwhelmed with theory that they don’t yet have a use for.

I’ve designed the labs mainly around the interests of bioengineering majors, but I’ve tried to keep in mind other possible students, such as Digital Arts and New Media students, who would be interested in practical sensor circuits for interfacing to art projects (particularly for inputs to Arduino microprocessors).

Lab 1: thermistor

See posts

  1. More musings on circuits course: temperature lab
  2. Temperature lab, part2
  3. Temperature lab, part 3: voltage divider

The first lab will consist of 3 parts, all involving the use of a Vishay BC Components NTCLE413E2103F520L thermistor.

First, the students would use a bench multimeter to measure the resistance of the thermistor, dunking it in various water baths (with thermometers in them to measure the temperature).  They should fit a simple curve to this data (warning: temperature needs to be on an absolute scale).

Second, they would add a series resistor to make a voltage divider. They have to choose a value to get as large and linear a voltage response as possible at some specified “most-interesting” temperature (perhaps body temperature, perhaps room temperature, perhaps DNA melting temperature).  There should probably be a pre-lab exercise where they derive the formula for maximizing . They would then measure and plot the voltage output for the same set of water baths. If they do it right, they should get a much more linear response than for their resistance measurements.

Finally, they would hook up the voltage divider to an Arduino analog input and record a time series of a water bath cooling off (perhaps adding an ice cube to warm water to get a fast temperature change), and plot temperature as a function of time.

EE concepts needed: voltage, resistance, voltage divider, notion of a transducer.

Lab skills developed: use of multimeter for measuring resistance and voltage, use of Arduino with data-acquisition program to record a time series, fitting a model to data points, simple breadboarding.

Note:  Mylène suggested that we start student familiarization with the test equipment by having them use the multimeters to measure other multimeters.  What is the resistance of a multimeter that is measuring voltage?  of one that is measuring current? what current or voltage is used for the resistance measurement?  We might want to do this first.

 Lab 2: electret microphone

See posts

  1. Oscilloscope practice lab
  2. Op-amp lab

Mylène suggested that we start oscilloscope familiarity by looking at the output of power supplies. What ripple can you see on the voltage output of a benchtop supply? of a cheap wall wart?  This requires the students to learn the difference between DC and AC input coupling for oscilloscopes.  I think that we may be able to teach what we need here without measuring the power supplies, though that is a good backup plan.

First, we would have the students measure and plot the DC current vs. voltage for the microphone.  The microphone is normally operated with a 3V drop across it, but can stand up to 10V, so they should be able to set the Agilent E3631A power supply to various values from 0V to 10V and get the voltage and current readings directly from the bench supply, which has 4-place accuracy for both voltage and current.  There is some danger of the students accidentally delivering too much voltage and frying the mic, but as long as they get the polarity right, that isn’t too big a hazard.  Ideally, they should see that the current is nearly constant as voltage is varied—nothing like a resistor.

Second, we would have them do current-to-voltage conversion with a 5v power supply to get a 2.5v DC output and hook up the output of the microphone to the input of the oscilloscope.  Input can be whistling, talking, iPod earpiece, … . They should learn the difference between AC coupled and DC coupled inputs to the scope, and how to set the horizontal and vertical scales of the scope.

Third, we would have them design and wire their own DC blocking filter (going down to about 1Hz), and confirm that it has a similar effect to the AC coupling on the scope.

Fourth, they should play sine waves from the function generator through a loudspeaker next to the mic, observe the voltage output with the scope, and measure the voltage with a multimeter, plotting output voltage as a function of frequency.  Note: the specs for the electret mic show a fairly flat response from 50Hz to 3kHz, so most of what the students will see here is the poor response of a cheap speaker at low frequencies.  Those with extra time could look at putting the speaker and mic at opposite ends of tube and seeing what difference that makes.

EE concepts: current sources, AC vs DC, DC blocking by capacitors, RC time constant, sine waves, RMS voltage, properties varying with frequency.

Lab skills: power supply, oscilloscope, function generator, RMS AC voltage measurement.

Lab 3: electrode measurements

See posts

  1. Trying to measure ionic current through small holes
  2. Conductivity of saline solution
  3. On stainless steel
  4. Better measurement of conductivity of saline solution
  5. Measuring Ag/AgCl electrodes

First, we would have the students attempt to measure the resistance of a saline solution using a pair of stainless steel electrodes and a multimeter.  This should fail, as the multimeter gradually charges the capacitance of the electrode/electrolyte interface.  For the safety of the lab equipment, we should have the beakers with salt water in a secondary containment tray at all times.

Second, the students should again use a voltage divider, with 10–100Ω load resistor, but with the function generator driving the voltage divider.  The students should measure the RMS voltage across the resistor and across the electrodes for different frequencies from 3Hz to 300kHz (the range of the AC measurements for the Agilent 34401A Multimeter).  They should plot the magnitude of the impedance of the electrodes as a function of frequency and fit an R2+(R1||C1) model to the data.  A little hand tweaking of parameters should help them understand what each parameter changes about the curve.

Third, the students should repeat the measurements and fits for different concentrations of NaCl (we’ll have to get a liter or so of each stock solution made up by one of the wet labs).  Seeing what parameters change a lot and what parameters change only slightly should help them understand the physical basis for the electrical model.

Fourth, students should make Ag/AgCl electrodes from fine silver wire. To avoid possible problems with Clorox in the lab, we’ll probably have them electroplate in NaCl solutions.  If their electrodes have an area of about 0.8 cm2 (2.5cm of 18 gauge wire with a diameter of 1.024mm), we can electroplate at the recommended current density of 1mA/cm2 (so 0.8mA) in 0.9% (0.16M) NaCl for a minute, reversing polarity occasionally to improve the chloride coat. The instructions I’ve seen vary a lot, so neither the salt concentration nor the current density seem to be particularly critical values. We could provide a constant-current supply, but we can probably get by with just having them use a bench supply and adjust the voltage manually to keep the current around 1mA, using visual feedback to terminate the process. (Some instructions just call for using a 9v battery and a whole coil of silver wire.)  According to Warner Instruments

The color of a well plated electrode will be light gray to a purplish gray. While plating, occasionally reversing the polarity for several seconds tends to deepen the chloride coating and yield a more stable electrode.

Fifth, the students should measure and plot the resistance of a pair of Ag/AgCl electrodes as a function of frequency (as with the stainless steel electrodes). We’ll have to think of an easy way for them to mount their electrodes so that they don’t move and so that the silver-copper interface is not near the salt water.

Sixth, if there is time, measuring the potential between a stainless steel electrode and an Ag/AgCl electrode.

EE concepts: impedance, series and parallel circuits, variation of parameters with frequency.

Electrochemistry concepts: At least a vague understanding of half-cell potentials. Ag → Ag+ + e-,  Ag+ + Cl- → AgCl.

Lab skills: bench power supply, function generator, multimeter, fitting functions of complex numbers, handling liquids in proximity of electronic equipment.

Lab 4: Sampling and aliasing

I don’t know the details of this lab, but Steve P. has a PC board that samples and digitizes an input with an 8-bit ADC, then reconstructs the waveform with a DAC.  He has worked out a lab for explaining and demonstrating aliasing of sampled signals using this board, a signal generator, and a dual-trace oscilloscope.  I’ll have to borrow the board and the lab handout from him to see if there is anything in the lab I’d want to tweak.

EE concepts: quantized time, quantized voltage, sampling frequency, Nyquist frequency, aliasing.

Lab skills: dual traces on oscilloscope.

Lab 5: Op amp basics

See post Op-amp lab

Use an op amp to build a simple non-inverting audio amplifier for an electret microphone, setting the gain to around 6 or 7.  Note that we are using single-power-supply op amps.

If this lab is too short, then students could feed the output of the amplifier into an analog input of the Arduino and record the waveform at the highest sampling rate they can with the software we provide (probably around 300–500 Hz).  This would again demonstrate aliasing.

EE concepts: op amp, DC bias, bias source with unity-gain amplifier, AC coupling, gain computation.

Lab skills: complicated breadboarding (enough wires to have problems with messy wiring). If we add the Arduino recording, we could get into interesting problems with buffer overrun if their sampling rate is higher than the Arduino’s USB link can handle.

Lab 6: capacitive touch sensor

See posts

  1. Capacitive sensing
  2. Capacitive sensing, part 2
  3. Capacitive sensing with op amps
  4. Capacitive sensing with op amps, continued

The students would build an op-amp oscillator (a square-wave one, not a sine wave) whose frequency is dependent on the parasitic capacitance of a touch plate, which the students can make from Al foil and plastic food wrap. Students would have to measure the frequency of the oscillator with and without the plate being touched.

We can provide a simple Arduino program that is sensitive to changes in the period of the oscillator (see example in Capacitive sensing with op amps, continued) and turns an LED on or off.

EE concepts: frequency-dependent feedback, oscillator, RC time constants, parallel capacitors.

Lab skills: more messy breadboarding.  Frequency measurement.

Lab 7: Phototransistor

See posts

  1. Phototransistor
  2. Synchronous demodulator
  3. Pulse detection with light
  4. Giving up on light-based pulse sensor
  5. Looking at bioengineering measurements courses
  6. Random thoughts on circuits labs

Since optical detection is such an important part of many biomolecular lab techniques, I really want to do something with an LED and phototransistor (or CdS cell or photodiode), but so far none of my ideas have worked out.  I have a nice Fairchild QRE1113 reflectance sensor that uses a matched 940nm wavelength LED and phototransistor, which I’ve used a tachometer for motors for the robotics club. Unfortunately, a tachometer is more appropriate for a mechatronics lab than a biengineering circuits course.

I thought that I might be able to use it to measure arterial pulses by reflection, but I don’t seem to get a signal at my heart rate (I did better with the uncomfortable ear clip).

The reflectance sensor is good for measuring finger tremor if you hold a finger close to (but not touching) the sensor.  The effect is optical, not capacitive coupling, since the signal is stronger if a non-conducting white piece of paper is held near the sensor rather than a finger.  The reflectance sensor is remarkably insensitive to ambient light, though shining a laser pointer on the sensor is easily detected.

We can easily do labs involving interrupting light beams, but there isn’t much “circuit” stuff for the simple ones and not much “bio” stuff either.  We could up the circuit content (perhaps too much) by modulating the light beam and using a synchronous demodulator to detect the beam even in the presence of high ambient light.

I still need to find something that is feasible and somehow related to bioengineering.  This needs more thought.

Lab 8: No idea

I’m still missing a lab.  I’ve not done anything with position, pressure, or volume sensing yet.  Of course, it is possible that some of the earlier labs will take longer than I think, and we’ll need to slip the schedule anyway.  The EKG lab looks pretty packed, so may be some portion of that could be foreshadowed here.  Perhaps bandpass filtering and characterizing a simple filter?  That would be useful, but rather boring.

Maybe an electronic music lab of some sort would be fun here?

Labs 9 and 10: EKG

See posts

  1. EMG and EKG works
  2. Two-stage EKG
  3. EKG recording working
  4. More thoughts on EKG
  5. EKG blinky
  6. Instrumentation amp protoboard
  7. Instrumentation amp protoboard rev2.1
  8. EKG blinky boards arrived

The electrocardiogram will be the final project for the course, and I think it will take two full lab sessions. The first lab session would consist of soldering up the instrumentation amp protoboard, checking for opens and shorts, and designing and characterizing a differential amplifier with an adjustable gain of about 100–1000 (including AC coupling to eliminate problems with DC offset saturating later stages).  The amplifier should have a bandwidth of about 0.01Hz–150Hz.

The second one would be and making a twisted-wire harness with alligator clips to attach to the EKG electrodes, connecting the amplifier to the electrodes, debugging the student-designed EKG amplifiers, and adjusting the gain.  I suspect that a few students will get a design that works in the first week, but that a lot of students will be doing a lot of unsoldering and resoldering as they find bugs in their design, hence the need for 2 weeks in the lab.

Student check out will require that they be able to blink an LED in time with their heart beat, display the EKG waveform on the oscilloscope, and record a minute of EKG signal at 200 samples/second using the Arduino, all without adjusting their board between demos.

EE concepts: biopotentials, instrumentation amplifier, common-mode signal, differential signal, twisted pair wiring, grounding to avoid common-mode signal saturating an instrumentation amplifier, Ac coupling, simple bandpass filtering.

Lab skills: soldering.

Summary

I have a pretty clear idea how I think the lab part of the course should start and how it should end, but there are a couple of weeks just before the end that are still a bit vague.  Perhaps as Steve starts aligning the EE topics with the labs he can identify some topics that need a lab exercise to clarify them.  Maybe some of my blog readers (those who haven’t deserted me during this long process of designing a course) can make some more suggestions—even repeating some old suggestions would not be a bad idea now, as I need a creative kick.


Filed under: Circuits course, Data acquisition Tagged: Arduino, bioengineering, capacitive touch sensor, circuits, course design, ECG, EKG, electret mic, electret microphone, electrocardiogram, electrodes, electronics, multimeter, op amp, oscilloscope, phototransistor, sensors, teaching, thermistor

Accelerometer for circuits course?

One of the people that I asked to look over the course notes and give me suggestions suggested another lab that would likely appeal to bioengineers:

another cheap experiment, accelerometers from Sparkfun to measure gait patterns or detect falls.  If really ambitious, you can teach chaos theory here with analyzing chaos levels in gait patterns—they are different for men and women.

I’ve used accelerometers before, both the analog output ADXL335 and the I2C MQA8452Q. The ADXL335 breakout board was from Adafruit Industries, the MQA8452Q from Sparkfun.  Although I personally prefer the I2C interface, since it takes up only 2 Arduino pins, programming is outside the scope of this class.

This lab sounds like fun, and it would be good for the bioengineers to think of accelerometers as cheap sensors that are easily used, rather than as magic that comes in cell phones, I’m not sure how we would get a circuits lab out of this. Even the analog-output accelerometer just needs to have its XYZ pins connected to analog inputs on the Arduino.  Anything interesting you do with the accelerometer is in either the mechanical mounting or in the software analyzing the data, not in electronic circuits.

We have several constraints in selecting labs for this circuits course:

  • Lab must teach something useful to the students.
  • Lab must seem interesting (or at least useful) to bioengineering students.
  • Lab must not be dangerous (either to students or to equipment).
  • Lab must be doable in one 3-hour lab session (we can afford at most 2 labs that are 2-session labs).
  • Lab cannot require students to be able to program computers.
  • Lab cannot require knowledge of electronics beyond what is taught in the course.
  • Lab should support the teaching of traditional linear circuits.
  • Lab should involve student design and not just analysis of existing designs.

The accelerometer lab fails on two points: any design component would have to be software and there is no support for teaching linear circuits in the lab.  That’s too bad, because it is otherwise a cool lab idea.


Filed under: Accelerometer, Circuits course Tagged: accelerometer, Arduino, bioengineering, circuits, course design

Random thoughts on circuits labs

DNA melting

I spent some time yesterday thinking about whether we could do optical detection of DNA (particularly some variant of the DNA melting lab from MIT—see also the Fall 2008 class handouts).  I noted in the 2008 handouts that they were using a blue LED array driven by a 0.29A current source (made from an LM317T voltage regulator, a rather inefficient method). The wiki page uses a regulated 5V supply and a 25Ω series resistor, which would be around 60–70mA for a typical forward drop of 3.2–3.5V in a blue LED.  That’s still a pretty powerful light source for an LED. They say they are using LZ1-00B200, which has a 3.6V forward voltage, but can handle a full amp of current, so is more LED than is needed.

We can get a blue LED for under $2 that can handle 50mA continuously (LTL911CBKS5), though it has a forward voltage of typically 4.3V.  In surface mount for $1.14, we could get MLEBLU-A1-0000-000T01, which has a dominant wavelength of 465–485nm (depending on bin code) and a luminous flux of 10.7 lm at 150mA (forward voltage 3.2V).  I estimate the LED MIT mentions produces about 6lm at that current.  The expensive part of the illumination is not the LED, but the focusing lenses to concentrate the light and the optical filtering needed to keep the excitation wavelength from being detected by the photodiode.

I was thinking that it would be cool to use a laser as an excitation source, rather than an LED, since then no lenses or filter would be needed on the source—just a blocking filter on the photoreceptor. Unfortunately, blue lasers are very expensive.  What are cheap are the blue-violet lasers at 405nm, since the laser diodes are made in quantity for BluRay players. (Amazon has 405nm laser pointers for under $10 with shipping.) Unfortunately the usual fluorescent dyes used for DNA melting measurements (SYBR Green, LC Green Plus, EvaGreen) are not excited at 405nm, and need excitation wavelengths in the range 440nm–470nm).  I’ve been wondering whether one of the 405nm-sensitive dyes used in flow cytometry (like Sytox Blue dead cell stain) could be used.  But I’ve not found a double-stranded DNA dye for sale that is easily excited at 405nm (even Sytox Blue is way down in sensitivity from its peak), so laser excitation seems to be out—the excitation wavelengths needed for standard dyes require fairly expensive lasers.  The benchtop lasers usually used in labs and flow cytometry equipment are priced in the “if-you-have-to-ask” price range.  Buying enough copies for a student lab is more than this lab is worth.

I still don’t see a way to make the DNA melting curve project work within our course.  Even MIT gives up half a semester to this lab, and we don’t have that much time (nor that caliber of students, on average).

Soldering project

I want the students to learn to solder (at least through-hole parts, not necessarily surface-mount). I don’t want to do the traditional blinky-light soldering practice, so I’ve been looking for a place in the course where it makes sense to require soldering, rather than wiring up a breadboard.

Breadboards have problems with loose wires, so the more complex the circuit, the more problems a breadboard causes.  Breadboards also have problems connecting to wires that have to leave the breadboard—particularly wires to moving objects.  This suggests that the EKG/EMG circuit would be the most appropriate as a soldering project, as it is fairly complicated and the long wires to the Ag/AgCl gel electrodes can cause a lot of problems with loose connections (my first check on debugging is to wiggle the header pins for those wires).

But I want the students to be doing some designing for the EKG circuit, not just soldering up a predetermined circuit, so I’m thinking of designing an instrumentation-amp protoboard, which has an ina126 instrumentation amp and an MCP6002 dual op amp chip, with power pins wired up and a place for the Rgain resistor and bypass capacitors, but everything else in a breadboard-like configuration, so that resistors, capacitors, and jumper wires could be added.   Off-board connections could be done with screw terminals to make sturdy connections.

My son and I came up with the further idea of adding an optional LED output, to make a blinky-light-EKG device.  I think that the approximately 1.5V, 30msec pulse that I was seeing for the R segment of the EKG would be enough to make a visible flash—I’ll have to try it out on my breadboard.  I tried it today, but I was only seeing 0.5V pulses today (poorer contact with the electrodes?), and I had to raise the 3.9kΩ feedback resistor to 10kΩ to increase the gain of the final stage., which was enough to get weak flashes from an LED with a 100Ω series resistor.  Because the op amp has limited output current (±23mA short circuit), I felt it fairly safe to put the LED directly between the op amp output and the Vref signal, which gives a good flash even with a green LED.

The lower voltage that I got this time (until I raised the gain) makes it clear that if I do make an EKG protoboard, it should have room for some trim pots for adjusting the final gain.


Filed under: Circuits course Tagged: Arduino, bioengineering, blinking light, circuits, course design, DNA melting, ECG, EKG, electrocardiogram, instrumentation amplifier, laser, op amp, pulse, violet lasers

More thoughts on EKG

Before doing the EKG lab, we should definitely discuss safety concerns,  including things like the following chart (information from http://electronicstechnician.tpub.com/14086/css/14086_34.htm):

Human reaction at 60Hz Current in mA
 Perception—slight tingling sensation  1.1
 Can’t let go (120 lb. person)—arm and hand muscles close involuntarily  10.0
 Can’t let go (175 lb. person)  16.0
 Can’t breathe—paralysis of the chest muscles  18.0
 Heart fibrillation—rapid irregular contractions of the heart muscles, which could be fatal  65.0

The very small voltages we work with (5–10 V DC) means that we rarely need to be concerned about safety issues in the lab. Most of the resistance of the body comes from the skin, and varies enormously according to how sweaty the skin is. Cleaning dead skin cells off (as is done with most preps for EKG electrodes) reduces the resistance of the skin quite a bit. DC is somewhat safer than AC, because skin is less conducting than the rest of the body, and so acts as a capacitor in parallel with a resistor. Puncturing or scraping the skin reduces resistance considerably.

It would probably be useful to have students measure the resistance between two Ag/AgCl electrodes and compute the currents that would flow at different voltages. When I tried this on two chest electrodes (just after showering, so clean, damp skin) I measured around 50kΩ. Pressing the electrodes more firmly against the skin dropped the resistance to 25 kΩ, and it gradually crept back up.

I keep thinking that the 3-wire design for EKGs is overkill. The 3rd wire seems to be just provided to bias the body to be between the power rails of the instrumentation amplifier. It should be sufficient to bias one of the electrodes with a large resistor to the reference voltage directly, rather than through the body.

I tried this.  First I hooked up the 3-wire system of the 2-stage EKG amplifier (though there was a mistake on that post, as the Rgain resistor was really 4.7kΩ, not 820Ω).  This was to make sure that I was getting good contacts and a clean signal. I then disconnected the bias lead and tried to bias the opposite end of the wires.  This did not work at all.  Disconnecting the bias wire resulted in a large signal with a period of 16.7ms (60Hz, though with a complex waveform).  Adding resistors between Vplus and Vref, Vminus and Vref, or both, just made this noise worse.  I then tried taking my body out of the loop, connecting a 25 kΩ resistor between the clip leads.  Without the biasing resistors I saw the same complex 60Hz signal.  It seems to come from capacitive coupling to the leads, as moving my hand closer or further from the leads changes the magnitude of the signal, and grounding myself eliminates it.  Putting 24kΩ resistors between Vplus and Vref and between Vminus and Vref reduced the noise, but did not eliminate it.  Touching either Vplus or Vminus was enough to produce huge noise again.

I tried another experiment, where I attached the ground electrode not to Vref directly, but through a 0.56 μF capacitor.  This worked fine, even though there was no DC bias connection for the instrumentation amp inputs!  It stopped working if I then touched either the +5V or 0V power rail—the DC bias is important, but my body was working as a pretty good capacitor, holding the DC bias for quite a while.  It is clear that the AC path to ground is crucial also.

I found that I could clean up the EKG signal by putting a 0.56 μF capacitor between Vplus and Vminus—enough that the P part of the EKG was visible.

Clean EMG with P,Q,R,S,T parts of signal all clearly visible. The remaining noise seems to be mainly quantization noise in the Arduino analog-to-digital converter, which could be reduced by increasing the amplifier gain.

Since the remaining noise seemed to be all quantization noise, I upped the amplifier gain.  Trying to raise the gain on the first stage did not work, so I raised the gain on the second stage.

Higher gain EKG circuit, with capacitor on the inputs.  The first-stage gain should be 22.02, and the second stage  18.73, for a total gain of 412.4.

The higher gain amplifier did produce good traces, with less evidence of quantization noise:

The “Arduino units” are 4.967 V/ 1024 = 4.851 mV at the output of the EKG, or 11.76µV at the electrodes. The R peaks are about 3.9mV and the S dips about -0.7mV.  The first R-R interval is 1.368 seconds for a pulse rate of 43.86 bpm.

One thing that is important—the EKG readings are resting EKGs.  If I flex the left pectoral muscle, I can swamp out the EKG signal.

Every EKG is also an EMG (electromyograph), and flexing muscles between the electrodes (here the left pectoral muscle) can swamp out the EKG signal. I computed the electrode voltage from the recorded signal, the measured Arduino A-to-D reference voltage, and the gain of the EKG amplifier. The zero-reference is determined by recording the Vref signal as well as the EKG output signal. The quantization noise from the A-to-D converter is about 3μV (less than 1 pixel in this picture).


Filed under: Circuits course, Data acquisition Tagged: Arduino, bioengineering, circuits, course design, ECG, EKG, electrocardiogram, instrumentation amplifier, op amp, pulse

EKG recording working

My son and I spent some time today debugging his data logger.  I also convinced him to add some documentation, though not nearly as much as I think is needed.  This version is just a text command interface, with no GUI—the PyGUI interface he was building seemed to slow things down a lot, and is not yet ready for use.

The data logger works fine as long as the sampling interval is at least 3msec.  With 2msec sampling, I think that serial communications (over a 115200 baud USB serial connection) is getting overwhelmed.  The Arduino seems to be capable of sending out data ok at 2msec/sample, though 1msec/sample causes it to miss some timer interrupts.

If the Python program can’t empty the serial port fast enough, I think that there operating system problems. My MacBook Pro sometimes gets wedged with long runs at higher sampling rates—I’ve had to reboot it a couple of times today. If the problem is with the MacBook Pro, it may be possible to run with slightly shorter sampling intervals on faster hosts, before hitting the limits of the Arduino.

I did manage to get a nice recording for about 8.5 seconds at 3msec sampling:

Recording of EKG trace on the Arduino. The value 512 represents the midpoint of the Arduino voltage scale. The EKG circuit and Arduino used separate power supplies, so the reference voltage is about 2.506V, while AREF on the Arduino was 4.96V, so the reference voltage should be about 517.  In a separate recording of the EKG signal and Vref, I found Vref to be 515±1.  The arbitrary units are about 4.844mV at the input to Arduino.  If my gain of my EKG is set to 591 as I expect from the resistor values, the arbitrary units should correspond to 8.2µV at the electrodes, and the biggest peak is about +1.6mV and the deepest drop is about -0.24mV.

I think that the signals were clearer today, because I was using a ground electrode on my chest, rather than on my elbow, reducing the common-mode noise a little. The 3msec resolution allows zooming in to get a pretty clear view of the structure of the pulses:

Detail of a couple of pulses showing the QRS complex and the T pulse. I’m not sure whether or not a P pulse is visible—if so it is almost buried in the noise. I’ve added a line where I believe that the reference voltage is, though it was not recorded on this run. The R-R interval here is about 1251±2msec for a pulse of 0.80 Hz or 48.0 bpm, which is about my usual resting pulse.

Although it took my son and me a little debugging to get everything working today, overall I’m quite pleased with the data logger code he wrote. He still has more documentation to add (both in-code and external), and there are some more features that could be added, but it is basically usable as is.

Incidentally, I found out today from Cardiology Explained by E.A. Ashley and J. Niebauer, that

ECG terminology has two meanings for the word “lead”:

  • the cable used to connect an electrode to the ECG recorder
  • the electrical view of the heart obtained from any one combination of electrodes

So it is not surprising that I was confused by the usage—I was only familiar with the first usage, which corresponds to normal engineering terminology.


Filed under: Circuits course, Data acquisition Tagged: Arduino, bioengineering, circuits, course design, ECG, EKG, electrocardiogram, instrumentation amplifier, op amp

Capacitive sensing with op amps, continued

What more can I do (or, more importantly, have the students do with the Capacitive sensing with op amps?

The circuit that I gave in that post has several parameters.  Perhaps the students should try predicting what happens when they are adjusted.

Op amp multivibrator. The first op amp is just to set up a virtual ground halfway between the power rails. The second op amp does the oscillating (at about 8.12 kHz for these components). Circuit drawn with CircuitLab, which is not capable of simulating it.

For example, what happens if Vbias is raised or lowered? What is the effect of changing each of the resistors? How can we optimize the circuit for easy, reliable detection of touches with an Arduino pulseIn() measurement?

If we pretend that the output is a rail-to-rail square wave (ignoring the slew rate limitation), analysis is pretty easy.

.

  • If the output is low, then and Vminus is higher than that, but dropping.
  • If the output is high, then and Vminus is lower than that, but rising.

If we define , we can simplify further and say that Vminus swings between two threshold voltages:   and .

The discharging curve is simply , where , so it takes to discharge to the other threshold.

The charging curve is , and so it takes . That is, .

If we want a symmetric waveform, we need to have , which in turn requires . Raising Vbias makes the low part of the output waveform shorter and the high part longer. Conversely, lowering Vbias makes the low part longer and the high part shorter.

The total period is  .  If we set Vbias to Vdd/2, then we can simplify further to .

The sum R4+R5 only affects the amount of current that the Vbias supply has to provide, but it is probably a good idea to make it fairly large, and to add a bypass capacitor to Vbias, to prevent noise coupling though the bias supply.

When using pulseIn() on the Arduino to measure the capacitance C1, we want to have a large change in the pulse duration (to avoid quantization effects from reporting the duration in μsec), which means a large value for R3. That is limited by the problem of picking up 60Hz noise if the input impedance is too high.

We can also tweak r=R5/R4 a little, to make the period a larger multiple of τ, limited by the problem of noise if we get the thresholds too close to the rails.

Since pulseIn() only measures one part of the waveform (the low part or the high part), we could also tweak the bias voltage to lengthen just that part of the waveform, for example, dropping Vbias to Vdd/4 to length the low part.  We again have to be careful not to get the threshold too close to the rails.  If we are lowering Vbias, then the threshold to watch is . If we fix as low as we’re willing to make it, then should we make Vbias low or r high?  The number we are trying to maximize is the discharge time , with the constraint that . At equality, we have to maximize , which is achieved by making r as large as possible.  Of course, that would mean raising Vbias, which would run us into trouble with noise at the other threshold.  In general, it seems like the symmetric waveform with Vbias=Vdd/2 gives us the best noise margins.

Next step: how do we either slow down the oscillator or clean up the waveform enough to get a good signal to feed into the Arduino?

I tried increasing both R1 and R5, while decreasing R4, as shown below.

Modified circuit for longer period. C1 is just the stray capacitance of the touch sensor, with no deliberately added capacitance.

This circuit oscillates with a frequency of 35.66 kHz (period of about 28 µsec )when the touch sensor is not touched, which is slow enough that the signal runs from rail to rail. Touching the sensor drops the frequency to 20kHz or less (period of 50 µsec or more). Since r=5.556, the expected period is 4.988 τ, or 0.4988 µsec/pF C1.  The period is consistent with a stray capacitance of 56 pF, increasing to over 100 pF when the sensor is touched.  There is a lot of jitter in the lower-frequency signal, probably due to some coupling of 60 Hz noise into the system. A 1nF capacitor for C1 gives a frequency of 1660Hz (602 µsec, which is more than the expected 500 µsec), 47nF gives 34.65 Hz (28.86 msec, not the expected 23.44 msec).  Why am I consistently 25% off?

The change of 20 µsec or more in the period (10 µsec or more in the half period) should be easily detectable with one pulseIn() measurement on the Arduino.  The following code seems to work fairly well, with a light touch causing the LED to flash (right on the edge of detection) and a firmer touch giving a steady reading.

// Capacitive sensor switch
// Thu Jul 12 21:36:42 PDT 2012 Kevin Karplus

// To use, connect the output of the op-amp oscillator to
// pin CAP_PIN on the Arduino.
// The code turns on the LED on pin 13 when a touch is sensed.

// The Arduino measures the width of one LOW pulse on pin CAP_PIN.
// The LED is turned on if the pulse width is more than min_pulse_usec

// pin that oscillator output connected to
#define CAP_PIN (2)

// time (in milliseconds) to wait after a change in state before
// testing input again
#define DEBOUNCE_MSEC (100)

static uint8_t was_on;	// stored state of LED, for detecting transition

static uint16_t min_pulse_usec=5;
// min pulse width (in  microseconds) for detecting a touch

void setup(void)
{
    was_on=0;
    pinMode(CAP_PIN,INPUT);
    pinMode(13, OUTPUT);
    
    // assuming that the touch sensor is not touched when resetting, 
    // find the maximum typical value for untouched sensor
    for (uint8_t i=0; i<10; i++)
    {   long pulse=pulseIn(CAP_PIN,LOW);
        if (pulse>min_pulse_usec)
	{    min_pulse_usec =pulse;
	}
    }
    min_pulse_usec += 2;	// add some room for noise
}

void loop(void)
{
    uint8_t on = pulseIn(CAP_PIN,LOW) >= min_pulse_usec;
    digitalWrite(13, on);
    if (on!=was_on)
    {   delay(DEBOUNCE_MSEC);
        was_on=on;       
    }
}


Filed under: Circuits course Tagged: Arduino, bioengineering, capacitive touch sensor, circuits, course design, op amp, sensors, teaching

Capacitive sensing with op amps

I’m not very happy with the lab exercise in Capacitive sensing.  The basic design questions are good:

  • What capacitance do we add by touching something?
  • What frequency should the oscillator run at without the touch?
  • What % change in frequency can we detect reliably? How will we do that detection?

but I’m not happy with my choice of an LM555 chip for the oscillator.  It is a fine choice for many purposes, and a good chip for students and hobbyists to learn about, but the Fairchild Semiconductor LM 555 data sheet does not do a good job of explaining how the chip works nor exactly what the logic function is for triggering the flip-flop.  As a result, students will probably end up just copying the astable circuit without really understanding it.

I think I would prefer to have them use an op-amp multi-vibrator circuit.  It can’t quite be modeled with only linear op amps, as it relies on clipping of the output to get nearly a square wave.

Op amp multivibrator. The first op amp is just to set up a virtual ground halfway between the power rails. The second op amp does the oscillating (at about 8.12 kHz for these components). Circuit drawn with CircuitLab, which is not capable of simulating it.

The op-amp multivibrator is a simple design.  When the output is high, C1 is charged until V_minus is higher than the positive input of the op amp (about 34.7% of the way from Vbias to Vout=Vdd).  Then the output goes low (taking about 6µsec, limited by the slew rate of the op amp), and the capacitor discharges until it is below the positive input (about 65.3% of the way from Vbias to Vout=0 with these values for R4 and R5). So Vminus swings from (1-0.6526) Vbias = 0.1737 Vdd to Vbias+0.6526(Vdd-Vbias)=0.8263Vdd.  The time it takes to charge or discharge should be about ,  where the time constant τ=R3 C1.  For the values of R4 and R5 here, the charge time should be 1.560 τ, and the period 3.119 τ. With the given values of R3 and C1, this should be a period of 102.9 µsec, or a frequency of 9.7 kHz.   I’m measuring 8.1 kHz, not 9.7 kHz, but I think that the discrepancy is due to the slew rate limitations (which add about 12 µsec to the period) and possibly stray capacitance.  With C1=47 nF, the frequency is 203.6 Hz, when the calculation says it should be 206.7 Hz, well within the accuracy of the components.

Connecting the foil-and-plastic-wrap sensor to Vminus adds a little stray capacitance, dropping the frequency to 8.01 kHz. Touching the sensor drops the frequency to 7.5 kHz–7.7 kHz, adding about 5 µsec–8.5 µsec to the period, consistent with adding about 50pF – 83 pF to C1.  This is a little smaller than the 163 pF that I estimated using the parallel-plate model in Capacitive sensing, but consistent with my measurements using the LM555 circuits.

I can get a much stronger effect if I remove C1 from the circuit, and use only stray capacitance.  The period drops to about 6.2 µsec (roughly 160 kHz), but (because of the slew rate limitations of the op amp) is not full scale and is essentially a triangle wave.  Touching the sensor reduces the frequency to about 35 kHz – 45 kHZ, an increase of 16 µsec – 22 µsec in period, consistent with an additional capacitance of  155 pF – 220 pF, which is about what was predicted by the parallel plate model. I’m a little reluctant to put this signal into an Arduino board, though, as the no-touch signal spends most of its time in the non-digital region between high and low, and only barely crosses the thresholds that would allow the ATMega328 chip to detect the signal.

One interesting idea would be to take advantage of the change in amplitude of the oscillation to make an all-analog touch detector.  I’m afraid that would not be very robust, though, as an increase in the period of only 12 µsec is enough to make the oscillation full scale.


Filed under: Circuits course Tagged: Arduino, bioengineering, capacitive touch sensor, circuits, course design, LM555, op amp, sensors, teaching

Capacitive sensing, part 2

The obvious next step with the capacitive sensor is to make the sensor actually control something.  This is not essential for the circuits class—for that class it is better to have the students viewing the waveform on the oscilloscope and seeing the frequency of the output vary  as the touch varies.  But I was curious about whether the various grounds (oscilloscope, USB cable, wall wart power supply) were making a difference to the capacitive sensing, so I wanted to redo the capacitive sensor to be a fully battery-based application, with no external ground connections.

To display whether the sensor had been touched or not, I turned on or off the LED on pin 13. I used the same software detection mechanism as in the previous post, counting the number of pulses it takes to get a total time for the signal being low. Touching my laptop (to reduce the resistance to ground) no longer makes a difference in the sensitivity of the switch, now that the battery ground is separated from the laptop ground.

// Capacitive sensor switch
// Mon Jul  9 06:05:54 PDT 2012 Kevin Karplus

// To use, connect the output of the LM555 oscillator to
// pin CAP_PIN on the Arduino.
// The code turns on the LED on pin 13 when a touch is sensed.

// The Arduino measures the number and width of LOW pulses on pin 2 until
//    the sum of the pulse width exceeds TOTAL_PULSE_USEC.
// The LED is turned on if the number of pulses is less than NO_TOUCH_NUM

#define CAP_PIN (2)

#define TOTAL_PULSE_USEC (100)	// total of pulse widths (in  microseconds) before reporting
#define NO_TOUCH_NUM (50)

void setup(void)
{
    pinMode(CAP_PIN,INPUT);
    pinMode(13, OUTPUT);
}

void loop(void)
{
    uint32_t pulse_sum=0;
    uint16_t num_pulses=0;
    while (pulse_sum<TOTAL_PULSE_USEC)
    {   pulse_sum += pulseIn(CAP_PIN,LOW);
        num_pulses++;
    }
    digitalWrite(13, (num_pulses<NO_TOUCH_NUM? HIGH:LOW));
}

I had to set the threshold a bit higher than I expected, indicating that the frequency shift was not as large without all the connections to ground, but the sensor still works with a moderately firm touch. With a light touch, the LED flickers on and off, indicating that the frequency shift is near the threshold. Raising NO_TOUCH_NUM too high has the LED always on. Even raising it from 50 to 55 makes the switch too sensitive—the LED turns on when my finger is still 5mm away from contact. Perhaps the ideal setting is 52, as that detects a light touch fairly reliably, but doesn’t fire until my finger is within about 1mm of the surface.

Note: it might make more sense to leave NO_TOUCH_NUM at 50 and adjust TOTAL_PULSE_USEC down to 96, since the larger number can be adjusted more finely.

If I wanted to avoid the flicker, I would debounce the detection.  I can’t use the Arduino Bounce library for this, as the signal that needs debouncing is in software, not on a pin.  It is a trivial matter to add a delay whenever the output changes, though:

// Capacitive sensor switch
// Mon Jul  9 06:44:33 PDT 2012 Kevin Karplus

// To use, connect the output of the LM555 oscillator to
// pin CAP_PIN on the Arduino.
// The code turns on the LED on pin 13 when a touch is sensed.

// The Arduino measures the number and width of LOW pulses on pin 2 until
//    the sum of the pulse width exceeds TOTAL_PULSE_USEC.
// The LED is turned on if the number of pulses is less than NO_TOUCH_NUM.

// pin that LM555 output connected to
#define CAP_PIN (2)

// total of pulse widths (in  microseconds) before reporting
#define TOTAL_PULSE_USEC (96)

// minimum number of pulses to indicate that sensor is not touched
#define NO_TOUCH_NUM (50)

// time (in milliseconds) to wait after a change in state before
// testing input again
#define DEBOUNCE_MSEC (100)

static uint8_t was_on;

void setup(void)
{
    was_on=0;
    pinMode(CAP_PIN,INPUT);
    pinMode(13, OUTPUT);
}

void loop(void)
{
    uint32_t pulse_sum=0;
    uint16_t num_pulses=0;
    while (pulse_sum<TOTAL_PULSE_USEC)
    {   pulse_sum += pulseIn(CAP_PIN,LOW);
        num_pulses++;
    }
    uint8_t on = num_pulses<NO_TOUCH_NUM? 1:0;
    digitalWrite(13, on);
    if (on!=was_on)
    {   delay(DEBOUNCE_MSEC);
        was_on=on;
    }
}

Debouncing does not completely eliminate multiple flashes. If I hold my finger very steady just touching the sensor or my whole hand flat about 1mm away, the LED will flash on and off about 5 times a second (the speed of the flashing is determined mainly by DEBOUNCE_MSEC).

Really good code would not require fixed NO_TOUCH_NUM and TOTAL_PULSE_USEC, but would learn what values are usual for off and on states and set the thresholds to separate them reliably.  I’ve not figured out a good way to do this as unsupervised learning. It would not be very difficult to have initial settings, gather averages for on and off states, then dynamically adjust the threshold, but I don’t know how stable such threshold setting would be. I suspect that it would end up rather unreliable, and highly dependent on good initial settings.


Filed under: Circuits course Tagged: Arduino, bioengineering, capacitive touch sensor, circuits, course design, LM555, sensors, teaching

Capacitive sensing

I decided that it was time to try a new circuits lab today.  Although I have the INA-126 instrumentation amplifier working (with a 220Ω gain resistor for a gain of about 370), and I did get some EKG stick-on electrodes, I don’t feel like trying to debug the EKG lab today.  I could do a little more with the instrumentation amplifier and the new function generator, adding the function generator output to the microphone output to see try to separate the differential gain from the common-mode gain, but I’m getting a bit tired of op-amp and instrumentation amp circuits.  I’ll try to come back to them later.

Other sensor ideas from What sensors for circuits class? that I have the parts for now include phototransistors, LEDs and IR emitters, and reflectance light sensors, but I don’t feel like playing with phototransistors today either.  That leaves one rather do-it-yourself sensor: a capacitance touch switch.  I was thinking of implementing this with LM555 timer chip as an oscillator, detecting capacitance increase as a change in the frequency of the oscillator.

Design questions include

  • What capacitance do we add by touching something?
  • What frequency should the oscillator run at without the touch?
  • What % change in frequency can we detect reliably? How will we do that detection?

Capacitance

Let’s do a first-principles calculation of capacitance of a touch, using a simple parallel-plate model.  Let’s say that the area of the touch, pressing lightly with a finger, is about 1cm^2.  We need to know the dielectric constant of the insulator and its thickness.  Let’s say we use a cheap plastic  wrap from the grocery store.  According to Wikipedia, common plastic wraps are about 0.5 mils (12.5 µm) thick and are now generally a low-density polyethylene (LDPE).  According to Bert Hickman (referring to sites that no longer exist), the relative dielectric constant for LDPE is 2.2, with a breakdown voltage of 3000v/mil (or 1500v for 0.5mil).  Of course, he also claims that the common wrap material is a mix of PVC and PVDC, which seems to be out of date information. The A to Z of Materials site for LDPE claims

Dielectric Strength (MV/m) 27
Dissipation Factor 1kHz 0.0003
Dielectric Constant  1kHz 2.3

That dielectric strength would be 337V at 12.5µm, which seems more reasonable than Bert Hickman’s numbers.

I also have 3M contractor’s plastic for masking large areas when painting. It claims to be 8.9 µm thick, but I can’t figure out what the material is (they just say “high density plastic”).  If it is HDPE (a possibility), the A to Z of Materials site for HDPE claims

Dielectric Strength (MV/m) 22
Dissipation Factor 1kHz 0.0005
Dielectric Constant  1kHz 2.3

which gives the same dielectric constant as LDPE, but the breakdown voltage would be about 195V at 8.9µm—still plenty for a touch sensor.

If I have 1 cm^2 (1E-4 m^2) area, 5 mil thickness (12.5E-6m), relative dielectric constant of 2.3, and ε0=8.8542E-12 F/m, I get a capacitance of 163pF for the touch.

Frequency

The LM555 can be set up as an astable oscillator:

LM555 astable oscillator circuit from the Fairchild Semiconductor LM 555 data sheet.

The data sheet gives the period of the oscillator as and the frequency as . If I want a slow oscillator, I’ll need to use a large resistance.  The largest resistance they show in the data sheet is RA+2RB=10MΩ, and I happen to have some 3.3MΩ resistors, so 9.9MΩ seems reasonable.  If I had no stray capacitance, 163pF and 9.9MΩ would give a period of 1.6msec (620Hz).  But, of course there will be substantial stray capacitance—probably much larger than the touch capacitance.  In any event, the increment to the period of the oscillator by adding the touch capacitance should be about 1.6msec, so we need to be able to detect that small a change in the period.  The percentage change will depend mainly on the stray capacitance.

One thing that is not clear from the LM555 data sheet is what value should be used for C2.  I suspect that it is just a bypass capacitor to reduce noise in the reference voltages used for the threshold, so a 4.7µF ceramic capacitor (of which I have several) should do fine.  Design notes I’ve seen on the web suggest that 0.1µF is plenty, though a bypass on the Vcc input of that amount is also recommended.

Experiment

I set up the circuit on the breadboard, with RA=RB=3.3MΩ, C1 being just the stray capacitance in the circuit, and C2 being a 4.7µF ceramic bypass capacitor. I also put a 4.7µF bypass capacitor between pins 1 and 8, as well as a 470µF electrolytic capacitor, to make sure that the power supply was clean.

The resulting oscillator has a period of about 0.2msec (4.4kHz), but it fluctuated a lot, so that I could not get a clean trace on my oscilloscope. Touching the insulted sensor pad (made from Al foil and Glad Cling Wrap) caused the period to increase enormously, but to a pulse train of 3 pulses that repeated at 60Hz.  I believe that what I was mainly doing was coupling in a 60Hz noise signal, rather than detecting a change in the capacitance to ground.

I could decrease the sensitivity of the circuit to noise by reducing the resistances and adding some more capacitance to C1. Adding 1nF cleans up the signal, but doesn’t eliminate the problem.  I get 107±1Hz without a touch, and 60Hz with a touch.  I’m still mainly coupling in 60Hz noise!  I’d have to reduce the impedance to reduce the 60Hz coupling, reducing RA and RB.

Leaving in the 1nF capacitor and reducing RA and RB to 100kΩ results in a non-touch frequency of 4.05kHz and a touch frequency of 3.6kHz.  This is about a 30µsec difference in period, consistent with an 150pF change in capacitance. But this frequency change seems to be almost independent of the area of contact, which is not consistent with a parallel plate model.  The lower frequency still seems to be modulated by a 60Hz hum.

Removing the 1nF capacitor, but leaving the 100kΩ resistors, I get a no-touch frequency of 140kHz–156kHz (depending on how close my arm comes to the sensor) and a touch frequency around 45kHz–50kHz, a 15µsec difference in the period. A firm press with all my fingers depresses the frequency further, down to about 20kHz. Touching my laptop (reducing my resistance to ground) decreases the frequency further—pressing with my palm and touching the laptop gets the frequency own to about 13kHz.

Here is the complete layout for the capacitive touch sensor, showing (clockwise) the aluminum foil wrapped in Glad Cling Wrap (except for the folded over part where the alligator clip is attached, the breadboard with the LM555 chip, and the Arduino board.

I wouldn’t want to use the interrupt-driven timer code to measure this frequency, but a simple busy-wait loop that times the period could work, or I could add a counter to divide the frequency down (and average out many clock cycles).  But this is supposed to be a circuits class, not a digital design class, so adding a counter is probably not appropriate for the lab.  Perhaps a better approach is to measure the duration of the low part of the pulse, which should be about 1/3 of the total period, using the Arduino pulseIn function.  Looking on the scope, the low part of the pulse seems to be closer on 1/6th of the total period than to 1/3 at the high frequency, though the ratios are more reasonable at the low frequency.  I suspect that there are stray capacitance within the LM555 that account for some of the pulse shape error.

By averaging over 500 pulses, I see a switch from 1.15±0.03 µsec for the low pulse in the no-touch configuration to 5.4±0.3µsec for a firm touch and 2.8±0.2µsec for a light touch (and up to 220µsec for a full-palm touch while touching my laptop). Single pulse measurements may be a bit unreliable at those speeds, since pulseIn only has 1µsec resolution, but adding 500 pulses doesn’t take much time, unless the capacitance is very high. Putting the 1nF capacitor back in the circuit makes the low time look more like 1/3 of the period.  The pulse widths are about 78.4±0.05µsec for no-touch and 80µsec–85µsec for a touch.  Those are long enough to be reliably detected with even a single pulseIn call, but the difference is rather small, so setting a fixed threshold would be a bit risky.

An alternative approach to averaging 100s of pulse widths is to collect pulses until the total pulse width exceeds 200µsec and report the number of pulses collected.  That mechanism results in an easily detected change in counts (from over 150 to under 60) and a response time of about 2–5msec (most of which is probably in the serial communication).  A detection threshold would have to be set for each different sensor plate the circuit is connected to, but that is pretty straightforward.

Here is the code I used for detecting sensor touches with summed pulse widths (click to expand):

// Capacitive sensor timer
// Sun Jul  8 17:59:49 PDT 2012 Kevin Karplus
//
// License: CC-BY-NC http://creativecommons.org/licenses/by-nc/3.0/
//
// To use, connect the output of the LM555 oscillator to
// digital pin 2 on the Arduino.
// On initialization, the Arduino will print "Arduino ready." to serial.
// The Arduino measures the number and width of LOW pulses on pin 2 until
//    the sum of the pulse width exceeds TOTAL_PULSE_TIME.
// It then reports 3 numbers to the serial line:
// The first is the time since the start, in microseconds.
// The second is the number of pulses measured.
// The third is the average duration of the pulses.
// Serial baudrate is 115200.
// The start time may be reset by sending the character 'R'.

#define TOTAL_PULSE_TIME (200)	// total of pulse widths (in  microseconds) before reporting

unsigned long first_time;   // what was the time for the first tick since reset?
// All times are in microseconds.

// do_reset() empties the queue and sents the count to 0
void do_reset(void)
{
    noInterrupts();     // don't take interrupts in the middle of resetting
    first_time=micros();
    // let the user know that the Arduino is ready
    Serial.print(F("\nArduino ready.\n"));
    interrupts();
}

// interrupt handler for data becoming available on the serial input
// Reset if an R is received
void serialEvent(void)
{
    if (Serial.read() == 'R')
    {
        do_reset();
    }
}

void setup(void)
{
    Serial.begin(115200);       // use the fastest serial connection available
    do_reset();
    pinMode(2,INPUT);
}

void loop(void)
{   // keep trying to print out what is in the queue.
    uint32_t pulse_sum=0;
    uint16_t num_pulses=0;
    while (pulse_sum<TOTAL_PULSE_TIME)
    {    pulse_sum += pulseIn(2,LOW);
        num_pulses++;
    }
    uint32_t datum=micros();
    Serial.print(datum - first_time); // time since start (usec)
    Serial.print("\t");
    Serial.print(num_pulses); // number of pulses
    Serial.print("\t");
    Serial.println(pulse_sum*(1.0/num_pulses), 2); // avg pulse duration
}


Filed under: Circuits course Tagged: Arduino, bioengineering, capacitive touch sensor, circuits, course design, LM555, sensors, teaching