# What inputs can I use with my Raspberry Pi? Part 2 - Proportional sensors

DrLucyRogers

This is Part 2 in a series of two articles on inputs. Part 1 is available here.

### Proportional Sensors

Switches and logic-level sensors are easy to use but can only give two discrete states - on and off. Many more sensors produce an electrical output that is proportional to the physical quantity it is sensing. There are sensors available for almost any physical quantity you might care to measure, far too many to cover here, but we’ll try to give some examples as we go along rather than writing a huge list.

### Signal Conditioning

Sensors convert a physical “real-world” quantity (e.g. temperature) into an electrical quantity (e.g. voltage.) Sensors have a large number of different electrical output formats but the more common ones are voltage, current, resistance and frequency. Almost all of these are “analogue” in nature and cannot be directly connected to the Pi without some further steps. To get analogue signals into the Pi, we need an analogue to digital converter (ADC.) ADCs usually need their input signals to be in the form of a voltage within a specific range of values. This means another step is required to convert the sensor’s electrical output into a voltage acceptable to the ADC. This step is called signal conditioning. Signal conditioning circuitry can range from a simple potential divider to high-precision instrumentation amplifiers. What’s more, when measuring “noisy” physical quantities, some degree of filtering is required between the signal conditioning circuit and the ADC to prevent an effect called aliasing, but that’s beyond the scope of this article.

Fortunately, many sensor manufacturers have made our lives easier by integrating the signal conditioning and ADC into the sensor itself. These present a digital output in a number of common formats which are almost all supported by the Pi.

Because signal conditioning and analogue to digital conversion are topics which almost need a whole book to themselves, we will mostly concentrate on these pre-packaged “digital output” sensors in this article. First though, we will make a quick tour of the more common types of “raw” analogue sensors to give a flavour of some of the things you may encounter and briefly mention two ADC solution which can be used with the Pi and the Node-RED programming language.

### Analogue Sensors

#### Potentiometers

One of the simplest types of analogue sensor is a potentiometer (or pot for short.) These should be familiar to anyone who has adjusted the volume knob on a radio. Potentiometers are easy to use because they can be connected to most ADCs with no extra signal conditioning. The can be used as a user-operated control or for measuring the position of slow-moving mechanical parts. They have a movement range of about 270 degrees so are not suitable for things which rotate continuously (for that you need a rotary encoder, see above.) As well as rotary pots, you can get slider pots and other varieties. Pots are specified by their total resistance value (something in the range 5KΩ to 20KΩ is good for general-purpose use.)

As sensors, pots can be thought of as having a voltage or a resistance output depending on how you connect them. If you connect both ends of the track (the outside terminals) to supply and ground, you get voltage output on the centre

(wiper) connection. If you only use the wiper and one end of the track, you get a variable resistance. Note that most pots won’t handle a lot of current, so be careful how you connect them, otherwise the magic smoke will come out.

#### Light Sensors

An LDR (light dependent resistor) is a resistor who’s resistance changes with light level. Other methods of sensing light level include photodiodes and photo-transistors which pass a current that depends on light level.

#### Temperature Sensors

These come in many varieties, the commonest being thermocouples and thermistors. Thermocouples work by the Seebeck effect. By joining together wires made of two different metals, a temperature difference is converted into a voltage difference. The use of thermocouples is beyond the scope of this article but here are some important things to note:

1. There are different types for different applications. They are named with letter codes. You have to connect them together with the right kind of wire or you’ll get errors in the reading.
2. The voltage they make is very small (e.g. a type-K thermocouple has an output of roughly 41 microvolts per ◦C) so the signal needs a lot of amplification before it can be sent to an ADC.
3. The temperature to voltage conversion is non-linear - the number of microvolts per ◦C changes with temperature - so this must be accounted for in software (there are also some hardware solutions.)
4. They only measure a temperature difference, so you need an independent means of measuring the temperature of the “cold junction” and a way of accounting for this in software or hardware. (This is called cold-junction compensation.)

Thermocouples are often used for measuring high temperatures (>100◦C.) For lower temperatures, thermistors are easier to use.

Thermistors are just temperature-dependent resistors. There are two types, PTC and NTC. PTC (positive temperature coefficient) thermistors increase their resistance as the temperature goes up. NTC (negative temperature coefficient) ones do the opposite. You might also come across RTDs (Resistance Thermometry Devices) which are very accurate (and expensive) thermistors. Thermistors generally have a non-linear temperature-resistance response.

The resistance output of a thermistor must be converted to a voltage before it can be applied to an ADC. More on this to follow.

A third kind of temperature sensor makes use of the fact that the voltage across a semiconductor junction will change with temperature. This is amplified to produce a changing voltage (e.g. LM35) or current (e.g. AD590) which has a nice linear relationship to temperature.

Finally, there are temperature sensors with digital outputs but we’ll come on to these in a while.

#### Strain Gauges

A strain gauge is a device for measuring how much a piece of material is stretched. It is made of fine wire bonded to a film which is in turn glued to the material of interest (e.g. part of a metal structure.) As the material stretches, the wire stretches too, causing it to change resistance. Strain gauges form the basis of several other types of sensor, including load cells and pressure sensors.

Load cells measure force. They form the basis of most electronic weighing scales. They usually consist of a block of metal in which special shaped holes have been made so that it bends in a very predictable way when a mechanical load is applied. A special configuration of four strain gauges, called a Wheatstone bridge (or strain bridge) produces a small voltage that changes linearly with applied load. The Wheatstone bridge requires an accurate power source, usually 5V or 10V. The output voltage is very small (e.g. 20mV max) but rides on top of a voltage corresponding to half the supply voltage. This requires a special bit of circuitry called an instrumentation amplifier (or differential amplifier) in order to produce a signal suitable for an ADC.

#### Pressure Sensors

Pressure sensors (often called pressure transducers) measure changes in pressure, either of the air or some other fluid. They are available with pressure ranges of a few millibar up to hundreds of bar (1 bar is 14.5psi and is roughly the same as atmospheric pressure.) They mostly work by using a metal diaphragm between the pressure of interest and a reference pressure. The diaphragm will bend by different amounts depending on the applied pressure. A strain bridge is used to turn this into a small change in voltage. Many pressure transducers have built-in signal conditioning circuitry to turn this into a voltage in the 0-5V range or a current in the 4-20mA range. One thing to note about pressure transducers is that they tend to be almost as sensitive to temperature as they are to pressure, so most incorporate some kind of temperature compensation.

Pressure transducers come in three variants depending on what reference pressure is used: gauge, absolute and differential. Gauge types just measure pressure relative to the air outside their case. Absolute ones contain a sealed vacuum reference so can measure the air pressure itself (this is called barometric measurement.) Finally, differential types have two pressure connections and measure the difference between them. Another important thing to be aware of is media compatibility - for example, not all pressure transducers will withstand getting wet internally.

### Analogue Sensor Output Types

Now we’ve covered some examples of analogue sensors, we can take a further look at their output types and the signal conditioning involved.

#### Voltage Output

Sensors which produce a voltage can be very convenient to use (some can connect directly to an ADC) but others require amplification. Some sensors produce a voltage which is a natural function of their physical action, for example, a thermocouple or a solar panel, and don’t need any external power supply. With others, the ratio of output voltage to supply (or excitation) voltage is proportion to the quantity being measured. These are called ratiometric transducers. Potentiometers and strain bridges are a good example of this. Finally, some transducers have built-in signal conditioning circuits that produce an output (e.g. 0-5V) which is independent of their power supply voltage (within certain limits).

#### Current Output

A huge range of rugged pre-packaged industrial-grade sensors are available (from pressure transducers to infrared thermometers to RPM sensors to ultrasonic position sensors) which have a standard type of output called an industrial current loop or 4-20mA (four to twenty milliamp) output. These sensors cleverly get their power and transmit their output using only a pair of wires. They are designed to operate from a nominal 24V DC supply voltage but will usually work with quite a lot less than this (sometimes less than 15V). The current-loop method is extremely good at rejecting interference and does not suffer from errors due to the resistance of the wiring. Usually, 4mA corresponds to the sensor’s minimum output and 20mA to its full-scale output. To convert the current into a voltage, you just need to apply it to a resistor which is grounded on the other side. For example, applying 4-20mA to a 250Ω resistor will convert it to a 1-5V signal. Be aware that this means you lose up to 5V of “headroom” across the transducer - it will now see a varying supply voltage which depends on the resistance. This is not normally a problem but check the data sheet. Sometimes you might need to use a smaller resistor and amplify the voltage.

#### Resistance Output

Resistance can be converted into voltage in a number of different ways, but a very simple one is to take the sensor and a regular resistor and make them into a potential divider. The output voltage will vary with the resistance of the sensor. You can select the value of the fixed resistor (or use a trim-pot) to produce a sensible voltage change. The voltage will not vary linearly with resistance but this can be dealt with in software (see below.) There are other methods, involving op-amps, which give a linear output but they are beyond the scope of this article. Another option is to make the resistor part of an RC (resistor-capacitor) oscillator and measure the period of the oscillation, which will be a linear function of resistance. This is not so easy on the Pi, at least not using the programming language Node-RED. Another option is to use a microcontroller board, such as an Arduino, to do the period measurement and send the results to the Pi over a serial link.

### Analog To Digital Conversion

ADCs output a digital number which represents the voltage applied at the input. There are several different ways of doing analogue to digital conversion and a huge number of chips available to implement them. Here are a few key properties of an ADC:

Voltage reference. The digital numbers an ADC spits-out are a function of the ratio of the input voltage to the reference voltage (VREF ). The more accurate the reference, the more accurate the result. Most ADCs have a built-in reference, but some don’t. Some (e.g. the one in the Arduino) can use their own power supply as the reference.

Input range. This is the voltage range that the ADC will accept. Often it is from 0V to VREF , or some multiple of it. Some have bi-polar input ranges (usually −VREF to VREF). Exceeding the input voltage range of an ADC can cause it to do strange things or even damage it.

Number of channels. Some ADCs have a built-in multiplexer which allows multiple inputs to be converted (though not usually simultaneously).

Number of bits (resolution). This dictates how small a voltage difference the ADC can discern. The higher the number, the finer the resolution. The ADC will resolve 2B (where B is the number of bits) different voltage “steps” over its input range, e.g. an 8-bit ADC has 256 input “steps”. There is no point paying for more bits than you need. For example, a 12-bit ADC will have 4096 input steps. This corresponds to a resolution of about 0.025%. In order to make good use of this, you need decent signal conditioning circuitry and accurate sensors.

Conversion time/rate. ADCs do not work “continuously” - they sample the input data periodically. Some types of ADC (delta-sigma) are very accurate but slow. Others (flash) are extremely fast but less accurate. In the middle ground are successive approximation (SAR) ADCs which are a good choice for accurate medium-speed applications.

Output interface. ADCs are available with a variety of digital interfaces including parallel (one wire per bit) and serial formats such as SPI and I2C (more on these in a moment.)

Calculating the Input Voltage

The ADC will produce it output as an integer (whole number.) This number will be in the range 0 to 2B − 1 where B is the number of bits of resolution. When using the ADC in an application, we usually want to turn this number back into a voltage. The manufacturer’s datasheet will tell you how to do this. For most ADCs:

where n is the number produced by the ADC and B is the number of bits.

For example, say you have a 10-bit ADC and it’s reference voltage is 3.3 volts. The output number can vary from 0 to 1023. If you get 620 out, this means the input was 2.0V:

In code (javascript in this case) it might look like this:

`// n is the input value from the ADC. const steps = 1023;`
`const Vref = 3.3;`
`var Vin = Vref * n / steps;`

ADCs and the Raspberry PiSadly, the Raspberry Pi does not have a built-in ADC. However, a number of add-on options are available. Node-RED has a node which works with a particular ADC made by Microchip - the MCP3008. This is a 10-bit, 8-channel SAR ADC with SPI (Serial Peripheral Interface) output. This means it can be connected to the Pi with only a few wires.
To save you the trouble of wiring, there are one or two HATs available. For example, the RasPiO Analog Zero board .

Some micocontrollers, like the Arduino’s atmega328, have built-in ADCs. These can be used to read analog voltages on behalf of a Pi, sending their data back by serial link or even an RF link such as Bluetooth or Wifi.

Here are some general properties of analogue sensors that you might come across in data sheets:

• Rating - the maximum value of the physical (input) quantity the sensor can measure.
• FSO (full-scale output) - the output the sensor gives at its rated input.
• Zero offset - the value at the output of the sensor when its input is zero.
• Linearity - how much the input-to-output characteristic deviates from a straight-line graph, expressed as a percentage of FSO.
• Hysteresis - sometimes the input-to-output relationship of the sensor will different depending whether the input is increasing or decreasing. This deviation is expresed as a percentage of FSO.
• Temperature coefficient - how much the zero offset or FSO vary with temperature.
• Supply voltage - this will have a minimum and maximum value.
• Span error - how much the FSO can vary due to manufacturing spread, for example.
• Offset error - how much the zero offset can vary for similar reasons.

### Sensor Data Processing and Calibration

When we read the output of a sensor via an ADC, all we get is a number. We’ve seen how to convert this back to the ADC’s input voltage. We then need to convert this voltage back to a physical quantity before we can do something useful with it. To achieve this, we need to first “undo” the effect of any signal conditioning. We then need to “undo” the effect of the sensor.

Here is an example of what we would put in a Node-RED function node:
Note: if you are not accustomed to maths or coding, the following may be a little daunting. Please feel free to just copy and paste the code into your own projects. You only need to know which bits to change if you are using a different resistor or sensor.

For a thermistor connected to an ADC using some very simple signal conditioning  - just a potential divider. We know a potential divider has this characteristic:

In our circuit, the thermistor is R1. We can re-arrange this equation to find what the thermistor’s resistance is:

In our case, Vin is 3.3, Vout is the voltage fed into the ADC and R2 is 10K. In code, (javascript in this case) this is:

`// Vadc is the voltage from the ADC.`
`// R1 will come out in same units as R2 const R2 = 10e4; // Ohms`
`var R1 = R2 * (3.3/Vadc - 1);`

We’ve “undone” the signal conditioning. Now we need to do the same with the transducer. If we make R1 a 10K NTC thermistor made by Vishay, with part number NTCLE100E3103HB0 (538-0654). The manufacturer’s data sheet gives a scary formula (the “extended Steinhart and Hart” equation) for finding the temperature for a given resistance:

Where R is the resistance in ohms and T is the temperature in Kelvin. To get the values of the coefficients A1, B1, etc, there is a table of values but we need to find the right entry for our thermistor. Ours is the 10K variety (R25 = 10,000Ω). Looking at the “Electrical Data And Ordering Information” table, we find that our thermistor has a “B25/85” value of 3977. We can now look-up this number in the “Parameters for Determining Nominal Resistance Values” table, which, at row number 9, gives the following values:

Rref is the the same as R25, the value of the thermistor at 25◦C, which is 10,000Ω.

Turning this into code:

`// R1 is already set from earlier. `

`const A1 = 3.354016e-03;`
`const B1 = 2.569850e-04;``const C1 = 2.620131e-06;``const D1 = 6.383091e-08;``const Rref = 10e3;`
`var k = R1/Rref; // We make a substitution here to simplify things.`var T = 1.0 / ( A1 + B1*Math.log(k)

`+ C1*Math.pow(Math.log(k),2)`

`+ D1*Math.pow(Math.log(k),3) );`

` var Tc += 273.15 // Turn from Kelvin into degrees C`

Putting this all together with our ADC calculation earlier, we can create Node-RED function node which calculates the temperature from a thermistor connected to the MCP3008:

``````var n=msg.payload;
const steps = 1023;
const Vref = 3.3;
var Vadc = Vref * n / steps;
// Vin is the voltage from the ADC.
// R1 and R2 must be in same units (e.g. K or ohms)
const R2 = 10e3;
var R1 = R2 * (3.3/Vadc - 1);
const A1 = 3.354016e-03;
const B1 = 2.569850e-04; const
C1 = 2.620131e-06;
const D1 = 6.383091e-08;
const Rref = 10e3;
var k = R1/Rref; // We make a substitution here to simplify things.
var T;
if (k > 0) {
T = 1.0 / ( A1 + B1*Math.log(k)
+ C1*Math.pow(Math.log(k),2)
+ D1*Math.pow(Math.log(k),3) );
} else {
// Avoid taking logs of negative numbers
T = 0.0;
}
var Tc = T - 273.15 // Turn from Kelvin into degrees C
return msg;
``````

Many sensors just have a straight-line relationship of voltage to input value so these don’t need such a scary equation as the thermistor. Here’s an example for a pressure sensor that measures 0-25mbar and produces a 1-5V output:

``````const Vmax = 5.0 // Sensor max output of 5V.
const Vmin = 1.0 // Sensor minimum output of 1V.
const span = Vmax - Vmin;
const Pmax = 25.0;
var P = Pmax * (Vadc - Vmin) / span;
``````

Sometimes, you don’t know exactly what the sensor’s output is for a certain input, either because you don’t have the data sheet or because it has a large manufacturing spread in its characteristics or because its characteristics have changed over time. To deal with this, the sensor needs to be calibrated. A known input (e.g. pressure) is applied and the output is accurately measured. This usually needs to be done at a minimum of two data points. The data processing code must then be updated with the new numbers.

Most sensors are calibrated when they are manufactured. Some come with a certificate of calibration to prove this. Others have some sort of automatic calibration routine built in to them. There are companies who will calibrate sensors for you and issue a certificate showing that the calibration can be traced back to national standards. This is usually not cheap but could be necessary if you are using the sensor as part of an important scientific experiment, for example. Calibration is also important if you are using a sensor (e.g. an electronic weighing scales) to measure how much of something you are selling to people

Digital SensorsDigital sensors measure “analogue” real-world values but package up the sensor and all the signal conditioning, filtering and analogue-to-digital conversion in one module or chip, presenting the output in one of a number of common formats. Some of the chips are small and not easy to solder but, for prototyping, break-out boards are available for most devices, either from the manufacturer or from online retailers like RS Components for example!

The Table below gives some examples of digital sensors.

Device Type Interface RS Stock Number
MAX31855K Thermocouple amplifier and ADC SPI
DS18B20 Temperature sensor 1-wire
MCP9808 Temperature sensor I2C
TMP06 Non-contact infrared temperature sensor I2C
MS560702BA03-50 Barometric pressure/ altitude sensor I2C or SPI
BME280 Temperature, pressure and humidity I2C or SPI
CCS811 Air quality sensor I2C
TSL2561 Light level sensor I2C
ADXL345 3-axis accelerometer I2C or SPI
L3GD20H 3-axis gyro I2C or SPI
LSM303 Accelerometer and magentometer (compass) I2C
LSM9DS0 Inertial module (3D accel, gyro, magnetometer) I2C or SPI

Table 1: Some Examples of Digital Sensors

### Digital Sensor Output Types

Digital sensors have a number of different output types. Most of these are directly compatible with the Pi’s GPIO port.

ParallelParallel interfaces are not so common these days but you may occasionally come across them. They are very fast and relatively simple to use but with one downside: parallel interfaces need a lot of wires, one per bit, usually. This means they needs a lot of GPIO pins. In addition to the data lines, there are also hand-shaking lines which coordinate the timing and direction of the data transfer. Although not an input device, a common type of product which still uses a parallel interface is LCD displays.

SPISPI (Serial Peripheral Interface) is a very common standard for transferring data between sensors and a “host” CPU (i.e. the Pi or a microcontroller.)

Generally speaking, SPI uses four wires (excluding ground and power connections):

• SCLK - Serial Clock
• MOSI - Master Out, Slave In
• MISO - Master In, Slave Out
• SS or CS - Slave Select or Chip Select

[Note - the tech industry is starting to address the use of the terms "master" and "slave" - see here]

In SPI parlance, the term “master” refers to the host CPU (in our case the Pi) and “slave” the devices connected to it (e.g. sensors.) SPI is bus system - you can have more than one slave device connected to the master but each needs their own CS signal. The CS is inverting - when high, the slave device keeps its MISO output in a high-impedance (floating) state so others can use the bus. When low, the slave is allowed to transmit onto the bus.

Some properties of SPI:

• It is a serial protocol - data bits are sent one at a time.
• It is synchronous - data bits are sent under control of the SCLK line.
• It is full-duplex - two lines are used for transfer, the MOSI line for sending from master to slave and the MISO line for the reverse. This means master and slave can exchange data simultaneously.
• It is quite fast - most devices with SPI interfaces support clock rates of 4MHz or more, equivalent to 500,000 bytes per second.

The Pi has an SPI interface on the GPIO port and it features two chip select signals, so you can easily connect two SPI devices. It is theoretically possible to use other GPIO pins as extra CS signals, but this will need slightly more effort in software. Most other microcontrollers, like the Arduino, also have SPI built-in, and libraries are available to make it simple to use.

Some things to note about setting up SPI:

• There are two different modes for clock polarity (CPOL=0, CPOL=1) and phase (CPHA=0, CPHA=1). This gives four different modes of setting up the interface. You need to ensure that the master and slave use the same mode.

• Other aspects of the data protocol, such as whether bytes are transmitted MSB (most significant bit) or LSB (least significant bit) first, vary between devices and must be the same on master and slave.

• SPI devices have a maximum specified clock speed. The master should not exceed this or data corruption will occur.

All this (and more) should be specified in the device’s data sheet.

I2CI2C (Inter-Integrated Circuit), like SPI, is a synchronous serial interface bus but it has some major differences:

• It only uses two lines, SCK and SDA, instead of four (excluding power and ground, of course.)
• It is half-duplex - devices can’t transmit and receive at the same time.
• It is slower than SPI (usually 100kHz or 400kHz clock rate.)
• It has a more complex protocol (the details of which are beyond the scope of this article).
• It allows addressing, meaning that many devices can be connected to the bus and you don’t need a chip select line per device.
• More than one master can exist on the bus.
• It is much harder to use than SPI if you have to write all the software yourself, but many libraries exist to make it easy.
• The SCK and SDA lines need pull-up resistors somewhere on the bus.

Like SPI, I2C is commonly included on most microcontrollers. On the Pi, there are two I2C interfaces. One uses pins 3 (SDA1) and 5 (SCL1) of the connector, and is suitable for general use. The other, on pins 27 (ID_SD) and 28 (ID_SC), is generally reserved for the HAT protocol.

Sensors that use I2C include temperature sensors, humidity sensors, pressure sensors - the list is almost endless. To allow use of more than one of the same sensor on an I2C bus, the manufacturer usually provides pins for selecting some of the sensor’s address bits (the rest of the address is fixed and varies between devices and manufacturers.) You need to ensure they are set differently for each device, usually by pulling some to ground and some to the supply rail. The number of available address lines vary between sensors. Some only have one (two of those same devices max on the bus) but some have up to three (allowing up to eight similar devices to be connected.)

UART (or Serial) ProtocolUART stands for Universal Asynchronous Receive Transmitter. UART protocol is, like SPI, a full-duplex serial communications method but it differs in the following respects:

• UART protocol is point-to-point - it is not a bus. A UART interface on a microcontroller (or on the Pi) can generally only talk to a single device (there are ways of overcoming this limitation, such as RS485, but they are beyond the scope of this article.)
• It is asynchronous. This means it doesn’t need a separate clock line. This is both a blessing and a curse. It saves wiring but it means the two devices must be set to the same bit rate (sometimes called the Baud rate) in advance.

The two lines of the serial interface are usually called TXD (transmit data) and RXD (receive data). Be aware that these are named for the direction of data travel (out or in) as it relates to each device. This means that when you connect them together the lines must swap, i.e. the RXD of one goes to the TXD of the other.

The Pi has a UART interface on pins 8 (TXD) and 10 (RXD).

A common type of sensor that uses UART protocol are GPS receivers. Some GPS receiver modules have 3.3V or 5V supplies but use a 1.8V core. This means that a level-converter is needed on the serial lines. Breakout boards are usually available which include the GPS receiver, an antenna and the level converters on a handy PCB.

Some pre-packages sensors use the RS232 UART protocol. This uses high positive and negative voltages instead of normal logic levels. To use one of these sensors with a Pi’s UART pins, you’ll need a special RS232 level converter chip, (though there are various hacks to do this using a few passive components that will work in many cases.)

Another way of connecting serial devices to the Pi is to use a USB serial cable. These come in two variants - TTL (logic level) or RS232 (high level positive/negative signals.) The TTL variant often come in 3.3V or 5V versions - make sure you pick the right one for your application. Many microcontroller boards, like the Arduino, have logic-level UART connections (TXD, RXD) but also have USB serial adapters built in and will conveniently appear as a serial interface (e.g. /dev/ttyACM0) when plugged into the Pi.

### 1-Wire Sensors

There are a range of temperature sensors (and other devices) available which use the “1-Wire” interface invented by Dallas Semiconductor Corp (now part of Maxim Integrated.) The “one” wire carries both data and power. These devices also need a ground connection, of course, as you can’t complete a circuit with only one wire. 1-Wire works a bit like I2C but doesn’t need an extra clock signal and power connection.

Microntrollers don’t have onboard 1-wire interfaces but most can implement the protocol in software, an example of a technique called “bit-banging”. Bit-banging usually requires precise timing so is much harder on operating systems like Linux. If you want to connect 1-Wire sensors to the Pi, the best option is probably to use a I2C to 1-Wire bridge chip, such as the DS2482-100.

### Sensors with Pulse Outputs

Some sensors convey analogue information by changing the rate or timing of the pulses they produce. Examples of this type of sensor are ultrasonic distance measuring devices. The time between the transmitted pulse and the received pulse is proportional to distance. The Pi is generally not so great at doing fast, accurate, pulse timing or pulse counting and this could be another application where it is best to “outsource” the interfacing to a more “bare metal” type of platform like the Arduino which has counter/timers in hardware.

Other examples of pulse-output sensors include tachometers - a sensor which detects rotational speed, we mentioned an example of this under the section on opto switches. Another type of sensor which often has pulse outputs are liquid flow-rate sensors.

### USB Sensors

Some pre-packaged sensors can connect via USB but not all manufacturers offer software or drivers that work with the Pi. Some USB sensors are really just UART-output sensors plus a USB to serial converter. These don’t need special drivers but if the manufacturer does not describe the data protocol, they may still be almost impossible to use with the Pi.

So far, we’ve mainly looked at sensors which connect to the Pi’s GPIO port.

Another class of input devices are audiovisual ones. These include microphones (audio input) and cameras (video input.)

Audio InputsThe Pi doesn’t have an on-board audio interface. HATs are available with suitable audio ADCs but the cheapest solution is to use an external USB sound dongle. These devices usually provide stereo (two channel) audio input and output connection via 3.5mm jacks.

Video InputCapturing video signals (such as composite video or HDMI) requires a lot of CPU horsepower and special interfaces. Generic video capture is not easy on the Pi. There are many cheap (and expensive) USB video capture devices available but few manufactures provide Linux drivers, let alone ones which are compatible with the Pi’s ARM processor.

The Pi does, however, have its own dedicated connector for it’s own range of cameras, and can capture HD video or high-resolution still images.

Types of Pi camera include the NoIR camera. This is missing the infra-red cut filter which is normally fitted to digital camera. This means it can “see” better in low-light conditions. The term NoIR is somewhat confusing - just remember that the “no” refers to the absence of the anti-IR filter, not the infrared light itself. In other words, don’t buy a NoIR camera unless you particularly want to see in the dark. It’ll produce rather washed-out pictures in the daylight.

### Sensors and Inputs Conclusion

In this article we discussed the different types of sensors and input devices available. Digital inputs are relatively simple to connect to the Pi, although some extra electronics may be required.

Analogue sensors require both signal conditioning and an analogue to digital converter.

Digital sensors are increasingly popular and provide an output in one of a variety of common protocols, most of which are well supported by the Pi.

Some sensors and input devices easily be wired to the Pi. For many more there are HATs or other interface boards available.

While it has not been possible to describe in detail how to interface all the different sensors to the Pi, hopefully we have provided enough basic information and terminology that you can start to understand the manufacture’s data sheets and find the rest of what you need on the Internet. There is a thriving Raspberry Pi community - many members publish useful articles, videos and forum posts, so finding what you need should be straight forward.

I am an inventor, engineer, writer and presenter. Other stuff: Royal Academy of Engineering Visiting Professor of Engineering: Creativity and Communication at Brunel University London; Fellow of the Institution of Mechanical Engineers and have a PhD in bubbles; Judge on BBC Robot Wars.