What inputs can I use with my Raspberry Pi? Part 1 - Switches and logic-level sensorsFollow article
This article was written by James Macfarlane and Lucy Rogers
In computing, inputs and outputs are the means by which information can come in or out of the computer. The hardware which makes this possible is called an interface. Some interfaces do just one job (e.g. HDMI - output only) and some are bi-directional (e.g. USB.)
Broadly speaking, things connected to an interface can be classified as input devices (e.g. a keyboard) or output devices (e.g. a monitor.) Most of these devices (or “peripherals”) are designed to allow computers to interact with people. However, in the Internet of Things (IoT) the “things” we are interested in are a much broader category of input and output device. An input device could be a single switch or a light sensor. An output device could be a relay which switches on a motor.
Making your own hardware to work with interfaces like USB or Ethernet is not simple. This is where the Raspberry Pi’s GPIO port comes to the rescue. It allows many kinds of input and output devices to be connected without a lot of complex hardware and software. We’ll address input devices in these articles.
Computers like the Raspberry Piare, of course, electronic devices. This means that if we want a computer to measure or detect physical quantities, such as temperature or light level, we need to convert them into a electrical quantity (such as voltage). This is the job of sensors (also called transducers.) “Smart” devices (such as phones) are full of sensors. This has helped to reduce the price and it is now economically viable to add advanced sensors to your projects.
Our bodies are covered with a network of sensors that detect external stimuli and tell us about the world. Our skin helps us to feel touch and temperature. Our tongue and nose are chemical detectors. Our eyes respond to light, colour and movement, and can judge distance. Our ears pick up sound vibrations. Equilibrioception allows us to work out which way up we are and if we are accelerating. Proprioception lets us know where are limbs are without looking at them.
As well as measuring a huge variety of different physical quantities, sensors are available with a large variety of different electrical output interfaces. Some of these (e.g. I2C) are the same as one of the interfaces available on the Pi, so can be directly connected. Others require extra circuitry (e.g. an analogue to digital converter or ADC) to make the interfaces match. Sometimes this extra circuitry is available to purchase, for example in the form of a Raspberry Pi HAT, sometimes you’ll need to build it yourself.
This article starts with a look at one of the simplest types of input device - a switch - then takes you on a tour of the common types of sensors. Along the way we’ll explain some of the different types of interface that they use and how to connect them to the Pi. We’ll also look at other input devices for the Pi, such as cameras.
By the end of these articles you will have a good understanding of the different types of sensors and inputs devices available and how to connect them to your Raspberry Pi. We have not explored every type of sensor or how to use them, but hopefully we’ll give you enough background knowledge and confidence so that you’ll be able to search online for the information you need to complete your project.
These articles deal with sensors and inputs devices from a hardware viewpoint.
We will divide the world of sensors and other input devices into two:
1. Switches and logic-level sensors - those which produce a purely on/off type of output. These are covered in this article (Part 1)
2. Proportional sensors - those which produce a smoothly changing output. These are covered in Part 2.
Switches and Logic-Level Sensors
In this section we’ll look at switches and other input devices which produce a logic level (on/off) output. They are by far the easiest to connect to the Pi - in most cases they can be connected to a GPIO pin directly or with the help of one or two resistors, and require very little software effort.
The GPIO inputs are a logic-level interface. They use 3.3V logic levels. This means that the voltage you feed into them should either be near 0V (ground), which means you get a logic 0 (low) when you read the pin in software, or near 3.3V, which causes the software to read a logic one (high). The GPIO pins can’t read analogue signals (ones which vary over a range of values.) As you increase the voltage from 0V to 3.3V the value read by your software will suddenly change from 0 or 1. It might flicker between 0 and 1 if you get the input voltage just right (or just wrong!) - for a Pi3, this occurs at around 1.25V.
The voltage threshold where the pin swaps from 0 to 1 is not precisely defined. In fact, it will be slightly different depending on whether the signal is increasing or decreasing, a property known hysteresis (pronounced hiss-ter-ee-siss). This tries to prevent the aforementioned “flickering” that can happen with noisy signals caused by long wires. To be on the safe side, you should probably ensure that anything you want to Pi to consider as a logic 0 is less than 0.8V and anything you would like it to treat as logic 1 is higher than 2.5V. Don’t exceed 3.3V or go below 0V.
Not all devices use 3.3V logic levels. Some use higher (e.g. 5V) or lower (e.g. 1.8V) logic levels - these can’t be connected to the Pi’s inputs without a little extra circuitry called a level translator (more on this soon.)
Connecting a Switch to the Pi
One of the simplest (and most instantly gratifying) input devices you can connect to a Pi is a switch.
Some precautions before we begin:
Protecting the Pi
Don’t apply more than 3.3V to a GPIO pin.
Don’t apply less than 0V to a GPIO pin (i.e. no negative voltages.)
Before you touch any wires connected to a GPIO pin, ensure you earth yourself by touching one of the metal connectors on the Pi.
Take care not to short the 3.3V or 5V supplies to ground or each other.
Make sure any GPIO pins you want to use as inputs are configured as such in software before connecting signals to them. If in doubt, put a 1KΩ resistor in series with the GPIO pin to protect the Pi.
There are many different types of switch available but all work the same at a fundamental level. They consist of two or more metal contacts which either touch or don’t touch depending on the position of a lever. When the contacts are touching (closed) they allow a flow of current. When they are not touching (open) no current flows.
Figure 1: “Hello Word” Circuit
Here (Figure 1) is the “Hello World” of circuits - a battery, a switch and a lamp. (In our up-to-date version, the lamp has been replaced with an LED, complete with its current limiting resistor).
The switch turns the LED on and off. Simple. Can we just substitute a Raspberry Pi GPIO pin for the LED? (Figure 2.)
Figure 2: “This Won’t Work” Circuit
The answer is no. There are two problems with this circuit.
First, the battery voltage could be too high. We’ve drawn a battery with three cells. Depending on the type of battery, that’s 4.5V or more: too high for the Pi’s GPIO pins, which mustn’t be fed more than 3.3V. We could choose a lower voltage source of power, but if we select one with too low a voltage (around 2.2V or less), the Pi’s input pins won’t see it as a logic “one” (high) - it’ll appear as if the switch never turns on. This illustrates the challenge of successfully matching the logic levels without damaging the Pi, particularly when driving the GPIO pins from things connected to external power supplies.
The second problem is that when the switch is open, the GPIO pin becomes unconnected. Just because nothing is connected to the pin, it doesn’t necessarily mean it’ll go to a logic low state. If we want logic 0, we need to physically connect the pin to a low voltage, otherwise it’ll hang around at some random voltage, a state called “floating.” The reason for this is the GPIO pins have a very high impedance. In other words, they don’t present much of a load to applied signals. This means that floating pins are very sensitive to pick-up of electric interference from other nearby signals or from radio transmissions. When read by the software (e.g. Node-RED) the logic level on a floating input will often appear to be a meaningless stream of 0’s and 1’s.
The obvious solution to the first problem, if you haven’t already guessed it, is to use the 3.3V supply already built into the Pi (and made handily available on the GPIO connector.)
To avoid the second problem of floating inputs, we must ensure the GPIO input pin is always connected to a well-defined logic-level, either ground or 3.3V.
Here we show you two ways of solving this - with a changeover switch and with a pull-down resistor. Both work, but the pull-down resistor is usually more convenient:
First is with a changeover (SPDT) switch, as shown in Figure 3. We are also now using the internal 3.3V supply from the Pi. Note that this must be a “break-before-make” type of changeover switch. The “make-before-break” type would briefly short-circuit the Pi’s 3.3V rail when you switch it. Fortunately, the former type are much more common.
Figure 3: Using a changeover switch
There are some disadvantages to this approach, the main one being that not all types of switch are available in a changeover version. Also, the GPIO pin will still briefly “float” when the switch is changed. Finally, we need three wires to the switch instead of two.
The more convenient second solution is to go back to our normal (SPST) switch and use a pull-down resistor. This is just a normal resistor, having a value of a few KΩ to a few hundred KΩ. See Figure 4. The pull-down resistor ensures the GPIO input is “pull-down” to ground (0V) level when the switch is open so it can never float.
Figure 4: Pull-down Resistor
You may be wondering what the other (1K) resistor does in Figure 4. The GPIO pins can either be inputs or outputs, depending on how you program them. Most pins default to being inputs on power-up. However, if you connect the circuit shown in Figure 4 to an output pin, and the output is low, the pin will get shorted to the 3.3V rail when the switch closes. Something similar happens if you have short to ground an output that’s high. This is unlikely to destroy the Pi but will cause a few tens of mA to flow. If in doubt, you can include a current-limit resistor in series with the GPIO pin. A value of 1KΩ should be about right. I (James) measured about 35mA for a short from a high output to ground and about 55mA when shorting a low output to the 3.3V rail (on a Pi3.) This didn’t seem to harm the Pi but a 1KΩ resistor in series with the pin will limit this to 3.3mA and may be a wise precaution.
One problem with mechanical switches is, for a brief period just after the switch is changed, the contacts can “bounce”. In other words, they open and shut very rapidly before coming to rest in their final state. This can cause false readings in software. There are hardware solutions to contact bounce (dedicated “debounce” chips are available) but it is more common to deal with it in software. The general strategy is to set a timer the first time a change is detected and then ignore further changes until a certain time has elapsed. The duration of contact bounce depends on the switch but it is usually of the order of a few milliseconds to a few tens of milliseconds. Figure 5 shows an oscilloscope screenshot of a contact bounce event. The oscilloscope was connected to the GPIO input in a circuit very like Figure 4. This trace was captured when the switch was closed. The squares represent 1.0V vertically and 0.5ms horizontally. You can see that the GPIO input starts low and ends high but the transition from one to the other is marked by about 1.5ms of all kinds of crazy stuff happening.
Figure 5: Contact Bounce
Pull-up Resistors and Open-Collector Outputs
The circuit in Figure 4 gives a logic one (high) when the switch is closed. It is entirely possible to swap the switch and the resistor (which then becomes known as a pull-up resistor) so that it works in the opposite sense: logic zero when the switch is closed. This may not seem like such a natural way of connecting things but sometimes we have no choice. Many sensors that operate in an on-off manner, for example PIR movement detectors, have open-collector outputs. An electronic switch (a transistor) connects the output to ground when the sensor is activated. At other times, it is left open (floating.) This type of arrangement is shown in Figure 6. Note that the sensor and its power supply have to share their ground connection with the Pi. It is important to ensure that the sensor power supply’s ground is only connect connected to the Pi in once place, ideally at the GPIO connector. If they also share a ground some other way (e.g. via the mains earth) then problems can occur. Open-collector switches have the advantage that we control the “high” voltage by deciding what supply to connect the pull-up resistor to.
Figure 6: Open-Collector Outputs
Some sensors have open-collector outputs which work the “other way up” to the one shown above. These switch the output connection to the positive supply of the sensor when activated and are sometimes called PNP outputs. These can’t be directly connected to GPIO pins but we’ll explain how to get around this shortly. It may be helpful to introduce some terminology first.
High-Side, Low-Side and Push-Pull
You’ll see these terms used to describe different kinds of switching methods, especially when the switch is electronic. A high-side switch is one which switches the “output” of the switching circuit to the higher (positive) supply, just like in Figure 4. A low-side switch does the opposite: it switches to the low i.e. ground (0V) side. An open-collector circuit (with a NPN transistor) is an example of a low-side switch. A PNP output is an example of a high-side switch. Some electronic switching circuits can do both and connect the output to either the positive supply or ground, a bit like our changeover switch example from Figure 3. These are called push-pull circuits.
It is very common to encounter sensor devices with 5V logic levels. These can be conveniently powered by the Pi’s 5V rail but their outputs can’t be directly connected to the Pi. Some sort of level conversion is required. You can buy level converter chips but these are best for converting “up”. For inputs, a potential divider can be used. This is the name for a very simple bit of circuitry consisting of a pair of resistors in series, with the bottom connection grounded and the output taken from the centre connection. See Figure 7.
Figure 7: Interfacing 5V Logic-Level Devices to the Pi
The output voltage is given by:
In the circuit shown, this is
(Note: the units (Ω, KΩ, etc.) of the resistors doesn’t matter in this equation,so long as they are consistent.)
Many industrial logic-level sensors (e.g. proximity switches) need a supply voltage much higher than 3.3V or 5V, often in the range 10-30V. Some have open-collector outputs, which just need a pull-up resistor as we’ve seen above. If they have PNP outputs, however, they can’t be connected directly to the Pi’s GPIO pins, as the output will connect to the (rather high) supply voltage when the sensor activates. A potential divider could be used but getting the value of the resistors right can be tricky, especially if the sensor supply voltage can vary a bit (e.g. if it’s powered by a battery.) A better method of level conversion is to use a Zener diode to “clamp” the voltage on the GPIO pin to a safe level (e.g. 3V.) This is show in Figure 8.
Figure 8: Using a Sensor with a PNP Output
Internal Vs External Pull-Up/Down Resistors
The Pi conveniently has built-in pull-up or pull-down resistors which can be selected in software. They are roughly equivalent to a resistance of about 50KΩ. These internal pull resistors are usually sufficient for slow-speed applications where the switch is near to the Pi. For any situation where there is a lot of interference present, for example, in an industrial application, an external pull resistor is definitely recommended.
Some on/off type sensors have a relay output. This is often the case for mains-powered sensors. A relay output provides galvanic isolation ensuring safety and preventing ground loops. The contacts of the relay behave in exactly the same way as a switch so, if connecting them to the Pi, they also require a pull-up/down resistor and debounce code.
One of the characteristics of the open-collector and PNP output circuits shown above is that the sensor power supply must share a ground with the Pi. Sometimes, this is not desirable. One way around this problem is to use an opto-isolator (also known as an optocoupler). An opto-isolator looks like an LED to its input signals. The LED operates a light-sensitive transistor, which, because it doesn’t need to share a ground with anything, can be used to switch on the high side or low side. As an example, we’ve modified the PNP-output of Figure 8 to use an opto-isolator. The result is shown in Figure 9 with the Vishay SFH617A-3. As well as providing isolation, it also acts as a level converter, removing the need for the Zener diode.
There is a bit of consideration involved in choosing the component values for an opto-isolator circuit like that shown, particularly if you want it to cope with a wide range of input voltages, but you can use the circuit in Figure 9 as a starting point. The 1K0 resistor value can be changed to accommodate different input voltages. Calculating this value is just like choosing the resistor for an LED. Choose this resistor to ensure there is at least 5mA (but no more than 60mA) flowing into the opto-isolator’s LED and, if using an input of much more than about 12V, check the power rating of the resistor is high enough.
Figure 9: Using an Opto-Isolator
Be aware that if you want to use an opto-isolator to provide protection from mains voltages, extra precautions are required in the choice of components and the physical design of the equipment which are beyond the scope of this article.
Switches come in a huge variety of different types and sizes. These include slide switches, rocker switches, toggle switches and push-button switches. Most are latching (they stay where they’re put) but some are momentary (they are spring-loaded to return to one position.) Some switches can have more than two positions. Usually these are changeover switches with a centre off position. Rotary switches can have many more than three positions, however, and can be used to select between multiple circuits.
Things get more interesting when we move beyond human-operated switches. Microswitches are designed to be operated by very small movements. Reed switches respond to magnets and can be used to detect when doors are opened, for example. Pressure switches change state when the pressure of a gas or a liquid goes above or below a certain level. Float switches can detect when a tank of liquid becomes full (or empty.) Thermostats are switches which respond to temperature. All these switches use mechanical contacts so they require pull-up or pull-down resistors and debounce.
Other Logic Level Input Devices
Switches are not the only on/off input devices, of course. We’ve already mentioned two in passing: PIR and proximity sensors. Here are some more details on those and a few others.
PIR (Passive Infra-Red) Sensors
PIR sensors detect movement of humans and animals. All objects emit a certain amount of infra-red light depending on their temperature. Because the bodies of mammals are usually warmer than their surroundings, the PIR sensor detects subtle changes in the infra-red light landing on its detector.
Adafruit describe how a PIR works in this tutorial: https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor/how- pirs-work
Inductive Proximity Switches
Inductive proximity switches detect when metallic objects move near to the sensor. They are often used in factories to detect objects on conveyor belts or to detect the movement of metal parts of a machine. They work by generating an alternating magnetic field and detecting how the field is disrupted by nearby objects. They usually have an adjustable detection threshold in the range of few mm to a few tens of mm. Inductive proximity switches usually require a power source in the 12V-24V range and have PNP or open-collector outputs.
These do a similar job to the inductive proximity switches but use a beam of infrared light to detect objects. Opto switches can work in one of two ways: transmissive or reflective. The former detect when an object breaks a beam of light. The latter detect when light gets reflected off an object. Opto switches also come in a huge range of form-factors but these can be classified broadly into board-mounting (PCB mount) devices and industrial devices. The PCB- mounting variety leave most of the electronics up to you. They normally consist of an LED and a photo sensitive transistor in one box and can be wired in almost the same way as you would an opto-isolator. The industrial version usually come in a threaded cylindrical housing with wires pre-attached and have PNP or open-collector outputs. The reflective type will also usually have some means of adjusting the detection threshold.
I (James) recently used a reflective opto switch to detect the speed of rotation of the drive shaft in a truck. A piece of metallic tape was applied to the otherwise dark-coloured metal shaft to ensure the sensor got triggered once per revolution. The pulses were counted by some code on an Arduino using the reciprocal counting technique, which can measure frequencies accurately by timing the period of the pulse as well as counting the number per second. This data was sent over USB to a Pi.
Capacitive Touch Switches
These are a type of switch with no moving parts. They use a special circuit to detect changes in capacitance when you move your fingers near a conductive pad. You can make your own capacitive touch circuits but several integrated circuits are available to do the hard work for you, for example the AT42QT1070from Atmel. Adafruit make a break-out board for this.
Rotary Encoders (Optical Shaft Encoders)
These allow the position of a rotating component (e.g. a control knob or a robot’s wheels) to be determined. Absolute encoders will produce a special binary code (called a Gray code) corresponding to the angle of the shaft e.g. Copal Electronics JT22-320-500. These are generally expensive and not so widely used. By far more common type are incremental encoders e.g. Copal Electronics RES20D-50-201-1 , also called quadrature encoders. These use a slotted wheel that interrupts a pair of opto switches which are spaced half a slot apart. The outputs from the opto switches are usually called ‘A’ and ‘B’. By counting pulses, you can determine how far the shaft has moved. The order of arrival of the pulses (A first or B first) allows the direction of rotation to be determined. Often, a third opto-switch is incorporated which has its own solitary slot in the disk. This allows the 12 o-clock position to be determined and is called the index pulse or ‘I’ output.
Hopefully this has given you a flavour of what can be done with inputs which are only “on” or “off”.
In Part 2 (COMING SOON) we will look at proportional sensors, opening-up an even bigger universe of things to connect to the Pi.