Sensors: Bringing Information to the Body Electric
Guest post by G. Andrew Duthie, founder and chief consultant for Devhammer Enterprises
Whether you are a professional engineer, a hobbyist, or maker, when building electronic devices, sensors are an indispensable part of your toolbox. Today, we have an extraordinary variety of sensors to work with, and more become available on a regular basis.
When considering sensors, and what they allow us to accomplish, it may be useful to think about them as an analog of our own senses. We can think of sensors as devices that allow machines to receive input in some of the same ways that we perceive the world around us, through touch, sight, hearing, smell, and more.
How Sensors Work
All sensors operate by taking a source voltage, and using that voltage to power circuitry that can detect some change in the environment. This might be anything from a change in temperature, ambient light, vibration, etc. Depending on what has changed, the sensor then varies an output signal, which can be used by a device to modify its behavior, alert an operator, or most anything you can imagine.
In this article, we will examine a representative set of sensors from the perspective of providing machine senses, and discuss what kind of input each sensor provides. We’ll also cover why a sensor is useful or interesting, and the type of signals the sensor typically uses to communicate with devices. These signals can include simple digital (high/low voltage representing one or zero), analog (voltage varying from 0v to the source voltage), or higher-order protocols, such as i2c, SPI, CAN, etc.).
When shopping for sensors for a given project, one of the decisions you’ll face is whether to buy a bare sensor (or integrated circuit), or a breakout board. A bare sensor can be significantly cheaper, and more compact, and thus more suitable for high-volume production. A breakout board, on the other hand, while usually more expensive, can be much more convenient for prototyping, since it usually provides easy-to-solder connections, and may also include additional components needed for properly powering and reading from the sensor. In this article, we’ll mostly focus on breakout boards and sensor modules.
Sensors Representative of the Sense of Touch
One of the most important senses a human has in interacting with the world is the sense of touch. While machines have not quite caught up with us in this area, there are many sensors that can bring parts of the touch experience to devices. In this category of sensors, we’ll start with the simplest sensor of all…a button.
- The Button: Buttons are so simple that one might make the argument that they’re not sensors at all, but they fit our basic definition. A button at its simplest, is a digital sensor that allows you to open or close a circuit. When the circuit is closed, the device connected to the button reads a voltage equal to the source voltage of the circuit, which equates to a logical value of one. When the circuit is open, the device reads a voltage equal to ground, or a logical zero.
Buttons can be used for a variety of purposes in your device projects, from providing a means for human operators to interact with a device, to providing limit switches on automated equipment. The button may be a humble sensor, but it is enormously flexible, with many configurations of buttons to choose from, including normally open and normally closed, self-latching buttons, and many more.
One important note about wiring up buttons…while in theory a button, when closed, should produce a clean transition from a logical zero to a logical one, most buttons suffer from something called “bouncing” where the signal oscillates from zero to one and back again repeatedly. How often and how long varies a great deal from button to button. As such, button signals often require “debouncing” which can be accomplished either in software or with some additional hardware. You can see a discussion of one potential hardware solution at: https://youtu.be/w7EWIXpEA5c
- Flex and Force Sensors: These both contribute forms of “touch” to a device. Both of these kinds of sensors operate on the basis of resistance.
Flex sensors are thin strips which, when flexed, increase the resistance between the two terminals on the sensor. Because they are thin, and meant to be flexed, it’s a good idea to think carefully about how and where such a sensor would be mounted, to ensure it lasts as long as possible. Flex sensors allow you to have a rough idea of position of moving parts, based on flexing resistance, or to sense when something that shouldn’t flex, does.
Force sensitive resistors, also known as force sensors, work in the opposite direction. That is, as more force is applied to the sensor pad area, the resistance across the sensor contacts decreases. Force sensors come in a variety of shapes and sizes, and can be used to sense pressure. These sensors are great for determining if a pressure is being applied, and they’re inexpensive, but they’re not always very accurate, so they wouldn’t be great for trying to determine how much something weighs. For that, you’d want to use a Load Cell, which is a more expensive and specialized sensor (if you opened up an electronic scale, you’d likely find one or more load cells at its heart).
Both flex and force sensors are easy to wire up, simply requiring an input voltage, and a second resistor to form a voltage divider to give the desired output range, which you’d read on an analog input pin on your microcontroller.
- Capacitive Touch: These sensors are arguably one of the most important sensors to come into widespread use in the last decade, since it is capacitive touch sensors that make it possible for us to interact with smartphones, tablets, and touch-enabled PCs without the need for a stylus.
Capacitive touch, as the name implies, detects touch by the use of changes in the capacitance of an electrode or, as in the case of a touch screen, a grid of electrodes. There are many variations of capacitive touch screens, but they all operate on the same basic principle of measuring changes in capacitance caused by the touch of something conductive, such as your finger.
Capacitive touch sensors work the same way. They are available as integrated circuits or in breakout boards for easier prototyping, and you can wire them up to anything conductive. The interface for these sensors will vary, but one example is the MPR121 Capacitive Touch Sensor Breakout available from SparkFun, which uses I2C for communicating with a microcontroller. In the case of the MPR121 breakout, you’d connect one side of the breakout to your microcontroller’s I2C pins, and connect one or more of the 12 electrode pins to a conductive material of your choice. This gives you great flexibility to add touch input to your project, and the breakout board is quite inexpensive, too.
- Temperature Sensor/Thermocouple: When you were a kid, you may have had to learn the hard way that touching something hot was painful. While we’re not quite at the point where devices can feel the pain of a burn, we do have sensors that can detect heat, and these include thermistors, temperature sensors and thermocouples.
Thermistors are the simplest and cheapest option, and they work by changing resistance in response to changes in temperature. There are two varieties: PTC, or positive thermal coefficient, and NTC, or negative thermal coefficient. The resistance of PTC thermistors increases as temperatures increase, while the resistance of NTC thermistors decreases with increased temperature. Thermistors have a wide range of uses, from the use of PTC thermistors as current limiters for circuit protection, to use in 3D printers for monitoring hot-end temperatures for consistent filament heating.
A downside of thermistors is that they don’t have a linear relationship between temperature and resistance, so it can be difficult to use them to get accurate readings over a range of temperatures without some extra calculations and code. Instead, you could use a simple temperature sensor such as the TMP36, which provides an extremely linear analog output voltage that directly corresponds to the temperature at the sensor. This makes it easy to apply a source voltage and read the temperature by applying a simple scale factor to the output voltage.
Another popular temperature sensor is the DS18B20, which is a waterproof temperature probe, so you can use it in wet environments. The DS18B20 uses a 1-Wire interface, which makes it simple to hook up to a microcontroller.
On the more expensive end of the scale are thermocouples and infrared thermometers. Thermocouples operate by generating a small voltage based on the combining of terminals of two dissimilar metals. By measuring the output of the other ends of these terminals, you can read a wide range of temperatures, and thermocouples can typically read much higher temperatures than the other sensors we’ve looked at in this section. Thermocouples are used in a variety of applications, including in monitoring the pilot light of a gas furnace…if the pilot light goes out, the thermocouple junction cools, and causes the gas valve supplying the pilot light to close. Infrared thermometers are available both as standalone devices (or integrated into some digital multimeters) and as sensors that can be embedded in your device or project. The big advantage of IR thermometers is that they are non-contact sensors. Because of this, you can use them to read the temperature of components or surfaces at a distance.
Sensors that Resemble the Human Sense of Vision
The ability to see carries with it many possibilities, from the simplest of just differentiating between light and dark, to recognizing objects, colors, or patterns. There are sensors that provide many of these abilities to our projects and devices.
- Light Sensors: Like temperature sensors, light sensors come in a variety of shapes, sizes, and prices. The simplest, and most common, is the photocell, sometimes called a photoresistor. Photocells operate by changing their resistance based on the amount of light detected. The higher the intensity of the light, the lower the resistance. So they’re great for sensing whether the lights are on or off in a room, or for changing an incoming signal based on the intensity of the light detected by the sensor. Adafruit.com, another great site for purchasing components for your products, has a nice photocell tutorial you can follow.
Other types of light sensors include ambient light sensors, RGB light sensors, UV sensors, and even more sophisticated sensors such as the APDS-9960 RGB and Gesture sensor sold by SparkFun Electronics, which provides an easy way to include gestures in your device or project.
- Barcode Scanner: This is a specialized sensor that is designed to do one thing really well…pattern recognition. While there are a variety of illumination methods for a barcode scanner, the one most of us are probably familiar with uses a laser to illuminate the barcode. To the naked eye, the laser light appears as a steady bar of light, or a pattern (for example, in a supermarket checkout scanner), but in fact, the laser light is oscillating, either through a moving mirror, or movement in the laser diode itself. As the laser light moves, the reflection from the barcode being scanned is received by a sensor that outputs an analog signal, which is received by a converter, which interprets the incoming analog signal and turns it into a digital signal. This digital signal is then decoded into ASCII text. That text is then sent to the receiving device, by USB, serial, or whatever interface the specific scanner supports.
Many barcode scanners support a USB HID mode, in which the barcode scanner behaves like a USB keyboard, so you can simply scan a barcode and the resulting text will be input as though it was typed on a keyboard. This makes barcode scanners extremely easy to use. But beware…if you’re anything like me, once you try one of these, you’ll probably spend a good bit of time looking for anything nearby with a barcode to scan.
Connecting a barcode scanner to a microcontroller can be done using a USB shield or interface, or by simply switching the barcode scanner into RS-232 (serial) mode, and wiring it up according to the recommendations of the manufacturer. Most handheld barcode scanners helpfully include a sheet of barcodes that make changing the scanner settings as simple as scanning the barcode for the desired setting.
- Camera: Our eyes are our windows on the world, they are one of the primary means by which we interpret the world around us, from recognizing the faces of friends and loved ones, to reading books and signs, to the simple act of finding our way around the room.
Cameras, likewise, can provide devices with variations on the ability to see. When we think of cameras, often we think of the devices we use to take photographs, and indeed, that’s one purpose for cameras as sensors. Where once cameras used specially-treated film, exposed to light and then developed via chemical processes, to make photos, today, CMOS and CCD sensors have become so tiny and ubiquitous that they are in every smartphone made today, as well as in larger digital cameras, with the main difference between them being the optics and lenses used in the larger cameras.
Not limited to the visible spectrum, cameras can do more than simply take static photos. Of course, most digital cameras today, both standalone and those in smartphones, can record video, which has led to a revolution in both entertaining cat videos as well as more serious uses in documenting interactions with police and other officials.
Cameras as sensors can also be used for color recognition, as with the “Cubestormer” robot, which uses LEGO Mindstorms components, including a webcam, to rapidly solve a Rubik’s Cube. The robot, which is now in its third iteration, can solve a random cube in just over 3 seconds. More practical uses for color recognition include sorting of parts in industrial and manufacturing scenarios.
Another use for cameras is facial recognition. With the right software, a camera can use the distance between parts of the face to accurately identify an individual. An ongoing challenge with facial recognition technology, however, is that facial recognition systems that rely purely on 2D imaging may perform poorly in low light, or with varied facial expressions.
As a result, newer facial recognition systems rely on the use of infrared cameras, which combine infrared LEDs for illuminating the subject along with an infrared camera, which can provide improved recognition, even in dark conditions. Additionally, many sensors now include depth sensing, which can provide additional data for facial recognition.
- Going Deep with Sensors: These depth sensors, which have now become small enough to be embedded in mobile devices, can perform functions beyond just facial recognition. They can also be used to map the world around them, for example scanning 3D objects for replication or modification. Depth sensors are at the heart of the XBOX Kinect sensor, which can provide skeletal tracking based on depth data, as well as the Leap Motion sensor, which accurately tracks the position of the user’s fingers, and recognizes gestures.
While many uses of depth sensors are more fanciful than practical, one can easily envision a rescue robot using depth sensors to map a room where potential survivors of a natural disaster might be, and combined with thermal cameras to sense body heat, be able to map a path to the victim or victims.
Interfacing with cameras in your own devices will vary based on the camera you use, but there are cameras for just about any application, including USB webcams, simple serial connected cameras, and Camera Serial Interface, which is used on devices such as the Raspberry Pi.
- Reflectance Sensor: This type of sensor uses an infrared (IR) emitter paired with a photodiode to measure the reflectivity of a surface to IR light. These can be purchased as single sensors, as breakouts, or in arrays of sensors on a single board. One of the main uses for reflectance sensors in the hobbyist arena is to create line-following robots. The reflectance sensors (usually 2 or 3 at a minimum) are mounted low on the front of the robot chassis, and measure the reflectance of the surface on which the robot is driven, which is usually white with a black line for the robot to follow. When the line diverges from the robot’s current path (or vice-versa), the reflectance sensors detect the change in reflectance, and the robot code applies more or less power to the drive wheels to correct the path and follow the line. More sophisticated reflectance sensors are used in manufacturing, and can detect unwanted curvature or provide similar measurements on manufacturing tolerances.
Sensors Similar to the Auditory Sense
People and animals use their sense of hearing for a variety of purposes, from communication to sensing potential threats. With the next set of sensors you can provide similar capabilities to your electronic devices, from capturing audio snippets to detecting approaching objects, or movements.
- Microphone: This is something most people are familiar with, whether having used one themselves, or having seen them in use at concerts, in interviews, or elsewhere. Microphones can also be used to provide devices with the ability to sense the presence of an audio signal, and with some straightforward math and code, even display what that signal looks like. One type of microphone commonly used in electronics is the electret microphone. An electret microphone operates through the use of two plates, one of which acts as a diaphragm, typically made of a permanently charged dielectric material, such as metallized Teflon foil, which outputs a signal when vibrated. You can buy electret mics as bare components, in which case you’ll usually need to wire them into your own amplification circuit or, as with other sensors, as a breakout board that includes some or all of the additional components needed to simplify the use of the sensor.
Use a microphone to detect when someone in a room is speaking, or to analyze and/or display the frequency of a given sound source. Common hobbyist projects include voice changers or blinking LEDs that react to sound sources.
Electret mics will vary in terms of the specific output levels, but most will provide a specific peak-to-peak voltage based around a given operating voltage, also referred to as the bias. For example, this breakout board from Adafruit, which includes all the components needed for amplifying the signal as well as adjustable gain, has a peak-to-peak voltage of 2Vpp, with a bias of 1.25V, making it great for use with microcontrollers operating at 3.3 volts.
- Ultrasonic Range Finder: This is a fairly simple sensor that behaves similarly to echolocation used by bats. The sensor emits an ultra-high frequency pulse of sound (far beyond the range of human hearing), and then measures the time it takes for the reflected sound to return to the sensor. These sensors come in many configurations, some with narrower beam widths (which helps to ensure you’re measuring what you want to measure), and with varying ranges.
Ultrasonic sensors are very simple to use, and are great for measuring distances and detecting objects within a specified proximity. Depending on your sensor, this can be as simple as reading an analog value and applying some simple math.
- Piezo Vibration Sensor: Piezoelectric materials have a very useful property in that they can convert movement or vibration into a small alternating current (or vice-versa). Piezo buzzers, for example, are often used in small electronics where a speaker would be impractically large. If you’ve ever had a wristwatch that had that annoying beeping alarm, that’s a piezo buzzer in action.
Piezoelectronic materials are also used for vibration sensors. Because movement in the material produces a voltage, it’s possible to make a sensor that produces a known voltage range so you can measure the result and decide what to do.
A common hobbyist use for a piezo vibration sensor would be to detect knocks or taps, perhaps to create a reaction time game. These sensors are also used in industrial settings, to monitor manufacturing equipment, for example one use is as a fan flow sensor, where the vibration sensor would trigger an alarm if it no longer detected the vibration from the expected airflow.
To use a vibration sensor, you can simply connect it to ground and an analog input pin on your microcontroller (depending on the expected voltage range of the sensor, you might also want to add a resistor to ensure the levels fall within the range your microcontroller expects).
Sensor Counterparts for the Human Sense of Balance
The human sense of balance is pretty complex, but one of the important aspects is the vestibular system, which is based on the movement of fluid within the inner ear. When this fluid moves, it provides information to the brain on the direction we’re moving, and the speed at which we’re moving (more specifically, the direction and speed of the head, since that’s where the ears are). This information is combined with visual cues and other information to help us stay upright. We can bring some of the same sensing to devices using accelerometers, gyros, and IMUs.
- Accelerometers: These measure either static forces, such as the pull of gravity, or dynamic forces, such as from vibration or impact along single or multiple axes. Gyros are similar, but measure angular velocity, and are not affected by gravity. IMUs typically combine an accelerometer and a gyro on a single board or chip, to provide a much more accurate picture of orientation and movement than either sensor can provide separately.
Accelerometers can be used for many purposes, such as measuring acceleration in vehicles, monitoring machinery for vibration that may indicate impending failures, pedometers such as those found in popular fitness trackers, and more.
- Gyroscopes: Often abbreviated as gyros, these sensors are used in radio control helicopters, anti-shake circuitry in cameras, and video game controllers, to name a few uses.
- Inertial Measurement Units (IMUs): These are found in robotics and drone aircraft, where the rapid measurement and correction for changes in attitude and position are extremely important.
Like many of the sensors we’ve discussed, accelerometers, gyros, and IMUs come in a variety of packages, with many different signal interfaces, including analog, serial, I2C, and SPI. Note that IMUs, due to their more sophisticated nature, will typically use a higher-level protocol such as I2C or SPI for communication, rather than simple analog signals.
Sensors that Smell
Without our sense of smell, humanity might not have lasted long enough to invent electronics and sensors. For example, our sense of smell can give us important clues about what’s good to eat, and what’s spoiled. Specialized sensors can allow devices to perform similar tasks, by looking for the presence of specific gases in the air.
Gas Sensor: An electronic gas sensor detects the presence of the target gas (sensors are available for alcohol, methane, LPG, hydrogen, and other gases) through the chemical reaction of the sensor material (for example, tin dioxide for a hydrogen sensor) in which the presence of the target gas results in lower resistance across the sensor terminals.
These sensors are very useful in environments where hazardous gases might be present, and can be used to raise an alarm when harmful levels of a gas such as methane or LPG are detected. Since the sensors are resistive in nature, using them is as easy as connecting them to an analog pin on a microcontroller (some sensors may also require a resistor in-line with the analog connection).
Speciality Sensors Designed for Security, Identifcation, and Monitoring Applications
While most of the sensors discussed so far are analogous to one or more human senses, there are also many sensors that perform tasks outside of the normal range of human senses. These specialty sensors can be used for security and identification, for health monitoring, and more.
- RFID Reader: RFID (short for Radio Frequency Identification) use active or passive technology to read values from an RFID tag. Passive RFID tags must be used in close proximity to the RFID reader, as they use the energy of the reader to activate their circuit and send the data embedded in the tag. Active RFID devices include their own power supply and can operate over longer distances.
RFID is used for security purposes, such as in keycards for building access as well as keyless ignition systems in cars, for inventory tracking and management, as well as for automatic toll collection. NFC (near-field communication) is a newer subset of RFID designed for communication over very short distances, which helps reduce the possibility of third-party interception of NFC tag data, or inadvertent activation of NFC devices. NFC is used in many modern smartphones for automatically beginning the pairing process with devices such as external Bluetooth speakers
The signal you get from a given RFID reader will vary, but one example, the USB RFID reader included with the SparkFun RFID Starter Kit, communicates via serial, making it very easy to use with either a PC or a microcontroller.
- Fingerprint Reader: This is typically used for identification and/or access control. Fingerprint readers require that anyone who will use them go through a process called enrollment, in which one or more fingers are scanned or imaged, and the resulting data stored by the fingerprint reader. When a user wishes to access the resource controller by the fingerprint reader, they scan or press their finger against the imaging pad, and the reader compares the fingerprint to the stored data, and determines whether it is a match. Some readers provide a distinction between identification (who is the person with this fingerprint?) and verification (does this fingerprint match who the person is claiming to be?).
Fingerprint readers are used in laptops for easier logins, and more recently have shown up in smartphones, including newer iPhones. They provide a convenient means of accessing restricted resources without having to remember complex passwords.
Because of the complexity of storing, comparing, and validating fingerprints, fingerprint readers are among the more complicated sensors in this article. But you can get fingerprint reader modules that are very easy to use, and which communicate over a simple serial protocol.
- Heart Rate Sensor: One of the recent trends in the use of sensor technology is having more and more sensors embedded in wearable devices, to assist in tracking and improving our health. We already discussed the use of accelerometers in fitness trackers, but another important sensor that is increasingly showing up in wearables is a heart rate sensor.
Not long ago, most sports heart rate monitors required wearing an uncomfortable chest strap with electrodes that measured the electrical impulses from the beating heart. While these are still in widespread use, newer types have become available that use light sensors to detect variations in the capillaries of the skin, and determine the heart rate from that information.
For hobbyists, the strap type of heart rate sensor is the easiest to use. You can purchase a kit that includes a chest strap, along with a breakout board for a receiver coded to the strap. The breakout board simply toggles an output pin each time a heartbeat is detected, so it is as simple to use as a button.
- Muscle Sensor: This sensor operates in similar fashion to a strap-type heart rate monitor in that it uses electrodes attached to the skin to detect electrical activity related to muscle activation. One available muscle sensor makes this very simple for microcontroller use by providing an output signal tailored to an analog input. You just connect the electrodes to the target muscle, and the sensor detects the level of muscle activity in the target muscle.
You could use a muscle sensor in cosplay, for example to control parts of a robot costume, or for remote control of actuators or servos. You could also use it to sense a person’s relaxation or tension by using multiple sensors.
Again, the signal provided by the sensor will vary depending on the one you use, but the sensor described above provides a simple analog output, making it simple to use. The signal varies in proportion to the amount of muscle activity detected, allowing a range of control using the output of the sensor or, if you configured your code with a threshold value, simple on/off control of a circuit or device.
- Brain Scanner: Consumer-grade brain scanners, such as the Mindwave line by NeuroSky, use sensors to measure EEG brain activity using a sensor that rests against the forehead. The sensor includes its own processing circuitry that calculates so-called “attention” and “meditation” values that you can use in your devices for display or control. It’s important to note that medical EEGs use many more electrodes to measure brain activity, so you should not expect great accuracy from sensors such as these. But they’re also relatively affordable, with prices around $100 for a Bluetooth-enabled headset that can transmit data to a smartphone, PC, or (with an appropriate Bluetooth breakout board) a microcontroller.
Potential uses for a brain scanner would be training yourself to more easily enter focused or meditative states, or show off for your friends by turning devices on with just the power of your mind.
NeuroSky’s headsets can be used with their developer tools, which provide an API for creating apps for Windows, Mac, or PC, and with microcontrollers via serial over Bluetooth.
In this article, you’ve seen a wide array of sensors, each of which plays its own part in helping electronic devices and projects gain information about the world around them. Whether it’s sensing touch or force, detecting gases, or seeing the world through infrared, sensors are an incredibly important part of any electronic project.
Of course, now that we’ve got all these sensors to work with, we’re going to be generating a lot of data. That data needs to go somewhere, but we’ll leave that for a future article.
About the Author: Andrew Duthie, aka devhammer, is the founder and chief consultant for Devhammer Enterprises. Andrew is a consultant focused on helping clients meet their business goals through software. Andrew is also a trainer and writer with more than 15 years of industry experience, including nearly 10 years as a Technical Evangelist for Microsoft’s Mid-Atlantic States district, where he provided support and education for developers working with the Microsoft development platform. In addition to his work with Microsoft, Andrew is the author of several books on ASP.NET and web development, and has spoken at numerous industry conferences from VSLive! and ASP.NET Connections, to Microsoft’s Professional Developer Conference (PDC) and Tech-Ed.