Reader small image

You're reading from  Practical Python Programming for IoT

Product typeBook
Published inNov 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838982461
Edition1st Edition
Languages
Right arrow
Electronics 101 for the Software Engineer

So far in this book, we've focused mostly on software. In this chapter, we're about to flip that and focus on electronics. We'll do this by learning about the fundamental electronic concepts that are the basis for interfacing basic electronic sensors and actuators with your Raspberry Pi. What we'll learn about in this chapter will provide the foundation for many of the circuits we'll discuss in Section 3IoT Playground.

We will begin by covering the essential workshop tools that you will require for working with electronics, and provide practical tips to help you purchase electronic components. Next, we'll provide you with guidelines to help keep your Raspberry Pi from being damaged as you work with its physical GPIO pins. We will also discuss common ways electronic components fail to help...

Technical requirements

To perform the exercises in this chapter, you will need the following:

  • Raspberry Pi 4 Model B
  • Raspbian OS Buster (with a desktop and recommended software)
  • Minimum Python version 3.5

These requirements are what the code examples in this book are based on. The code examples should work without the need to modify a Raspberry Pi 3 Model B or use a different version of Raspbian OS, as long as your Python version is 3.5 or higher.

You can find this chapter's source code in the chapter06 folder in this book's GitHub repository: https://github.com/PacktPublishing/Practical-Python-Programming-for-IoT.

You will need to execute the following commands in a Terminal to set up a virtual environment and install the Python libraries required for this chapter:

$ cd chapter06              # Change into this chapter's folder
$ python3 -m venv venv # Create Python Virtual Environment
$ source venv/bin/activate # Activate Python Virtual Environment...

Fitting out your workshop

Having the right tools and equipment is important to help you put together, build, test, and diagnose problems in electronic circuits. Here are the bare essentials (besides electronic components) you're going to need as you journey deeper into electronics and create circuits like the ones shown in this book:

  • Soldering iron: You will need a soldering iron (and solder) for odd jobs such as joining header pins to breakout boards or soldering wires to components so that they can be plugged into your breadboard.
  • Solder: Look for a general-purpose 60/40 (60% tin and 40% lead) resin core solder with a diameter of around 0.5 mm to 0.7 mm.
  • Solder Sucker/Vacuum: We all make mistakes, so this device helps you remove solder from a joint and undo your soldering work.
  • Wet Sponge or Rag: Always keep your soldering iron tip clean by removing built-up solder – a clean tip promotes clean soldering.
  • Wire Stripper and Cutters: Keep a set of wire cutters and...

Buying electronic modules and components

A catalogue of all the components and modules used throughout this book is contained in the Appendix. In this section, I want to provide a few general tips and guidelines to help you out when purchasing electronic components in case you have not done much of this before. We will start with a few tips to help you when purchasing loose components.

Purchasing lose components

When it comes to purchasing loose components such as resistors, LEDs, push buttons, transistors, diodes, and other components (which we will be exploring in Section 3IoT Playground – Practical Examples to Interact with the Physical World, of this book), there are some guidelines that will help you out, as follows:

  • Source the specific component values and part numbers listed in the Appendix. Purchase many spares since it's possible that you will damage components while learning to use them.
  • If you're purchasing from sites such as eBay or Banggood, carefully review the details of the item, and preferably zoom in on the images of the parts and check the part numbers shown. Never rely solely on the title of the listing. Many sellers add a variety of terms to their titles for search optimization purposes that do not necessarily relate to the actual item being sold.
  • Search around sites such as eBay and Banggood for terms such as...

Purchasing open source hardware modules

I'm sure you are aware of open source software, but there is also open source hardware. This is where the maker of some electronic hardware publishes the design and schematics publicly so that anyone can make (and sell) the hardware. You will find many breakout modules (such as the ADS1115 modules we used in Chapter 5, Connecting Your Raspberry Pi to the Physical World) from various vendors with different (or no) branding. Different vendors may also make their modules in different colors and, while less common, different physical layouts.

The core or heart of a module particularly the more simple ones is often a single integrated circuit (IC or chip). As long as the core IC and I/O pins are similar, it's generally safe to assume that boards will operate the same way.

SparkFun (https://www.sparkfun.com/) and Adafruit (http://adafruit.com/) are two companies producing open source hardware that many others clone...

Keeping your Raspberry Pi safe

In this section, we will cover guidelines and suggestions to help keep your Raspberry Pi safe while you are interfacing electronics with it. By being careful and diligent in your approach, these guidelines will help you minimize any potential for damage to your Raspberry Pi or electronics components.

Don't worry if some of the electronic-orientated points such as voltages and currents do not make sense at the moment. We'll be touching on these concepts throughout this chapter, and during Section 3IoT Playground – Practical Examples to Interact with the Physical World, of this book, so more context will be coming:

  • Never apply more than 3.3 volts to any input GPIO pin. Higher voltages can cause damage.
  • Never use more than 8 mA from any single output GPIO pin (they can handle up to ~16 mA, but by default, stick to 8 mA to ensure reliable GPIO operation). As a rule of thumb, do not power anything other than LEDs and breakout...

Three ways electronic components fail

Working with electronics is different from software. In the software world, we can change code, break code, debug code, and fix code as many times as we want with no real harm. We can also freely back up and restore states and data. When working with electronics, we do not have this luxury. We're in the physical world, and if something gets damaged, it's final!

Components and circuits made of components, including a Raspberry Pi, can become damaged and fail in many different ways due to them being connected incorrectly, oversupplying too much voltage, supplying or sourcing too much current, overheating, and even mishandling delegate components to the point that they physically break or are damaged by static electricity from your body.

When a component fails, it can fail in a few different ways:

  • It fails in a puff of smoke, melts, or otherwise displays a physical sign that it has been damaged.
  • It fails silently, with no visual indication...

Electronics interfacing principles for GPIO control

While this book is not a book on electronic theory, there are a few core principles that are important to have an appreciation for because they impact circuit design and how they interface with your Raspberry Pi. The goal of this section is to present you with a basic understanding of why circuits are designed in certain ways and how this relates to GPIO interfacing. Armed with this basic knowledge, I hope it provides you with the incentive to explore the core ideas and principles in more depth. You'll find suggested resources in the Further reading section, at the end of this chapter.

We will start our coverage of electronic principles with what is arguably two of the most fundamental electrical principles of them all  Ohm's Law and power.

Ohm's Law and power

Ohm's Law is a fundamental electronics principle that explains how voltage, resistance, and current relate to each other. Together with the principle of power, these are core underlying principles that explain why certain value components are chosen in circuits.

Ohm's Law is expressed as the following equation:

Here, V is voltage measured in volts, I (capital i) is the current measured in amps, and R is resistance measured in Ohms, commonly prefixed with Ω, the Greek symbol for Omega.

On the other hand, power is expressed as the following equation:

Here, P is power measured in Watts, I (capital i) is the current measured in amps (same as in Ohm's Law), and R is resistance measured in Ohms (same as in Ohm's Law).

The take-home principle regarding these equations is that you cannot change a single parameter in an electronic circuit without affecting another. This means that components are selected...

Kirchhoff's circuit laws

Kirchhoff's voltage and current laws are two laws that circuits abide by. They are two laws essential to electrical engineering, and are stated as follows:

  • The algebraic sum of all voltages in a loop must equal zero.
  • The algebraic sum of all currents entering and exiting a node must equal zero.

That's about as deep as we're going to go on these laws. I have mentioned these laws here because the voltage law is the one we will see in action in the next section, when we calculate why we've been using a 200 Ohm resistor in earlier chapters for our LED circuits.

With that, we have covered briefly three important electrical principles or laws – Ohm's Law, power, and Kirchhoff's circuit laws. It's now time to put these principles into practice. We will do this with an exercise to work out why we have been using a 200Ω series resistor in our LED circuits.

Why are we using a 200 Ohm resistor for the LED circuit?

So far in this book, our electronics have mostly evolved around LEDs. I have done this for good reason. LEDs (and resistors) are easy to use components and provide the basic building blocks for learning about concepts such as Ohm's Law, power, and Kirchhoff's voltage law. Master the basics of LED circuits and the calculations that lie behind them and you will be well on your way to undertaking more complex components and circuits.

Let's go a little deeper with our LED and explore its data properties and see the application of Ohm's Law, power, and Kirchhoff's voltage law. Through a series of examples, we will work through a process to explain why the LED circuits you've seen previously in this book are using a 200 Ohm resistor.

The following is a basic LED circuit, similar to what we have been using so far in this book. If you need a refresher on this circuit, please revisit Chapter 2Getting...

Calculating the resistor value

In the preceding circuit diagram, we have the following parameters:

  • Supply voltage of 3.3 volts
  • LED typical forward voltage of 2.1 volts
  • LED current of 20 mA (test condition for mA is mentioned in the datasheet for voltage drops)

Here is the process to calculate the resistor value:

  1. Our resistor (labelled R1) needs to drop 1.2 volts, which is a simple application of Kirchhoff's voltage law that we mentioned briefly previously; that is, The algebraic sum of all voltages in a loop must equal zero. So, if our source voltage is +3.3 volts and the LED drops 2.1 volts, then the resistor must drop 1.2 volts. This means we get the following equation:

+3.3V + -2.1V + -1.2V = 0V

  1. We can arrange Ohm's Law algebraically so that we get the following:

  1. Using this formula, we calculate our resistor's value:

= 60Ω (hence, resistor R1 in the preceding circuit is 60Ω)

But this is not 200Ω. Our example so far is a simple LED and...

Factoring in the Raspberry Pi's current limits

The maximum current we can safely use with a GPIO pin configured for output is 16 mA. However, there is a configurable aspect of GPIO pins, which means that, by default, we should not use more than 8 mA per GPIO. This limit can be configured so that it goes up to 16 mA, but this is beyond our scope. Ideally, we want to be moving toward external circuits when more current is needed rather than pushing the pins higher and higher. We will learn how to do this in Chapter 7Turning Things On and Off.

While we want to limit a single GPIO output pin to 8 mA, we should not exceed a combined total of ~50 mA over multiple GPIO pins. When it comes to GPIO input pins, we should limit the current to 0.5 mA for safe operation when connecting an external input device or component. Connecting an input GPIO pin directly to the Raspberry Pi's +3.3 V or GND pin is fine as the measured current is approximately 70 microamps. (We&apos...

Calculating the resistor's power dissipation

General-purpose resistors like the ones we're using in our breadboards are commonly rated to be 1/8 Watt, 1/4 Watt, or 1/2 Watt. If you supply too much power to a resistor, it will burn out with a puff of smoke and give off a horrible smell.

Here is how we calculate the power dissipation of our 200Ω resistor when we have a 3.3-volt power source:

  1. The power dissipated by a resistor can be calculated with the following formula. Note that the voltage V is the voltage drop across the resistor in volts, while R is the resistance in Ohms:

  1. Therefore, when we substitute our resistor's voltage drop and resistance value in the formula, we get the following:

= 0.0072 Watts, or 7.2 milliwatts (or mW)

  1. Our power value of 7.2 mW is below even a 0.25 Watt-rated resistor, so a 1/8 Watt or above resistor is safe in our circuits and will not burn out in a puff of smoke.

If you think the power equation looks different...

Exploring digital electronics

Digital I/O essentially means detecting or making a GPIO pin high or low. In this section, we will explore core concepts and see some examples of digital I/O in operation. We'll then talk about how this relates to your Raspberry Pi and any digital electronic components you will interface with it. We will start or digital I/O journey by looking at and playing with digital output.

Digital output

In simple electrical terms for our Raspberry Pi, when we drive a GPIO pin high, its voltage measures ~3.3 volts, and when we drive it low, it measures ~0 volts.

Let's observe this using a multimeter:

Different multimeters may have different connections and labeling than the multimeter illustrated here. Consult your multimeter's manual if you are unsure how to set it up for measuring voltage.
  1. Set your multimeter to its voltage setting and attach it to GPIO 21 and GND, as shown in the following diagram:

Figure 6.3 – Connecting a multimeter to a GPIO pin
  1. Run the following code, which you can find in the chapter06/digital_output_test.py file. You will notice that the meter toggles between about 0 volts and about 3.3 volts. I say about because nothing is ever really perfect or precise in electronics; there are always tolerances. Here's a synopsis of the code:
# ... truncated ...
GPIO_PIN = 21
pi = pigpio.pi()
pi.set_mode(GPIO_PIN, pigpio...

Digital input

Generally, when we think about digital input and voltages for a 3.3-volt device such as the Raspberry Pi, we think of connecting a pin to the ground (0 volts) to drive it low or connect it to 3.3 volts to make it high. In most applications, this is exactly what we will strive to do. However, in truth, there is more to this story because GPIO pins don't just operate at two discrete voltage levels. Instead, they work within a range of voltages that define an input pin as being high and low. This applies to the Raspberry Pi and similar computers with GPIOs, microcontrollers, ICs, and breakout boards.

Consider the following diagram, which shows a voltage continuum between 0 and 3.3 volts, as well as three highlighted areas labeled low, floating, and high:

Figure 6.4 – Digital input trigger voltages

This illustration is telling us that if we apply a voltage between 2.0 volts and 3.3 volts, then the input pin will read as a digital high. Alternatively...

Using pull-up and pull-down resistors

When a pin is not connected to anything, it's said to be floating. As shown in the preceding example, it floats around, picking up electrical noise around it from other nearby components, wires connected to it, and charges coming from yourself.

Referring again to the preceding diagram, when the button is pressed, the circuit completes and GPIO 21 gets connected to the ground, and hence we can say for certain that the pin is low. And as we just saw when the button is not pressed, GPIO 21 is floating it can fluctuate between high and low due to external noise.

This needs to be rectified, and we can do this two ways with a resistor or in code.

The resistor solution

If we add an external resistor to the circuit, as shown in the following diagram, then we'll introduce what is called a pull-up resistor, which serves the purpose of pulling (meaning connecting) GPIO pin 21 up (meaning connected to a positive voltage) to 3.3 volts:

Figure 6.6 – Push button circuit with a pull-up resistor

Here are the steps to create this circuit on your breadboard. The step numbers here match the numbered black circles shown in the preceding diagram:

  1. Place the push button on your breadboard.
  2. Place the resistor (with a value between 50kΩ to 65kΩ ) on your breadboard. One end of the resistor shares the same row (shown at hole B5as the upper positioned leg of the push button. The other end of the resistor is placed on an empty row.
  3. Connect the other end of the resistor to a 3.3-volt pin on your Raspberry Pi.
  4. Connect the lower leg of the push button to a GND...

The code solution

We can solve our floating pin situation in code by telling our Raspberry Pi to activate and connect an embedded pull-up resistor to GPIO 21, which, according to the Raspberry PI's documentation, will be within the range 50kΩ-65kΩ, hence why we stipulated that range in the circuit shown in the previous diagram.

The following diagram shows a circuit similar to the one shown in the preceding diagram, but without the physical resistor in the external circuit. I've added a resistor inside the Raspberry Pi diagram to illustrate the fact that there is a physical resistor hiding away somewhere in the Raspberry Pi's circuitry, even though we can't see it:

Figure 6.7 – Push button circuit using an embedded pull-up resistor

Let's enable a pull-up resistor in code and test this circuit. Here are the steps for you to follow:

  1. This example uses the push button circuit shown previously in Figure 6.5. Please...

Exploring analog electronics

As we saw in the previous section, digital I/O is all about discrete highs or lows, as determined by voltage. Analog I/O, on the other hand, is all about degrees of voltage. In this section, we will explore some core concepts and look at examples of analog I/O in operation.

Analog output

In Chapter 5, Connecting Your Raspberry Pi to the Physical World, we discussed that by using PWM on a digital output pin, we can create a pseudo-analog output or the appearance of a variable output voltage. Furthermore, we also saw PWM in use back in Chapter 3, Networking with RESTful APIs and Web Sockets Using Flask, when we used this concept to control the brightness of an LED.

In this section, we'll explore the idea underlying PWM just a little further with a short exercise. Our example is similar to the one we performed for digital output previously, only this time, we are using PWM to produce a varying voltage on a GPIO pin. Here are the steps we need to follow:

  1. Connect your multimeter to your Raspberry Pi as we did for digital output in Figure 6.3.
  2. Run the following code, which you can find in the chapter06/analog_pwm_output_test.py file.
  3. As the code runs, your multimeter will step through a range of different voltages. They won't be...

Analog input

In Chapter 5, Connecting Your Raspberry Pi to the Physical World, we learned how to use the ADS1115 ADC breakout module, and that analog input is all about measuring a voltage from within a predefined range, which, for our purposes, is between 0 volts and 3.3 volts. While in digital I/O, we'd say 0 volts measured on a pin means low and 3.3 means high, in analog I/O, there are no concepts of high or low in this regard.

Many simple analog components and sensors operate on the principle that their resistance changes in accordance with what they measure. For example, a light dependent resistor, or LDR, changes its resistance in proportion to the light it detects. However, analog input is all about measuring voltage. To turn a varying resistance into a varying voltage, we use a voltage divider circuit.

Voltage dividers

The following diagram shows a simple two-resistor voltage divider circuit. Our resistor values are fixed for this example to illustrate the basic principle. Notice that we've used 5 volts in this example. The reason for this will be revealed shortly when we cover logic-level conversion:

Figure 6.8 – Measuring voltages across a voltage divider

It's a principle of electronics and resistors that voltage is dropped across series resistors in proportion to their resistance. In the preceding circuit, R1 is twice as high as R2, so it drops twice as much voltage. Here is the basic formula, as applied to the preceding circuit (it's actually the application of Kirchhoff's Law and Ohm's Law again):

Vout = 5 volts x 2000Ω / (1000Ω + 2000Ω)

Vout = 3.33333 volts

We'll see the application of voltage dividers in Section 3IoT Playground – Practical Examples to Interact with the Physical World, but for now, to...

Understanding logic-level conversion

There will be occasions when you need to interface with 5-volt devices from your Raspberry Pi's 3.3-volt GPIO pins. This interfacing may be for the purpose of GPIO input, output, or bi-directional I/O. The technique used to convert between logic-level voltages is known as logic-level conversion or logic-level shifting.

There are a variety of techniques that can be used to shift voltages, and we will cover two of the more common ones in this section. One uses a voltage divider circuit, which we discussed under the previous heading, while the other uses a dedicated logic-level shifting module. Our first example of logic-level conversion will be to look at a resistor-based solution known as a voltage divider.

Voltage dividers as logic-level converters

A voltage divider circuit constructed of appropriately selected resistors can be used to shift down from 5 volts to 3.3 volts, allowing you to use a 5-volt output from a device as the input to your 3.3-volt Raspberry Pi pin.

To be crystal clear in your understanding and learning, in this section, we are dealing with digital electronics, specifically digital input and the application of a voltage divider within a digital input circuit. For your own learning and understanding, please ensure that, after completing this chapter, you are comfortable with the basic practical differences and application of a voltage divider in both analog and digital circuits.

The following diagram is the same example we saw previously in Figure 6.8, only this time, it's been drawn within a different context; that is, showing how a 5-volt input can be shifted down to 3.3 volts:

Figure 6.11 – Using a voltage divider...

Logic-level converter ICs and modules

An alternative to a voltage divider circuit is a dedicated logic-level shifter or converter. They come in IC (chip) form and breadboard-friendly breakout modules. There's no math involved because they are more or less plug and play, and they include multiple channels so that they can convert multiple I/O streams simultaneously.

The following image shows typical 4-channel (left) and 8-channel (right) logic-level conversion breakout modules. The 4-channel on the left is built using MOSFETs, while the 8-channel on the right uses a TXB0108 IC. Please note that while we will cover MOSFETs in Chapter 7, Turning Things On and Off, our focus will be using MOSFETs as switches, not logic-level conversion applications:

Figure 6.12 – Logic-level converter breakout modules

Logic-level shifter modules also have two halves a low voltage side and a high voltage side. In relation to your Raspberry Pi, we connect...

Comparing voltage dividers and logic-level converters

Is one approach better than the other? It depends, though I will say that a dedicated converter will always outshine a basic voltage divider, and they are a lot less fiddly to use with a breadboard. A voltage divider is cheaper to build but only works in a direct direction (you'll need two voltage divider circuits to perform bi-directional I/O). They also have relatively high electrical impedance, meaning that there is a practical delay that occurs between the variable resistance changing and the measurable voltage changing. This delay is enough to make a simple voltage divider impractical for circuits where there is fast switching between high and low states. A dedicated logic-level converter overcomes these limitations, plus they are multi-channel, bi-directional, faster, and more efficient.

Summary

This chapter commenced with a quick overview of the basic tools and equipment that you will need as you get further into electronics and the circuits that we will cover in Section 3 (which we'll be commencing in the next chapter). Then, we went through some suggestions to help keep your Raspberry Pi safe while you are connecting electronics to its GPIO pins, as well as a few tips when it comes to purchasing components.

Then, we explored Ohm's Law (and very briefly Kirchhoff's) before working through the reasons and calculations as to why our LED circuit was using a 200 Ohm resistor. We followed this example by looking at the electronic properties of digital circuits, where we explored logic voltage levels, floating pins, and pull-up and pull-down resistors. We then looked at analog circuits and worked through an example of a voltage divider circuit. We concluded this chapter by looking at logic-level conversion and how you can interface a 5-volt logic device...

Questions

As we conclude, here is a list of questions for you to test your knowledge regarding this chapter's material. You will find the answers in the Assessments section of the book:

  1. You have a circuit that requires a 200Ω resistor, but you only have a 330Ω resistor available. It is safe to use this value?

  2. You substitute a higher value resistor in a circuit but the circuit does not work. With respect to Ohm's Law, what could be the problem?
  3. You calculated a suitable resistor value for a circuit using Ohm's Law, but when you applied power to the circuit, the resistor started to discolor and let off smoke. Why?
  4. Assuming GPIO 21 is configured via Python as an input pin and it is connected by a wire directly to the +3.3-volt pin, what value will pi.read(21) return?
  1. You have a push button set up so that when it's pressed, it connects GPIO 21 to a GND pin. When the button is not pressed, you notice that your program is erratic and appears...

Further reading

The following two sites are electronic manufacturers and they both feature a wide range of entry-to-mid-level tutorials. They focus on the practical aspects of electronics and don't bombard you with too much theory. Try a search for Raspberry Pi on their sites:

In relation to the concepts that we have covered in this chapter, here are some specific links on the aforementioned sites:

If you want to go deeper, the following two websites...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Practical Python Programming for IoT
Published in: Nov 2020Publisher: PacktISBN-13: 9781838982461
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime