User avatar
Z80 Refugee
Posts: 352
Joined: Sun Feb 09, 2014 1:53 pm

Beginners Guide to Wiring Things to the GPIO

Tue Jun 19, 2018 12:59 pm

(This post was originally part of the first post in my thread about Forth, but I have now split it out so I can refer to it separately.)

WARNING: Hardware is not software. The worst that can happen when mucking about with software is you might corrupt an SD card or something. Generally, if you get software wrong it simply doesn't work. If you get hardware wrong, you can damage or kill your RPi, things can catch fire, and you can electrocute yourself (if you are playing with high voltages). What follows is the MIMIMUM you need to know if you want to wire your own circuits to the RPi - so read it, and until you can follow all of it consider yourself insufficienty knowledgable to be trying this.

There is a solution: instead of wiring your own circuits directly to your RPi, use ready-made HATs (interface cards designed for the RPi). These plug onto the GPIO and provide a range of capabilities: relays for switching lights and motors, motor drivers for controlling the speed and direction of motors, switch interfaces for inputs... usually with screw terminals for wiring up. BEWARE OF SHIELDS/CIRCUITS DESIGNED FOR 5V (ARDUINO). Arduino Shields are not generally directly compatible with RPi (3.3V).



Hardware Interfacing

I am not a coding expert - I'm a hardware expert (hence my interest in Forth rather than Python, C, etc I suppose). My general lack of experience with the software environment meant that I had to research how to do the things I've written up in the Forth article (as much to provide a permanent reminder for myself as for anyone else's benefit). Apart from looking up the specifications, I needed no such research for hardware interfacing: that was my bread and butter for decades. The following is offered specifically for the benefit of hardware newbies.

This is a quick get-you-going guide so that you know what you can do with the RPi GPIO, and must not do so that you do not risk damaging it. If there are any hardware engineers reading this - note that the DC specifications do not appear to be published anywhere but a useful summary of what other engineers have deduced is given here: mosaic-industries.com; further useful info here: blog on scribd.com.

The first thing to note is that the GPIO connections are an array of holes in the RPi PCB which may (or may not) have a pin strip soldered to them. Without the pin strip it is easy to solder flying leads (wires) to the connection points you want to use. However, for general mucking about, it is much simpler to have the pin strip, and then a suitable connector plugs onto the pins.

For convenience, I recommend obtaining the Adafruit Pi T-Cobbler Plus (or the Adafruit Pi T-Cobbler if you have an old RPi A or B model with a 26-pin GPIO) and a small breadboard - the T-Cobbler links the RPi GPIO header to the breadboard, and the breadboard provides an array of sockets into which electronic components can be inserted to make connections without soldering.

The GPIO connector pins have odd numbers down the side furthest from the edge of the PCB (and even numbers down the other), starting with pin 1 where the outline marked on the PCB has a chamfered corner and the solder pad is square (the others are round). The diagrams below show the orientation and pin numbering for the old 26-pin (RPi models A and B) version and the 40-pin version used on all other models.

Some reference material refers to the GPIO signal lines as "BCM" (eg BCM17 instead of GPIO17). In these cases, BCM stands for "Broadcom" (the manufacturer of the system chip used in the RPi), and refers to exactly the same thing. Do not confuse the signal names with the physical pin numbers: for example, the signal called GPIO17 is made available on GPIO connector pin 11.

Note that, on the 40-pin version, all the GPIO signals are available from 2 to 27 inclusive. Note also that many of them can be configured to have alternative special functions, such as serial ports and pulse width modulation (PWM) outputs - but those are way out of the scope of this article, and when/if your experimenting gets that far you will be using other sources of information. Why are the signals all muddled up on the connector? Most likely because it was easier to do that than design the PCB tracks to put them in a logical order. What about GPIO_0 and GPIO_1? These are on the GPIO connector at the "do not use" positions, and are specifically reserved for system use by add-on modules.

NB: The original pre-2013 Rev 1 model A and B RPi's are slightly different from the below. If you have one of these, check the information.


GPIO Location & Pinout.jpg
GPIO Location & Pinout.jpg (110.76 KiB) Viewed 311 times


What you must not do, so as to minimise risk of damage to the GPIO (or the RPi as a whole):
  1. Never wire any pin directly to any other; *
  2. Never use a voltage greater than 3.3V or less than 0V in a circuit connected to an I/O pin; *
  3. Never try to load a pin with more than 16mA (in or out);
  4. Never try to load all pins combined with more than 50mA total (in or out);
  5. Avoid any kind of electrostatic discharge to the connector or the RPi.
* Rules 1 & 2 are not absolutely hard and fast if you are an experienced designer.

Let's see what that means:

Rule 1 is saying that if you deliberately or accidentally wire two outputs together, or an output to 0V or 3.3V, or any pin to 5V, or any of 5V, 3.3V, and 0V together, do not be surprised if something fails permanently because of the overload it could cause. You can wire two or more inputs together (why would you want to?), or an output to one or more inputs (again, rarely if ever necessary). If you did want to wire two I/O pins together, for whatever reason, use a resistor of at least 220 ohms so that if both pins happened to be turned on as outputs with one high and the other low, even by accident, the current flow could not exceed 16mA (see rule 3).

Rule 2 is a consequence of the GPIO circuits inside the RPi system chip operating from a 3.3V power supply voltage. Allowing a voltage less than 0V or greater than 3.3V onto an I/O pin could make the internal circuits become "reverse biased", which may overload them or cause mis-operation resulting in failure. Note that there is also 5V available on the GPIO connector, so be careful what you do. Experienced designers know how to run circuits from higher voltages and prevent them getting back to the GPIO - but the safe thing to do is not to run external circuits from more than 3.3V.

Frequently on this forum I see people proposing to use "shields" (designed for Arduino, which runs from 5V and uses 5V signalling) on their RPi, instead of "HATs" (designed for the 3.3V interface of an RPi). Arduino shields will not work properly with the RPi, and may destroy it, unless you take measures to adapt the interface between the two voltages. Save yourself a lot of trouble and use HATs (or build your own circuit as described below - it's not that difficult, and will give you a greater understanding and appreciation of electronics).

Rule 3 is giving an absolute limit to the current that can flow in any one pin so as not to over-stress the components inside the RPi's system chip. That does not mean each pin can or will drive an external circuit with that much current, you have to consider voltage drop with increasing current to work out the load-line balance point, and also each output can be programmed to have different drive strengths between (nominally) 2mA and 16mA. Broadly speaking, try not to expect more that 8mA to drive low current devices (LEDs, sounders), and if you want more than that (for a lamp, motor, relay, etc) use a buffer circuit (such as a transistor - there are plenty of examples available on-line).

Rule 4 means that, if you have 8mA driving a LED circuit (for example), you can't have more than six of them (or at least no more than six lit up at any one time) - otherwise you need external buffering and probably a separate power supply to run them (not power drawn from the RPi pins). Otherwise, the RPi system chip may well overheat, or at the very least malfunction. With external power, you can exceed this limit when the output pins are sinking current - that means the driven device is powered from 3.3V and the GPIO pin turns it on by going to 0V ("low").

Rule 5 is the general advice given when handling any electronics at all. ICs made since the 1980's have used (and are using) millions of tiny transistors etched onto a small sliver of silicon, with very little insulating gap between them. Walking across a carpet can generate electrostatic charge of thousands of volts, just like rubbing a balloon charges it up enough to stick to a wall. If those volts then discharge into the microelectronics, microscopic sparks can break down the insulating gaps so that they don't insulate so well any more. You can't see anything, and the chip might not fail immediately, but the damage can be dormant until something else stresses it a bit more (such as a slight overload, or age), and then it fails.

But don't panic. All you need to do is make sure you discharge yourself frequently by touching something metal that is connected to earth, such as the central heating system or the sink tap, or a plugged in metal appliance - except that these days houses are being plumbed with plastic pipe and appliances are double-insulated rather than being earthed. The best thing is to invest in an anti-static work mat and wrist strap, but spreading some tin foil to work on (making sure the electronics doesn't come into contact with it when turned on), and rest your hands on to discharge yourself, will do at a pinch.

So, what does this all add up to when it comes to connecting a LED to a GPIO pin?

First of all, even old low-efficiency LEDs will light up quite well on 8mA (not hugely bright, but bright enough to see, and some of the LEDs I have in my parts bins are decades old!). To make sure the information here is accurate, I ran some tests on a batch of modern high-efficiency 3mm LEDs to get some actual figures. These modern LEDs only need 2mA, or 5mA to be quite bright.

For roughly similar brightnesses, red LEDs require about 1.87V @ 2mA, while yellow and green LEDs about 1.95V @ 3mA. That means they need a resistor in series to "soak up" the difference in voltage between the LED voltage and the output voltage of the GPIO pin, otherwise the LED looks like a short-circuit to roughly 1.9V which can easily overload the pin. (Yes, it will probably work if you just fit a LED without a resistor because the GPIO output has internal resistance which will limit the current... but you have been warned: DON'T DO IT!)

What value of resistor? For safety: never less than 100 ohms, but that will end up very bright for a high-efficiency LED. For the voltages and currents suggested above: red 680 ohms; yellow & green 390 ohms*. However, for convenience, anything you happen to have to hand between 330 and 680 ohms will do fine.

* These values are calculated to limit the LED current to roughly as stated when driven from 3.3V. In practice, the GPIO output voltage will be significantly less than 3.3V (and the greater the current, the smaller the voltage). Consequently, even with these values, the LED current will be less expected but it is difficult to say how much less. Whatever, all we need is to see the LED illuminate so it doesn't really matter as long as there is enough current to light the LED but not so much as to damage the GPIO. If it is critical in your application to match LED brightnesses, you will need to experiment with different resistor values.

Blue and white LEDs work in a different way, require 2.6-2.7V, and are very bright even at 2mA. Because their working voltage is very close to the maximum voltage available from the GPIO output, calculating a suitable resistor value is prone to considerable error and more a case of trial than calculation. 150 to 220 ohms might be suitable; don't go lower than 100 ohms (to protect the GPIO pin).

Which way around does the LED go? LEDs come with one lead longer than the other (positive), and/or a flattened edge on the plastic (negative), to tell which way around they should go - but if you have salvaged the LED from somewhere neither of those may be obvious. Look inside the transparent plastic casing at the metal terminals: one is large and the other is small, and the large one is the negative terminal. It doesn't matter which way around you fit the resistor or whether it comes before or after the LED (as long as it is in series with the LED).

Obtaining Parts

Unfortunately the last remaining (UK) High Street electronics supplier (Maplin) has now closed. There remain plenty of mail-order suppliers, or look on eBay and you will find multi-packs containing dozens (or even hundreds) of various-coloured LEDs for very little money. Resistors also. For plugging things together without needing soldering, I recommend a break-out cable (eg Pi T-Cobbler) and a "breadboard" (a socket block) - see text above.

For just one or two components though, it is often possible to salvage parts from other discarded products - particularly LEDs.

Here's a tip: if you have a scrap PC chassis, there are indicator LEDs that can be salvaged and are already on leads with connectors that will fit the GPIO header. They still need a series resistor fitted though, and be careful how you connect them to the GPIO.

What about fitting a switch to a GPIO pin?

It's one thing to take output from a program to light a LED or something, but normally you want input (in the form of sensor information) as well - and the easiest of those is a switch (which may detect the limit of travel for a motor, somebody opening a door, or just be user input). The switch needs a current to flow to detect that the contacts are closed, and which gets interrupted when the contacts are open. The voltage that develops across the open contacts is what the GPIO input detects as a "high" (or "1"), and lack of voltage due to the switch contacts shorting together is detected as a "low" (or "0").

The GPIO pin can be configured (by program) to provide the sense current, so that only a switch is required wired between the pin and 0V. However, if not set up properly, there is a risk that the pin is an output that then gets shorted through the switch to 0V. Therefore the safest thing to do is have the sense current coming directly from the +3.3V supply through a 3300 ohm resistor, and a 330 ohm resistor in series with the GPIO pin.

Note that GPIO_2 and GPIO_3 each have a 1800 ohm resistor pull-up to +3.3V fitted on the RPi PCB, which makes these pins unsuitable for these recommended safe switch circuits. To use GPIO_2 or GPIO_3 for a switch input: connect the switch with 220 ohms in series to 0V only, but avoid using them except as a last resort (they are designated for alternative functions).

Example RPi-safe LED and switch circuits are illustrated below. For LED series resistor values, see text above.


SimpleInterfacing.jpg
SimpleInterfacing.jpg (106.7 KiB) Viewed 311 times


Buffering

Rules 2 & 3 are something of a restriction when it comes to making things happen in the real world (short of lighting a couple of LEDs and making some noises from a piezo sounder). When it comes to simple on/off control of anything really chunky, the most robust way to do it is with a relay (as has been the case in cars for decades, although relay control is now being replaced with high-power electronics). A relay takes an input current and uses it to energise an electromagnet, and the electromagnet makes a set of switch contacts turn on or off (for as long as the input current is flowing). The switch contacts can be just a single "make" contact, or two-way "make and break" contacts, or even multiples of those.

The contacts in a relay are completely isolated from the input current, by virtue of the electromagnet. The contacts act just like you have a physical switch and operate it by hand, and can do anything a switch would do - the only restriction being the maximum current and voltage the contacts are rated for. If you want to switch mains circuits: make absolutely certain the relay is designed to be safe at mains voltages, that the contacts are rated for the current you wish to switch (with extra allowance for inductive loads such as motors), and be very, very careful. If in doubt: DON'T!

Unfortunately, the drive restrictions of the "naked" GPIO outputs aren't really adequate even to drive a relay coil, and need transistor buffering as well as protection from the voltage spikes that occur when an electromagnet is turned off. Relays are typically rated for a 5V or 12V coil voltage (so that is what you will need as your external power supply, and those voltages must be kept away from the GPIO lines).

You can build your own buffer circuit, but it is far easier (and not expensive) to buy a ready-made module for the purpose. Do a web search for "automation phat" and you will find just such a thing - and there are a multitude of other similar modules available with more and better relays etc etc. Beware of modules not specifically intended for the Raspberry Pi: other development systems use different voltages on the signal lines (typically 5V), and may not operate with the RPi's 3.3V logic system (and be potentially damaging).

If you do want to do-it-yourself, there are a couple of options illustrated above. The first uses a high gain NPN transistor or Darlington, and you can take your pick according to how much current you want to drive. The "transistor" could even be a fail-safe integrated driver that protects itself from just about every kind of abuse - if you try to overload it in any way it just limits or shuts down (when an ordinary transistor would end up toast). See below for a few suggestions - there are many alternatives.

Code: Select all

Transistor Type   Max Current   Max Voltage   Comments
---------------   -----------   -----------   --------
ZTX450            1A            45V           Amazing transistor in a very small package, good for about 500mA in this circuit (due to the limited current drive from the GPIO).  Add another 330Ω resistor to another GPIO output to get the full 1A.
MPSA13            500mA         30V           Darlington transistor to do a similar job as the ZTX450
BD679A            4A            80V           Darlington in TO126/TO225 package suitable for heatsinking
VPN10N07          10A           70V           Self-protected driver IC that fits in place of a NPN transistor, available from RS etc.  Drive high-power loads without a relay!
Alternatively, the ULN2803A provides eight 500mA Darlingtons (complete with resistors) in one IC package. Pin 9 is the 0V connection common to all the drivers, and pin 10 has to be taken to the highest voltage present in the external circuit. Don't expect to drive eight loads at 500mA each though! The eight inputs are on pins 1-8, and their corresponding outputs are pins 18-11.

Whether you are using individual transistors or the ULN2803A, outputs can be added up (but only because these are what we call "open collector" designs - don't try to do this with just any circuit). What I mean by that is if you want to switch (for example) 1.5A, it is OK to use two GPIO outputs driving two separate ZTX450 circuits, and then wire the transistors together at their collector terminals to drive just one load. It's even easier with the ULN2803A: one GPIO output can drive all the input pins at once, all of the outputs can be wired together, and then you have (nominally) 4A capability (although 2A is probably more realistic, and only for short periods).

The worst that can happen is the transistor/IC is overloaded and blows, but that is so much better than blowing your RPi! It will get hot first, so if you keep an eye out for that (and mind your fingers) you will know you are expecting too much. Driving the coil of a relay shouldn't be a problem, but motors are more demanding. If the driver gets hot but you are within its current limit specification, you could fit a heat-sink to keep it cooler.

Breadboards are not suitable for connecting high-current circuits, use soldered connections or screw terminals.

Protection Diodes

The example transistor circuit shown above includes a protection diode wired across the transistor, and integrated drivers (including Darlingtons) usually also have protection diodes incorporated. These are sometimes known as "flywheel diodes", although this term is more appropriately applied to a diode in a switch-mode PSU circuit.

At first sight, this diode appears to be redundant, because it is wired to be reverse-biased and therefore apparently always non-conducting. However, this does not account for the effect of a switched current on an inductive load (eg a motor or a relay coil). Inductance is the electrical analogue of momentum. What happens with an inductor is that if you try to cut off the current through it, the magnetic field collapses and in the process induces a voltage across the inductor which tries to maintain the current flow. The sharper the current is cut off from the source, the greater the induced voltage.

The consequence is that the transistor (or whatever is driving the inductor, ie the coil) will be subjected to voltage surges which may exceed its design capability and result in failure, and even risk those surges feeding back into the previous circuitry.

The diode shown turns on if the output of the transistor goes negative (due to ringing on the inductive load). This limits the voltage excursion to about -0.7V (within the capability of the transistor) and soaks up the inductive energy. It is also common to see a reverse-biased diode wired directly across the inductive load (not shown in my diagrams) which stops the main positive voltage surge exceeding the supply voltage + 0.7V, but for small loads such as a relay this is less of a concern.

Darlington arrays such as the ULN2803A have integrated protection diodes to both 0V and the load supply voltage. These are particularly necessary to prevent misoperation that could occur if the substrate of the chip became forward biased due to voltage surges on the output terminals. The common V+ pin is not there to power the IC, it is there as a common point for the protection diodes and must be wired to the highest voltage that powers any of the connected loads.
Military and Automotive Electronics Design Engineer (retired)

For the best service: make your thread title properly descriptive, and put all relevant details in the first post (including links - don't make us search)!

Return to “Interfacing (DSI, CSI, I2C, etc.)”

Who is online

Users browsing this forum: No registered users and 13 guests