<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" > <channel> <title>Circuit Crush</title> <atom:link href="https://www.circuitcrush.com/feed/" rel="self" type="application/rss+xml" /> <link>https://www.circuitcrush.com</link> <description>Learn Electronics & Microcontrollers</description> <lastBuildDate>Wed, 21 Aug 2024 20:06:21 +0000</lastBuildDate> <language>en-US</language> <sy:updatePeriod> hourly </sy:updatePeriod> <sy:updateFrequency> 1 </sy:updateFrequency> <generator>https://wordpress.org/?v=6.7</generator> <image> <url>https://www.circuitcrush.com/wp-content/uploads/cropped-favicon-2-32x32.png</url> <title>Circuit Crush</title> <link>https://www.circuitcrush.com</link> <width>32</width> <height>32</height> </image> <site xmlns="com-wordpress:feed-additions:1">118658195</site> <item> <title>How LCDs Work</title> <link>https://www.circuitcrush.com/how-lcds-work/</link> <comments>https://www.circuitcrush.com/how-lcds-work/#respond</comments> <dc:creator><![CDATA[Brian]]></dc:creator> <pubDate>Wed, 02 Dec 2020 03:59:33 +0000</pubDate> <category><![CDATA[Electronics]]></category> <category><![CDATA[Displays]]></category> <category><![CDATA[LCD]]></category> <category><![CDATA[Screens]]></category> <guid isPermaLink="false">https://www.circuitcrush.com/?p=4171</guid> <description><![CDATA[How LCDs Work If you’re an electronics hobbyist of any sort or even just the curios type, you may wonder how LCDs work. The LCD screen is ubiquitous. From our big screen TVs to our computers and “smart” devices like watches and phones to small displays we use in our projects, the LCD is now […]]]></description> <content:encoded><![CDATA[<h1><strong>How LCDs Work<br /> </strong></h1> <p>If you’re an electronics hobbyist of any sort or even just the curios type, you may wonder how LCDs work. The LCD screen is ubiquitous. From our big screen TVs to our computers and “smart” devices like watches and phones to small displays we use in our projects, the LCD is now truly the go-to display for hobbyists and manufacturers alike. <span id="more-4171"></span>While newer technologies like organic LEDs (OLEDs) and <a href="https://www.circuitcrush.com/quantum-dots/" target="_blank" rel="noopener noreferrer">quantum dots</a> threaten to loosen some of the LCD’s grip on the electronics industry, it still reigns supreme as the king of displays as of this writing.</p> <p>If you read this blog often, you know I sometimes like to start my posts off with a bit of quick history on the device or topic of discussion.</p> <p>Toward that end, the story of the LCD began in the late 1960s when a few of RCA’s scientists invented the device. The goal: to make flat, wall-mountable TVs. Today, most of us have already disposed of our heavy, bulky, power-hungry CRT (cathode ray tube) based TVs, but back then CRTs were the only available option for screens. While those of us living in current times take our thin, cheap, lightweight LCD TVs for granted (along with our laptops, phones, and even displays on our appliances), the scientists and engineers involved in the creation of the original LCDs failed and could not create a viable wall-mounted LCD TV at that time. Because of this, RCA did not commercialize the LCD.</p> <p>But good technology has a certain persistence about it, tending to eventually emerge victorious despite roadblocks and setbacks. This is due — at least in part, to the onslaught of time plus the relentless work of various scientists, engineers and even hobbyists. Eventually, the LCD did start to appear in various electronic devices, and it took off.</p> <p>The rest is history; now they’re everywhere and I’ll abruptly conclude my throw-back with that.</p> <p>But before we take a look at the inner workings of LCD screens, I want to let the reader know what they can expect from this article.</p> <p>I’m not going to talk about how to wire or hook up specific LCDs or LCD breakout boards nor discuss the specs on said LCDs/boards. Also, this post doesn’t cover writing code regarding the use of an LCD. Wiring and especially writing code for a particular LCD is dependent on the LCD of choice and the microprocessor/board one chooses to use as the brains of their project.</p> <p>Rather, I’m going to offer a solid treatment on the basics of how LCDs work and discuss the basic types of LCDs you may run into. This will be a primer for future, more detailed articles concerning the subject.</p> <p>Now, let’s take a look at how LCDs work.</p> <h2><strong>How LCDs Work – Light Polarization<br /> </strong></h2> <p>LCD screens rely on the polarization of light to work, so it’s appropriate we start with that.</p> <p>But what is light polarization? Good question – let’s take a quick minute to figure it out.</p> <p>Light (or any electromagnetic wave) can be polarized.</p> <p>To visualize this, imagine you have a rope in your hand and start to shake it. Waves will form and travel along the rope. They will be in one plane, assuming you don’t rotate your wrist or wiggle the rope in a different direction. The plane the waves along the rope travel in may be vertical or horizontal, as we can see in figure 1.</p> <p><img fetchpriority="high" decoding="async" class="aligncenter size-full wp-image-4172" src="http://www.circuitcrush.com/wp-content/uploads/Rope-in-Hand.jpg" alt="Light polarization example" width="225" height="340" srcset="https://www.circuitcrush.com/wp-content/uploads/Rope-in-Hand.jpg 225w, https://www.circuitcrush.com/wp-content/uploads/Rope-in-Hand-199x300.jpg 199w, https://www.circuitcrush.com/wp-content/uploads/Rope-in-Hand-99x150.jpg 99w" sizes="(max-width: 225px) 100vw, 225px" /></p> <p><strong><em>Figure 1: waves along a rope. In part (a) the waves are vertical and in part (b) they’re horizontal. The waves in the picture are transverse waves, just like light and all other electromagnetic waves.</em></strong></p> <p>In both cases, we can say that the waves along the rope have a linear polarization because the waves are in one plane.</p> <p>Now, let’s say we put an obstacle in the path of the waves with a slit in it. If the slit is vertical, the horizontal waves will not pass through it. Similarly, if the slit is horizontal, the vertical waves will not pass. If we use two obstacles, one with a vertical slit and one with a horizontal slit neither will pass. Figure 2 offers some intuitive insight into how light can be polarized.</p> <p> </p> <p><img decoding="async" class="aligncenter size-full wp-image-4173" src="http://www.circuitcrush.com/wp-content/uploads/Polarizer.jpg" alt="Polarizer" width="444" height="173" srcset="https://www.circuitcrush.com/wp-content/uploads/Polarizer.jpg 444w, https://www.circuitcrush.com/wp-content/uploads/Polarizer-300x117.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Polarizer-150x58.jpg 150w" sizes="(max-width: 444px) 100vw, 444px" /></p> <p><strong><em>Figure 2: this figure offers an intuitive demonstration of how polarization works. In part (a) the vertically polarized waves pass and in part (b) the horizontally polarized waves do not pass because the orientation of the slit will not allow it. Note that both ropes have linearly polarized waves because either way, the waves reside in only one plane. One can polarize light because, like the rope, it travels in waves.</em></strong></p> <p> </p> <p><img decoding="async" class="aligncenter size-full wp-image-4174" src="http://www.circuitcrush.com/wp-content/uploads/Polarized-Light.jpg" alt="Polarized Light" width="210" height="204" srcset="https://www.circuitcrush.com/wp-content/uploads/Polarized-Light.jpg 210w, https://www.circuitcrush.com/wp-content/uploads/Polarized-Light-150x146.jpg 150w" sizes="(max-width: 210px) 100vw, 210px" /></p> <p><strong><em>Figure 3: two pairs of polarized sunglasses at 90 degree angles. Notice no light passes through where they overlap. This is because both vertically and horizontally polarized light waves are being blocked. </em></strong></p> <p>Now that we have a basic intuitive grasp on light polarization, let’s talk about liquid crystals.</p> <h2><strong>Liquid Crystals 101<br /> </strong></h2> <p>The acronym LCD stands for liquid crystal display. As the name suggests, you can’t make an LCD without liquid crystals, but what exactly are liquid crystals?</p> <p>You already know what a liquid is. In case you don’t know, a crystal is a solid whose atoms arrange themselves in a high degree of order, like table salt (which is a crystalline solid) or the cool looking crystal “rocks” one may find in a cave.</p> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4175" src="http://www.circuitcrush.com/wp-content/uploads/Salt.jpg" alt="Salt" width="334" height="267" srcset="https://www.circuitcrush.com/wp-content/uploads/Salt.jpg 640w, https://www.circuitcrush.com/wp-content/uploads/Salt-300x240.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Salt-150x120.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Salt-600x480.jpg 600w" sizes="(max-width: 334px) 100vw, 334px" /></p> <p><strong><em>Figure 4: close up of table salt. Notice how the salt crystals look like cubes. This is because the sodium and chlorine atoms arrange themselves in an orderly fashion. Other crystals do the same, though the shapes may be different for different crystals.</em></strong></p> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4176" src="http://www.circuitcrush.com/wp-content/uploads/Rock-Crystals1.jpg" alt="Rock Crystals" width="331" height="220" srcset="https://www.circuitcrush.com/wp-content/uploads/Rock-Crystals1.jpg 800w, https://www.circuitcrush.com/wp-content/uploads/Rock-Crystals1-300x200.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Rock-Crystals1-150x100.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Rock-Crystals1-768x512.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/Rock-Crystals1-600x400.jpg 600w" sizes="(max-width: 331px) 100vw, 331px" /></p> <p><strong><em>Figure 5: rock crystals similar to those one may find in a cave. Again, the molecules in the crystals arrange themselves in an orderly fashion.</em></strong></p> <p>Liquid crystals are materials that flow like liquid but, like crystalline solids, pack at the molecular level with a high degree of order.</p> <p>The molecules are mostly organic (though I’m not suggesting you crack open your display and eat them!) and appear in a lot of places, including the cells in your body. What makes them useful for LCD screens are their electrical and optical properties.</p> <p>The liquid crystal molecules of interest are rod shaped and are electrically polarized. Some clarification on this is in order. Though liquid crystals can polarize light (as we’ll soon find out), I’m not talking about their ability to alter light waves traveling in a certain plane in this context. I’m talking about the molecules having more electrons in certain areas than others. This gives them a molecular dipole (sort of like an electric charge) and enables one to control their orientation with an electric field or a voltage.</p> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4177 size-full" src="http://www.circuitcrush.com/wp-content/uploads/LCD-Molecule.jpg" alt="How LCDs Work - the Liquid Crystal Molecule" width="450" height="129" srcset="https://www.circuitcrush.com/wp-content/uploads/LCD-Molecule.jpg 450w, https://www.circuitcrush.com/wp-content/uploads/LCD-Molecule-300x86.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/LCD-Molecule-150x43.jpg 150w" sizes="(max-width: 450px) 100vw, 450px" /></p> <p><strong><em>Figure 6: a typical liquid crystal molecule. Notice the rod shape. The red area has a high electron density, the blue areas a lower electron density, making the molecule an electric dipole.</em></strong></p> <h3 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://go.learnarduinonow.com/lp">Academy for Arduino</a> for FREE!</h3> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4422 " src="https://www.circuitcrush.com/wp-content/uploads/Logo-Design-2.png" alt="" width="164" height="115" srcset="https://www.circuitcrush.com/wp-content/uploads/Logo-Design-2.png 964w, https://www.circuitcrush.com/wp-content/uploads/Logo-Design-2-300x210.png 300w, https://www.circuitcrush.com/wp-content/uploads/Logo-Design-2-150x105.png 150w, https://www.circuitcrush.com/wp-content/uploads/Logo-Design-2-768x539.png 768w" sizes="(max-width: 164px) 100vw, 164px" /></p> <h2><strong>How LCDs Work – the Practical Stuff<br /> </strong></h2> <p>Now we know something about the polarization of light and liquid crystal molecules. It’s time to put it all together and talk about how the displays you’re familiar with work. Light polarization, chemistry, and electronics all work in tandem to give us the displays we use today.</p> <h3><strong>Common Types of LCD Displays<br /> </strong></h3> <p>Before we dissect an LCD screen and talk about its individual parts, it will be helpful to quickly discuss the basic types of LCD displays hobbyists are likely to use.</p> <p>Refer to figure 7 for the following discussion.</p> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4178" src="http://www.circuitcrush.com/wp-content/uploads/How-LCDs-Work.png" alt="How LCDs Work" width="653" height="490" srcset="https://www.circuitcrush.com/wp-content/uploads/How-LCDs-Work.png 1200w, https://www.circuitcrush.com/wp-content/uploads/How-LCDs-Work-300x225.png 300w, https://www.circuitcrush.com/wp-content/uploads/How-LCDs-Work-1024x768.png 1024w, https://www.circuitcrush.com/wp-content/uploads/How-LCDs-Work-150x113.png 150w, https://www.circuitcrush.com/wp-content/uploads/How-LCDs-Work-768x576.png 768w, https://www.circuitcrush.com/wp-content/uploads/How-LCDs-Work-600x450.png 600w" sizes="(max-width: 653px) 100vw, 653px" /></p> <p><strong><em>Figure 7: the layers of a typical LCD screen. Some screens have an anti-glare layer on top of layer 1, but this is optional and not all screens have this layer.</em></strong></p> <p><strong>Reflective LCD screens</strong> rely on ambient light passing through the layers and then reflecting back through the screen again to the viewer. In this type of LCD, the last layer (layer 6 in figure 7) is a mirror so the light that enters the screen reflects back. Since the light must pass through layers 1-5 of the screen twice, some light is “lost.”</p> <p><strong>Transmissive LCDs</strong> use a backlight rather than a mirror. The backlight corresponds to layer 6 in figure 7. In this case, the light only needs to pass through the screen layers one time. Transmissive LCD displays are great for viewing where there is no good external light source. The downside is that the backlight eats up a fair amount of power relative to the power consumption of the whole screen. Newer ones use an LED backlight which cuts down on power consumption though, saving battery life. Many smaller modern LCDs are transmissive.</p> <p><strong>Transflective LCD displays</strong> are a hybrid of both the above. They use a special polymer between layers 5 and 6 which can both reflect light and transmit light through it from the backlight depending on ambient lighting conditions. These often find a home in situations where ambient light is variable, like a car.</p> <h3><strong>Anatomy of an LCD<br /> </strong></h3> <p>Now that we know about the basic types of LCD screens, let’s talk a bit more about the individual layers of a common LCD. Refer to figure 7 again.</p> <p>The first layer is a usually a polarizing light filter. In figure 7, this layer vertically polarizes light. The fifth layer is similar but polarizes light horizontally. When light waves oriented in all directions enter the first layer, only waves with a vertical orientation pass and enter the next layer.</p> <p>Next, we have layer 2, the electrode layer. The electrodes are mostly clear, thanks to some clever materials science. This is because light must be able to pass through them so they don’t interfere with the display.</p> <p>LCD manufacturers use indium tin oxide (ITO) for this layer. They deposit ITO on the surface in the shape(s) they wish the LCD to display.</p> <p>Layer 3 is the liquid crystal itself. Before we go any further, here’s a little more detail on liquid crystals.</p> <p>As we know, there are different varieties of liquid crystals.</p> <p>Twisted nematic (or TN for short) is one type which refers to the alignment of liquid crystal molecules when no electric field is present. In this situation, this material forms a helical shape and is able to polarize light passing through by 90 degrees. When an electric field or voltage is present, the material untwists, and, because of this there is no polarization. In other words, when we apply a voltage to it, it does not polarize the light. This causes the light passing through to be blocked by the front vertical polarization filter’s (layer 1) interaction with the horizontal polarization filter (layer 5). Thus, the characters on the screen are now visible. By varying the strength of the electric field, the brightness varies. Figure 8 offers more detail on how this works.</p> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4179" src="http://www.circuitcrush.com/wp-content/uploads/LCD-Layers.jpg" alt="How LCDs Work More Detail" width="268" height="756" srcset="https://www.circuitcrush.com/wp-content/uploads/LCD-Layers.jpg 188w, https://www.circuitcrush.com/wp-content/uploads/LCD-Layers-106x300.jpg 106w, https://www.circuitcrush.com/wp-content/uploads/LCD-Layers-53x150.jpg 53w" sizes="(max-width: 268px) 100vw, 268px" /></p> <p><strong><em>Figure 8: another representation of an LCD in action. Here, the top plate and bottom plate refer to layers 2 and 4 from figure 7, respectively. The LC layer is the liquid crystal layer. Near the middle of the figure, we can see light entering the first polarizer from all orientations (thus the star shape) and exiting it with a vertical polarization. </em></strong></p> <p><strong><em>Also, this section of the figure shows the LC molecules are aligned due to an electric field, so light does not continue to pass through the second polarizer. Rather, the segment of the ‘2’ from the top of the figure appears dark so the viewer can see it. When there is no electric field, the LC molecules are in the twisted arrangement. Because of this, they rotate the light once again allowing it to pass into the second polarizer. Then, the mirror reflects the light back to the viewer making the segment of the ‘2’ appear to be clear, thus almost invisible. </em></strong></p> <p>The twisted nematic design was okay for early LCD displays, but TN material has some issues. It isn’t very responsive and doesn’t have a clear threshold of operation. So, in some instances, an electric field forces the liquid crystals to align, but in others – say a different temperature – the same electric field may not.</p> <p>Enter super-twisted nematic (STN) liquid crystal.</p> <p>The original incarnation is a bit slow to respond but the polarization twist is greater than TN liquid crystal. Though this type is an improvement over TN, better versions have been released since.</p> <p>These include FSTN- and FSTN+ where the F stands for filtered. These variants use an additional layer between STN liquid crystal and the rear polarizer. This gives the screen better contrast and sharpness.</p> <p>Finally, note that color LCDs use red, green, and blue (RGB) color filters (not shown in figures 7 and 8) and/or pixels to generate color images. We’ll talk a bit more about this in the summary section.</p> <h2><strong>More Recent Developments in LCD Technology<br /> </strong></h2> <p>It’s time to talk about some newer LCD technology that you’re likely to see in your TVs, laptops, and phones. We won’t go into gory detail (at least this time) in how they work, but the concept is similar to the older LCD incarnations from above.</p> <p>First up, we have IPS and TFT LCD displays.</p> <p>TFT stands for thin film transistor. For more on transistors and how they work, see <a href="https://www.circuitcrush.com/what-is-a-transistor/" target="_blank" rel="noopener noreferrer">An Introduction to Transistors</a>.</p> <p>This type of display uses transparent FETs (a type of transistor) on glass for controlling the rows and columns of the screen. This allows much more current to move around and changes the electric field the screen uses to control the liquid crystal material quickly.</p> <p>IPS is an acronym for in plane switching.</p> <p>Here, the electrodes are on the sides of the pixel so the electric field that controls the liquid crystal orientation is parallel to the glass. This gives the viewing angle a significant boost, greatly increasing it. In turn, this makes the color consistency better. You may have tried to view an older LCD TV at a wide angle and noticed the color appeared to be altered and washed out. IPS screens help reduce this phenomenon.</p> <h3><strong>Check Your Cholesterol<br /> </strong></h3> <p>Another, newer LCD technology worth mentioning is cholesteric LCD or ChLCD for short.</p> <p>The name refers to the cholesterol-like liquid crystal material.</p> <p>These displays are reflective and sunlight-readable, whereas many transmissive screens tend to wash out in sunlight. ChLCDs break the mold we discussed earlier (that a lot of light is ”lost” in reflective LCDs) because they lack the polarizer layers from figure 7. Because of this, cholesteric LCDs reflect a higher amount of incoming light than standard screens.</p> <p>The coolest thing about these LCD displays is that they are bistable, which is just a fancy way of saying the picture stays on after the power is removed. If you order a cholesteric LCD, don’t freak out if it arrives with the manufacturer’s logo and tagline still visible! This is perfectly normal. They also sport a high contrast and good viewing angle due to the lack of polarizers. One of their drawbacks, however, is the relatively slow refresh rate, especially at colder temperatures.</p> <p>Keep an eye out for ChLCD in electronic paper and other uses.</p> <h2><strong>How LCDs Work: Summary & Recap<br /> </strong></h2> <ul> <li>LCD stands for liquid crystal display.</li> <li>Most LCDs rely on light polarization to work.</li> <li>The molecules in solid crystals arrange themselves in an orderly fashion. Table salt is a good example of a common crystalline solid.</li> <li>Liquid crystals have both properties of a liquid and of a crystalline solid. They are organic molecules which can polarize light. They also have an electric dipole which allows them to be controlled with an electric field.</li> <li>There are 3 common types of LCD displays. Reflective displays use ambient light. Transmissive screens have a back light. Transflective displays are a hybrid of both.</li> <li>A series of layers make up an LCD display. Figures 7 and 8 graphically depict the layers of a typical LCD.</li> <li>Voltage controls the orientation of the liquid crystal material in the LCD due to the liquid crystal molecule’s electric dipole. A dipole is just an abundance of electrons in one area of a molecule, giving it electrical properties. This, combined with polarizers, allows light to pass or not pass, which controls which (if any) characters show on the screen.</li> <li>A pixel is the smallest controllable element on a screen. They are shaped like little squares. Many of them grouped together and turned on in a certain pattern can form a meaningful picture.</li> <li>Color LCDs use color filters or color pixels in addition to the layers. A colored pixel is actually three pixels in one. The three “mini pixels” are red, green, and blue. By varying the intensity of each color “mini pixel” within a particular pixel, it can display any of all the possible colors. This can number in the tens of millions depending on the specs of the screen. Displays like this usually find their home in TVs, computers, and phones. Other smaller, simpler LCD screens are often monochrome (meaning one color, usually black or grey) or are able to display only a limited number of colors.</li> <li>Newer LCD technologies include thin film transistor (TFT), in plane switching (IPS) and cholesteric LCD (ChLCD).</li> <li>Other new technologies like OLEDs and quantum dots may eventually replace many LCD displays, but right now the LCD is still the most common and cheapest display in use.</li> </ul> <h2><strong>Seeing How LCDs Work Clearly<br /> </strong></h2> <p>So now we know the basics on how LCDs work.</p> <p>Of course, it gets a bit more complicated when you drill deeper into the physics and chemistry of the devices, but this was just an introduction to LCDs.</p> <p>After reading this, those who are using LCD screens in their projects should have a better understanding of how LCDs work.</p> <p>Drop me a comment and tell about your projects involving LCDs. Are you using any of the newer technologies? What are you using the LCD display for?</p> <h2 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://go.learnarduinonow.com/lp">Academy for Arduino</a> for FREE!</h2> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4422 " src="https://www.circuitcrush.com/wp-content/uploads/Logo-Design-2.png" alt="" width="185" height="130" srcset="https://www.circuitcrush.com/wp-content/uploads/Logo-Design-2.png 964w, https://www.circuitcrush.com/wp-content/uploads/Logo-Design-2-300x210.png 300w, https://www.circuitcrush.com/wp-content/uploads/Logo-Design-2-150x105.png 150w, https://www.circuitcrush.com/wp-content/uploads/Logo-Design-2-768x539.png 768w" sizes="(max-width: 185px) 100vw, 185px" /></p> <a target="_blank" href="https://www.drpeterscode.com/index.php"><img src="https://www.circuitcrush.com/wp-content/plugins/dpabottomofpostpage/apixel1x1.jpg" ></a><table></table>]]></content:encoded> <wfw:commentRss>https://www.circuitcrush.com/how-lcds-work/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">4171</post-id> </item> <item> <title>All About I2C</title> <link>https://www.circuitcrush.com/i2c-tutorial/</link> <comments>https://www.circuitcrush.com/i2c-tutorial/#comments</comments> <dc:creator><![CDATA[Brian]]></dc:creator> <pubDate>Wed, 19 Aug 2020 23:32:37 +0000</pubDate> <category><![CDATA[Networking]]></category> <category><![CDATA[I2C]]></category> <category><![CDATA[Serial Communication]]></category> <guid isPermaLink="false">https://www.circuitcrush.com/?p=4119</guid> <description><![CDATA[What a time to be an electronics enthusiast! These days there is no shortage of communication standards and protocols for microcontrollers and other electronic devices. In addition to the I2C specification — the topic of this article, we have SPI, UART, RS-232, CAN, LIN, 1-wire, the ubiquitous USB interface and more. And these are just […]]]></description> <content:encoded><![CDATA[<p>What a time to be an electronics enthusiast! These days there is no shortage of communication standards and protocols for microcontrollers and other electronic devices. In addition to the I2C specification — the topic of this article, we have SPI, UART, RS-232, CAN, LIN, 1-wire, the ubiquitous USB interface and more.</p> <p>And these are just wired serial communications. If we throw in wireless and parallel specifications and protocols, the list grows much bigger.</p> <p>Each of the above have their own pros, cons, and are suitable for different purposes. This article will be an introduction to the I2C specification. You will see I2C written as I<sup>2</sup>C in many instances and both are technically correct. However, to keep things easy and consistent, we’ll refer to the protocol as I2C in the rest of this article.</p> <p>Be sure to go until the end for a nice summary on I2C communications and an I2C specifications chart!</p> <p><span id="more-4119"></span></p> <h1><strong>The I2C Specification<br /> </strong></h1> <h2><strong>Why I2C?<br /> </strong></h2> <p>I2C stands for inter-integrated circuit bus (which is why many refer to it as I<sup>2</sup>C). Most people pronounce it <em>I squared C</em>.</p> <p>The standard dates back to the 1980’s when Dutch giant Philips developed it.</p> <p>At the time, integrated circuits were growing more complex. Along with the additional complexity came higher pin counts. The actual circuitry inside an IC is much smaller than the package it comes in. The problem was that the higher pin counts were forcing IC manufacturers to use larger packaging in order to accommodate all the pins. The I2C standard was an answer to this problem. In an effort to reduce pin counts, Philips developed the standard. We’ll see why I2C can decrease pin counts in a minute.</p> <p>Multiwire cables don’t work very well beyond a few feet and are awful for use in high speed parallel buses which only work in lengths up to a few inches and require expensive connectors. This issue, along with the IC pin count issue, gave birth to a bunch of simple serial data buses and standards with I2C being one of them.</p> <p>Rather than running 16 and 32 bit buses (along with additional control lines) between boards and ICs, these serial data buses allow one to use far fewer lines which drastically simplifies manufacturing and the transfer of the data itself.</p> <p>Philips nixed their semiconductor division (which is now NXP) but I2C is alive and well today.</p> <h2><strong>How the I2C Standard Works<br /> </strong></h2> <p>I2C requires only two lines (plus ground) to work. Compare that with 32+ lines for a parallel connection with a modern 32-bit microprocessor.</p> <p>It is a two-wire serial bidirectional bus that connects ICs, boards (i.e. you can use I2C to connect Arduinos), and other electronic devices. Its also a synchronous bus meaning that the bit transfer is controlled by a clock which the master shares with all devices on the bus. Synchronous devices need a physical line to be dedicated to the clock (like SCL) which provides synchronization between all devices on the bus. But I2C is also asynchronous in the sense that the master can start and stop data transfer at any time.</p> <p>The two primary lines are the serial data line (SDA) and the clock like (SCL). Both share a common ground. The lines are usually copper paths on a PCB or short segments of twisted pair cable. The I2C standard uses a master-slave configuration which we’ll talk more about in a minute.</p> <p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4120" src="http://www.circuitcrush.com/wp-content/uploads/I2C-Standard.jpg" alt="I2C Standard" width="480" height="172" srcset="https://www.circuitcrush.com/wp-content/uploads/I2C-Standard.jpg 480w, https://www.circuitcrush.com/wp-content/uploads/I2C-Standard-300x108.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/I2C-Standard-150x54.jpg 150w" sizes="(max-width: 480px) 100vw, 480px" /></p> <p style="text-align: center;"><strong><em>Figure 1: Basic I2C block diagram.</em></strong></p> <p>Figure 1 depicts the basic gist of how an I2C bus works. Notice the double arrow on the data line (SDA). This indicates that SDA is a bidirectional line.</p> <p>The SDA and SDL lines are open-drain that use a pull-up resistor to 5 V or whatever the supply voltage is. We’ll say more about open drains shortly.</p> <p>The I2C bus can accommodate a lot more than just two devices and all circuits that connect to the bus share the two bus lines.</p> <p>A device on the I2C bus is usually either a master or a slave. The master provides overall control of I2C transmissions and also supplies the clock to any slave devices. Only a master can initiate a data transfer, slaves just respond to read or write commands from the master.</p> <p>So, what exactly is the “master?”</p> <p>The master can be an IC made for that purpose; however, it is usually built into a microcontroller or board. In fact, many single chip microcontrollers include an I2C bus as a standard I/O port.</p> <p>As we can see from figure 1, any device may transmit or receive data in either direction but what’s not obvious from the figure is that only one device can speak at a time.</p> <p>Let’s go a little deeper into the I2C rabbit hole and get to know the bus on a more intimate level.</p> <h3 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h3> <p><img loading="lazy" decoding="async" class="wp-image-4238 aligncenter" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="297" height="113" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 297px) 100vw, 297px" /></p> <h2><strong>Going Further Down the I2C Rabbit Hole<br /> </strong></h2> <p>Within the original I2C specification, two main modes of operation exist: standard mode with a maximum clock rate of 100kHz and fast mode with a max clock rate of 400 kHz.</p> <p>Each device that connects to the I2C bus has a unique address.</p> <p>More than one master (and also more than one slave) can exist on the same bus. However, one master always has control over the bus. This master is responsible for generating the clock and controlling bus access by initiating and terminating message transfers.</p> <p>Both SDA and SCL are open-drained and need to be pulled up to Vcc (the source voltage) with a resistor whose value typically ranges from 1 kΩ to 10 kΩ. Generally, the lower the value of the resistor the faster the speed of the bus. Figure 2 illustrates this.</p> <p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4121" src="http://www.circuitcrush.com/wp-content/uploads/I2C-Bus_2.jpg" alt="I2C Bus" width="899" height="303" srcset="https://www.circuitcrush.com/wp-content/uploads/I2C-Bus_2.jpg 899w, https://www.circuitcrush.com/wp-content/uploads/I2C-Bus_2-300x101.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/I2C-Bus_2-150x51.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/I2C-Bus_2-768x259.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/I2C-Bus_2-600x202.jpg 600w" sizes="(max-width: 899px) 100vw, 899px" /></p> <p style="text-align: center;"><strong><em>Figure 2: I2C bus with a pull-up resistor. Normally, only SDA needs the pull-up resistor. </em></strong></p> <p>In figure 2, devices 1-3 are slaves and the MCU is the master. We can also see a resistor (Rp) “pulling up” SDA to 5 V, which is Vcc in this case. SDA needs only one resistor, regardless of how many devices connect to the bus.</p> <p>SCL only needs a pull-up resistor if there will be more than one master on the line or when a slave will do clock stretching (more on this later).</p> <p>In the first case, the resistor is necessary for arbitration purposes if more than one master tries to initiate a data transfer at the same time. The I2C standard contains an arbitration procedure to deal with such events.</p> <p>In the second case, a receiver (or slave) may not be ready to receive data from the transmitter, so it holds SCL low to “stretch” the clock to delay the transmitter. Figure 3 illustrates the I2C bus with two pull-up resistors.</p> <p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4122" src="http://www.circuitcrush.com/wp-content/uploads/I2C-Bus.png" alt="I2C Bus 2 pull ups" width="903" height="304" srcset="https://www.circuitcrush.com/wp-content/uploads/I2C-Bus.png 903w, https://www.circuitcrush.com/wp-content/uploads/I2C-Bus-300x101.png 300w, https://www.circuitcrush.com/wp-content/uploads/I2C-Bus-150x50.png 150w, https://www.circuitcrush.com/wp-content/uploads/I2C-Bus-768x259.png 768w, https://www.circuitcrush.com/wp-content/uploads/I2C-Bus-600x202.png 600w" sizes="(max-width: 903px) 100vw, 903px" /></p> <p style="text-align: left;"><strong><em>Figure 3: in this case both lines have pull-up resistors. The second one on SCL is only necessary in the two special circumstances described above.</em></strong></p> <p>So, what’s all this <strong><em>open drain</em></strong> stuff?</p> <p>The drain is one of the terminals on a MOSFET. For a review on MOSFETS check out <a href="https://www.circuitcrush.com/what-is-a-transistor/" target="_blank" rel="noopener noreferrer">An Introduction to Transistors</a>. A typical IC is made up of many tiny MOSFETS. The term open drain is engineering speak for a sink on an output pin. By sink, I mean current flows into the pin, not out of it. A current source is the opposite of a current sink. In a current source, current flows out of the pin.</p> <p>Therefore, the term open drain means that part of the output transistor connects directly to a pin that’s on the outside of the IC.</p> <p>And what about that <strong><em>pull-up resistor</em></strong>?</p> <p>The pull-up resistor connects to HIGH (which is the same as the supply voltage or Vcc) at one end and connects to one or more external pins of the open-drain devices (via the bus). Thus, if any one of the open-drain devices is set to sink current, current flow for all of the devices sinks to ground.</p> <h3><strong>I2C Protocol<br /> </strong></h3> <p>The I2C bus is idle when both SDA and SCL are HIGH. The master initiates a data transfer by issuing a start condition. A start condition is simply a HIGH to LOW transition on the SDA line while SCL is HIGH. After the start condition, the master sends out an address to reach the right slave on the bus. Once any slave determines the requested address is not its own it disregards all further bus activity until the stop condition (more on this in a sec).</p> <p>The address is 7 bits with bit 8 being a data direction. Since 2<sup>7</sup> = 128, an I2C bus can hold up to 128 slave devices, though in practice there are usually a lot less. Also, the I2C specification includes a 10-bit addressing option but it rarely sees use in real life. The data direction dictates whether the master will be writing to the slave or the slave will be reading from the master. A HIGH indicates a write to the slave, and a LOW indicates a slave is reading from the master.</p> <p>After the address of the slave is sent, the protocol calls for sending a code to identify the register in the slave the master will write to or read from, if the slave has multiple registers. This is part of the data block in figure 4.</p> <p>The master (which controls the clock or SCL line) sends out the bits one bit per clock cycle with the most significant bit or MSB (for a review on MSB and binary numbers see <a href="https://www.circuitcrush.com/binary-numbers-basics/" target="_blank" rel="noopener noreferrer">A Bit of Fun with Binary Number Basics</a>) going first. The values on the SDA line can only change when the SCL line is LOW.</p> <p>Figure 4 depicts the basics of how this works.</p> <p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4123" src="http://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Basic.jpg" alt="I2C-Protocol-Basic" width="1024" height="183" srcset="https://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Basic.jpg 1024w, https://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Basic-300x54.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Basic-150x27.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Basic-768x137.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Basic-600x107.jpg 600w" sizes="(max-width: 1024px) 100vw, 1024px" /></p> <p><strong><em>Figure 4: basic I2C protocol diagram. For every 8 bits of data, the receiver or slave sends an acknowledgement (ACK) during the ninth clock cycle by pulling SDA low unless the master or receiver wants to end the transfer. In that case, the master will not acknowledge (this is the NACK in the picture) by keeping SDA high. Note that I2C does support 10-bit addressing but it is not used very often.</em></strong></p> <p>The slave will respond with an acknowledgement bit on the SDA line by pulling SDA LOW during the clock’s ninth cycle. The direction bit (R/W or read/write in figure 4) determines whether the master or slave will be the transmitter in the subsequent data transmissions.</p> <p>Data is transmitted in 8-bit chunks with the MSB first until all of it has been transferred, with an ACK (or a NACK if the transmission is over) after each byte. There is no limit on the number of bytes in a transmission. If any data chunk is not acknowledged, there will be no more data exchanged and the transmission ends.</p> <p>To end a data transfer, the master will send a stop condition by pulling the SDA line from LOW to HIGH while the SCL line is at a HIGH. If the master wishes to change the direction of the data transmission it will send another start condition, so it doesn’t have to release control of the bus.</p> <p>Figure 5 gives more detail on the read format of the I2C protocol. Below that, figure 6 shows some detail about the start and stop conditions.</p> <p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4124" src="http://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Details.jpg" alt="I2C-Protocol-Details" width="1020" height="235" srcset="https://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Details.jpg 1020w, https://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Details-300x69.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Details-150x35.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Details-768x177.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/I2C-Protocol-Details-600x138.jpg 600w" sizes="(max-width: 1020px) 100vw, 1020px" /></p> <p><strong><em>Figure 5: more detail on I2C transmissions. A start condition occurs if the data line (SDA) goes LOW while the clock (SCL) is HIGH. If it rises while the clock is HIGH a stop condition ensues. Other than these two special states, the data line can only change when the clock line is LOW.</em></strong></p> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4125" src="http://www.circuitcrush.com/wp-content/uploads/I2C-Start-Stop-Condition.jpg" alt="I2C-Start-Stop-Condition" width="568" height="217" srcset="https://www.circuitcrush.com/wp-content/uploads/I2C-Start-Stop-Condition.jpg 631w, https://www.circuitcrush.com/wp-content/uploads/I2C-Start-Stop-Condition-300x115.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/I2C-Start-Stop-Condition-150x57.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/I2C-Start-Stop-Condition-600x229.jpg 600w" sizes="(max-width: 568px) 100vw, 568px" /></p> <p style="text-align: center;"><strong><em>Figure 6: a close up of the I2C protocol start/stop conditions. The master initiates both conditions. In part a, SDA transitions from HIGH to LOW while SCL is HIGH. In part b, SDA transitions from LOW to HIGH while SCL is HIGH.<br /> </em></strong></p> <p> </p> <p>At first, this process can seem complicated so let’s summarize it.</p> <h4><strong>I2C Data Transmission Steps<br /> </strong></h4> <ul> <li>The master initiates a transmission by sending a start condition. This is done by pulling SDA from HIGH to LOW while SCL is HIGH. Every slave on the bus sees the start condition.</li> <li>Next, the master sends the address of the slave (can be 7 or 10 bits but usually 7, so we’ll assume 7 from here on) with a read/write bit as the eighth bit.</li> <li>The slave with the requested address will acknowledge by pulling the SDA line LOW for one clock cycle.</li> <li>If the slave has more than one register, the master sends the register number of the register it wants to write to or read from.</li> <li>The master sends or receives the data in 8-bit chunks.</li> <li>After each 8-bit chunk of data transmits, the receiver acknowledges it by pulling SDA LOW for one clock cycle.</li> <li>When the master finishes, it sends the stop condition by pulling SDA from LOW to HIGH while SCL is HIGH.</li> <li>All changes on SDA line (except start and stop conditions) must occur when SCL is LOW.</li> </ul> <h3><strong>I2C Clock Rates and Speed<br /> </strong></h3> <p>Recall that earlier we established two different speeds. Standard mode sports a maximum clock rate of 100 kHz and fast mode a max clock rate of 400 kHz.</p> <p>There are also newer, faster versions of the I2C standard.</p> <p>Fast plus mode tops out at 1 MHz while high speed mode can hit 3.4 MHz. Ultra-fast mode is the newest kid on the block boasting speeds up to 5 MHz.</p> <p>One important note is that older I2C devices won’t operate at the higher speeds. Becasue of this, communication on the bus must take place at a rate that’s compatible with <em>all</em> the devices. So, the slowest device limits the top speed of the whole bus.</p> <h4><strong>I2C Speed and Bus Capacitance<br /> </strong></h4> <p>The speed also depends on bus capacitance. Recall that SDA and SCL are physical lines which are either traces on a PCB or a twisted pair cable. The fact that both scenarios have two conductors close in proximity that are separated by an insulator means there will be parasitic capacitance. Other factors also have an effect on parasitic capacitance.</p> <p>The maximum capacitive load for the I2C bus is 400 pF for standard and fast mode and 550 pF for fast mode plus. The number of devices on the bus and the length of the cables or board traces affect the capacitance. The lower the bus capacitance the better and the faster the speed will generally be for any given flavor of I2C.</p> <p>While most hobbyists probably won’t have to worry about going over the bus capacitance limit it is worth mentioning. There are a few work-arounds for this but since this is an introduction to I2C, that’s all we’ll say about bus capacitance.</p> <p>The chart below shows some of the I2C specs and info you’ll need to know about.</p> <p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4136" src="http://www.circuitcrush.com/wp-content/uploads/I2C-Specs-1.jpg" alt="I2C Specs" width="1280" height="720" srcset="https://www.circuitcrush.com/wp-content/uploads/I2C-Specs-1.jpg 1280w, https://www.circuitcrush.com/wp-content/uploads/I2C-Specs-1-300x169.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/I2C-Specs-1-1024x576.jpg 1024w, https://www.circuitcrush.com/wp-content/uploads/I2C-Specs-1-150x84.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/I2C-Specs-1-768x432.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/I2C-Specs-1-600x338.jpg 600w" sizes="(max-width: 1280px) 100vw, 1280px" /></p> <h2><strong>I2C Outro<br /> </strong></h2> <p>At first, I was going to have the headline say something corny like now you see I2C, but I decided to spare the lame attempt at humor and be boring.</p> <p>Anyway, like all things in the wonderful world of electronics there is more to say about the I2C standard and protocol.</p> <p>But, this is just an intro to I2C so we’re going to stop here to avoid information overload.</p> <p>Until next time, feel free to post your questions about I2C or share your projects that use I2C.</p> <h2 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h2> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-2354" src="http://www.circuitcrush.com/wp-content/uploads/arduino_uno_2-1.jpg" alt="Arduino board overview" width="372" height="237" srcset="https://www.circuitcrush.com/wp-content/uploads/arduino_uno_2-1.jpg 629w, https://www.circuitcrush.com/wp-content/uploads/arduino_uno_2-1-600x382.jpg 600w, https://www.circuitcrush.com/wp-content/uploads/arduino_uno_2-1-150x95.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/arduino_uno_2-1-300x191.jpg 300w" sizes="(max-width: 372px) 100vw, 372px" /></p> <a target="_blank" href="https://www.drpeterscode.com/index.php"><img src="https://www.circuitcrush.com/wp-content/plugins/dpabottomofpostpage/apixel1x1.jpg" ></a><table></table>]]></content:encoded> <wfw:commentRss>https://www.circuitcrush.com/i2c-tutorial/feed/</wfw:commentRss> <slash:comments>5</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">4119</post-id> </item> <item> <title>How LEDs Work</title> <link>https://www.circuitcrush.com/how-leds-work-intro/</link> <comments>https://www.circuitcrush.com/how-leds-work-intro/#comments</comments> <dc:creator><![CDATA[Brian]]></dc:creator> <pubDate>Thu, 16 Jul 2020 01:09:17 +0000</pubDate> <category><![CDATA[LEDs]]></category> <category><![CDATA[LED]]></category> <category><![CDATA[light emitting diode]]></category> <guid isPermaLink="false">https://www.circuitcrush.com/?p=4085</guid> <description><![CDATA[What are LEDs and how do LEDs Work? What is an LED? How do LEDs work? Many of us take the humble LED, or light emitting diode, for granted despite their ubiquity. LEDs not only show up in many of your projects, they find a home in a myriad of consumer and commercial products and […]]]></description> <content:encoded><![CDATA[<h1><strong>What are LEDs and how do LEDs Work?<br /> </strong></h1> <p>What is an LED? How do LEDs work?</p> <p>Many of us take the humble LED, or <strong><em>light emitting diode</em></strong>, for granted despite their ubiquity.</p> <p>LEDs not only show up in many of your projects, they find a home in a myriad of consumer and commercial products and are now making headway into lighting, driving incandescent and fluorescent lighting into obsolescence.</p> <p>Before we answer the question <em>what is an LED</em> or delve into how LEDs work, let’s do a quick history lesson on a few common types of light emitting devices you’re probably familiar with. After that, we’ll talk about what LEDs are made of and how they work. Then, we’ll get into the practical side of LEDs and how to use LEDs in your projects and designs.</p> <p><span id="more-4085"></span></p> <h2><strong>LED & Lighting History 101<br /> </strong></h2> <p>The incandescent light bulb was the first viable electric light on the scene (though arc lamps were demonstrated as early as 1835). Thomas Edison patented the device in 1879.</p> <p>Modern incandescent bulbs use a tungsten filament to emit light. A glass envelope encloses the filament and a vacuum or inert gas fills the envelope. Many incandescent bulbs connect to the light socket using a screw base, but other types of bases exist.</p> <p>Incandescent bulbs were the standard for a long time in homes and other places. They generate a fair amount of light and have an okay lifespan, as long as they’re not subject to abuse (like mechanical shock).</p> <p>The problem is that they’re energy hogs. Much of the electric power the bulbs consume converts to heat rather than light. If you’ve ever touched an incandescent bulb that’s been on for more than a few seconds you know what I mean.</p> <p>The bulbs are also fragile, and their lifespan is relatively short.</p> <p>Before the advent of LEDs, small incandescent lamps were often used as indicators in various consumer and commercial products. Other variations of these lamps exist including halogen bulbs, high pressure sodium (think street lights), mercury vapor and metal halide. While the last three are not truly incandescent bulbs, we’ll lump them in here anyway as they deserve a mention. You may not be familiar with them, but they show up in commercial and industrial applications.</p> <p>Fluorescent bulbs have been around since the 1930’s but the compact fluorescent bulb or CFL didn’t show up on the scene until much later.</p> <p>CFLs are much more energy efficient than incandescent bulbs and have a longer life with the potential to last years, but they are also fragile. In addition, they contain mercury which is highly toxic. Once you flip the switch to turn a CFL bulb on, they tend to take a minute or two to “warm up” before they reach peak brightness. To many, this is a disadvantage.</p> <p>LED bulbs boast a long life, are very efficient and contain no mercury. They are also more robust and not as fragile as incandescent lamps or CFLs. For these reasons, many people — including myself — have switched out the CFLs in their homes for LED bulbs as the prices keep falling. Another perk some LED bulbs sport are IoT capabilities. These “smart bulbs” can change colors (among other things) and are easy to control with an app on a smartphone.</p> <p>Finally, LED bulbs progressively get dimmer over thousands of hours of use rather than failing suddenly as incandescent lamps do.</p> <h2><strong>How LEDs Work<br /> </strong></h2> <p>While LED bulbs are replacing incandescent and fluorescent lighting in buildings and architectural design, most electronics enthusiasts are going to work with the smaller, more traditional LEDs. They’re the main topic of this post, so let’s talk about what an LED is and how LEDs work.</p> <p>Since an LED is a type of diode, the reader may wish to review <a href="https://www.circuitcrush.com/how-diodes-work/" target="_blank" rel="noopener noreferrer">How Diodes Work – An Introduction</a> for a quick recap on diodes and semiconductors.</p> <p>The basic operation of a typical LED follows below.</p> <p>When an LED is forward biased, electrons cross the <em>pn</em> junction from the n-type material to the p-type material. The electrons recombine with holes in the p-type material. LEDs work by emitting light when this recombination takes place because the electrons release photons (energy in the form of light). Figure 1 depicts this process.</p> <p style="text-align: center;"><img loading="lazy" decoding="async" class="size-full wp-image-4106 aligncenter" src="http://www.circuitcrush.com/wp-content/uploads/How-LED-Works.jpg" alt="What is an LED?" width="346" height="514" srcset="https://www.circuitcrush.com/wp-content/uploads/How-LED-Works.jpg 346w, https://www.circuitcrush.com/wp-content/uploads/How-LED-Works-202x300.jpg 202w, https://www.circuitcrush.com/wp-content/uploads/How-LED-Works-101x150.jpg 101w" sizes="(max-width: 346px) 100vw, 346px" /></p> <p style="text-align: center;"><strong><em>Figure 1: how an LED works.</em></strong></p> <p>This release of photons is due to fact that the electrons in the conduction band have a higher energy level than the holes in the valance band. To shed this excess energy, they release a little bit of heat and photons of electromagnetic radiation in various frequencies once they recombine with the holes. The frequency determines the color of light the LED emits. Some LEDs, like the type in a typical remote control, emit infrared radiation (or IR) which is invisible to the human eye.</p> <p>This process, known as electroluminescence, is the basis on how LEDs work.</p> <p>Different impurities are added during the doping process to establish the color of light the LED will emit.</p> <p>Here’s another fun fact: electroluminescence was first observed in 1907.</p> <h3 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h3> <p><img loading="lazy" decoding="async" class="wp-image-4238 aligncenter" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="318" height="121" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 318px) 100vw, 318px" /></p> <h2><strong>How LEDs are Made<br /> </strong></h2> <p>LEDs are semiconductors. However, designers usually do not use silicon or germanium because they are mainly heat producing materials and are poor at producing light.</p> <p>Compounds like gallium arsenide (GaAs), gallium arsenide phosphate (GaAsP), gallium nitride (GaN), and gallium phosphide (GaP) usually comprise many LEDs.</p> <p>GaAs LEDs produce IR radiation, while GaAsP LEDs emit either red or yellow light. GaP devices emit either green or red light and GaN LEDs emit blue light. There are other materials that also find use in LED fabrication.</p> <p>A plastic epoxy lens of the same color the device emits encloses the semiconductor chip that makes up the LED. The lens protects the semiconductor chip and also helps focus the light the LED emits so it is easier to see. This gives the typical bench-top LED its dome-like shape you’re familiar with.</p> <p>At first, a combination of red, green, and blue LEDs were used to make white light. Later phosphor based white LEDs showed up on the scene. Some of you may have a tri-color LED with red, green, and blue chips in the same package. Depending on the intensity of each color, a variety of different colors including white can be made.</p> <p>Newer white LEDs usually consist of a blue LED chip with a coating of some sort of luminescent phosphor material. This phosphor converts some of the blue light into red, orange, and yellow light. When these colors mix with the blue light from the LED chip, it appears to the human eye as though the device is emitting white light.</p> <h2><strong>How to Use LEDs – the Practical Stuff<br /> </strong></h2> <p>This introductory tutorial assumes the reader knows nothing about LEDs, so we’re going to start with the basics and go from there.</p> <p>Figure 2 depicts the schematic symbol for an LED.</p> <p><img loading="lazy" decoding="async" class="wp-image-4087 aligncenter" src="http://www.circuitcrush.com/wp-content/uploads/LED-Symbol.png" alt="How LEDs work - schematic symbol" width="338" height="106" srcset="https://www.circuitcrush.com/wp-content/uploads/LED-Symbol.png 1200w, https://www.circuitcrush.com/wp-content/uploads/LED-Symbol-300x94.png 300w, https://www.circuitcrush.com/wp-content/uploads/LED-Symbol-1024x321.png 1024w, https://www.circuitcrush.com/wp-content/uploads/LED-Symbol-150x47.png 150w, https://www.circuitcrush.com/wp-content/uploads/LED-Symbol-768x241.png 768w, https://www.circuitcrush.com/wp-content/uploads/LED-Symbol-600x188.png 600w" sizes="(max-width: 338px) 100vw, 338px" /></p> <p style="text-align: center;"><strong><em>Figure 2: schematic symbol for an LED.</em></strong></p> <p>Notice also that the two ends in figure 2 have labels. The anode is the positive side and the cathode is the negative side of the LED. Notice the perpendicular line at the right tip of the triangle. That’s the cathode. Remember this because the two terminals are often not labeled in schematics.</p> <p>To get the LED to light, the anode must be more positive than the cathode. To do so, we apply a voltage to the anode and tie the cathode to a lower voltage, like ground. This is how LEDs work.</p> <p>When looking at an actual LED, we can see that one of the legs is shorter than the other, as figure 3 shows. This is the cathode of the LED.</p> <p><img loading="lazy" decoding="async" class="wp-image-4088 aligncenter" src="http://www.circuitcrush.com/wp-content/uploads/LED-Cathode.jpg" alt="How to tell LED cathode" width="507" height="285" srcset="https://www.circuitcrush.com/wp-content/uploads/LED-Cathode.jpg 1280w, https://www.circuitcrush.com/wp-content/uploads/LED-Cathode-300x169.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/LED-Cathode-1024x576.jpg 1024w, https://www.circuitcrush.com/wp-content/uploads/LED-Cathode-150x84.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/LED-Cathode-768x432.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/LED-Cathode-600x338.jpg 600w" sizes="(max-width: 507px) 100vw, 507px" /></p> <p style="text-align: center;"><strong><em>Figure 3: the anode and cathode of an LED.</em></strong></p> <p>You will also notice a flat spot on the rim below the LED’s dome. This is another way to tell which terminal is the cathode if you cannot see the leads. For instance, if I need to look at an LED which has already been soldered to a board, I can tell which lead is the cathode by looking at this flat spot.</p> <p>LEDs have a forward (a.k.a. threshold) voltage below which they will not operate. This is usually denoted V<sub>F</sub> on data sheets and technical documents. The forward threshold voltage depends on the color of the LED but is significantly higher than the 0.7 V a silicon diode needs to conduct, regardless of the LED’s color. Conversely, the reverse breakdown voltage of an LED is considerably less than that of a typical silicon diode (usually around 3 V – 10 V for an LED).</p> <p>The redder the light emitting diode, the lower the forward voltage with IR LEDs coming in at the lowest with a forward voltage of about 1.2 V.</p> <p>In fact, the higher the frequency of radiation the LED emits, the higher this threshold forward voltage is. Since IR “light” has a low frequency with red coming in second-last, these LEDs have the lowest threshold voltages. Blue and white LEDs have the highest (blue light is higher in frequency than IR or red light) which is typically about 3.5 V. As with all components, there is a variation which depends on current, temperature and other factors.</p> <p>The nifty chart in figure 4 shows the typical forward voltages for various LED colors.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-4089 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/LED-Forward-Voltages.png" alt="LED forward Voltage Chart" width="803" height="391" srcset="https://www.circuitcrush.com/wp-content/uploads/LED-Forward-Voltages.png 803w, https://www.circuitcrush.com/wp-content/uploads/LED-Forward-Voltages-300x146.png 300w, https://www.circuitcrush.com/wp-content/uploads/LED-Forward-Voltages-150x73.png 150w, https://www.circuitcrush.com/wp-content/uploads/LED-Forward-Voltages-768x374.png 768w, https://www.circuitcrush.com/wp-content/uploads/LED-Forward-Voltages-600x292.png 600w" sizes="(max-width: 803px) 100vw, 803px" /></p> <p><strong><em>Figure 4: LED forward voltages for different colors. The chart shows the typical and max values. </em></strong></p> <p> </p> <p><img loading="lazy" decoding="async" class="size-full wp-image-4090 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/LED-Color-Spectrum.png" alt="the electromagnetic spectrum" width="691" height="409" srcset="https://www.circuitcrush.com/wp-content/uploads/LED-Color-Spectrum.png 691w, https://www.circuitcrush.com/wp-content/uploads/LED-Color-Spectrum-300x178.png 300w, https://www.circuitcrush.com/wp-content/uploads/LED-Color-Spectrum-150x89.png 150w, https://www.circuitcrush.com/wp-content/uploads/LED-Color-Spectrum-600x355.png 600w" sizes="(max-width: 691px) 100vw, 691px" /></p> <p><strong><em>Figure 5: the electromagnetic spectrum with an emphasis on visible light. We can see IR right below red on the frequency spectrum with blue and purple on the high end of the visible portion of the spectrum. All the colors combined make white light.</em></strong></p> <h3><strong>LED Circuits and Current<br /> </strong></h3> <p>Light emitting diodes have a maximum current rating, so you’ll always need a series resistor when using LEDs in your circuits. More on this in a minute.</p> <p>The brightness of an LED is typically linear with current. That is, the more current you push through it, the brighter the LED gets. Too much current and the LED releases its magic smoke. Or the excessive current will reduce the life span of the device if it isn’t enough to destroy it. Too little current and the LED doesn’t light at all or is very dim.</p> <p>LEDs do have a finite lifespan, even if you use the right amount of current. It’s long though and something like 11+ years of continuous use.</p> <p>Reducing the current will increase the lifespan. The relationship between current and LED lifespan is exponential, so if we reduce the current by 50% the lifespan can increase by something like a factor of 50. This works both ways, so as we already know, too much current greatly reduces LED life.</p> <p>A 50% reduction in brightness – and therefore current (remember the current-brightness relationship is linear) – is actually not very noticeable to humans but it will extend the life of an LED significantly. It’ll also be helpful if your project runs on batteries and will extend their life.</p> <p>Earlier, we said you always need to use a current limiting resistor with LEDs, but how do we pick that resistor?</p> <p>Circuits exist with values ranging from 100 Ohms to 1k Ohms or more, but 220 – 240 Ohms are common values that are often acceptable.</p> <p>Let’s take a closer look at a simple circuit with an LED.</p> <p><strong><u>Ex:</u></strong> Consider the simple circuit in figure 6. The LED may look blue, but your eyes deceive you – it is actually red. What value resistor do we need to safely operate the LED without sending it to a premature grave?</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-4091 aligncenter" src="http://www.circuitcrush.com/wp-content/uploads/LED-Circuit.jpg" alt="simple LED circuit" width="357" height="217" srcset="https://www.circuitcrush.com/wp-content/uploads/LED-Circuit.jpg 357w, https://www.circuitcrush.com/wp-content/uploads/LED-Circuit-300x182.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/LED-Circuit-150x91.jpg 150w" sizes="(max-width: 357px) 100vw, 357px" /></p> <p style="text-align: center;"><strong><em>Figure 6: LED circuit. We need to find a good value for R.</em></strong></p> <p><strong><u>Answer:</u></strong></p> <p>It’s a red LED so we’re going to use a forward voltage drop of 1.5 V. We want to keep our LED comfortable, so even though the data sheet says the maximum current is 20 mA we’re going to run it at about 10 mA as it should still be sufficiently bright for our purposes.</p> <p>The circuit has a 9 V source and the LED will drop 1.5 V, so the resistor will drop 9 V – 1.5 V = 7.5 V.</p> <p>We know we want 10 mA, so we’ll use Ohm’s Law: 7.5 V / 0.010 A = 750 Ohms for our resistor.</p> <p>We’re lucky because 750 Ohms is a standard value for resistors with 5% tolerance. If our calculation gives us a non-standard value like 703 Ohms, we just pick a value that’s close. In this case, we can choose between the 750 Ohm resistor or a 680 Ohm resistor. Either of these would make the current close enough to our desired value.</p> <p>In general, the formula to find the correct resistor value in a circuit like this is:</p> <p><strong>Eq. 1</strong> (V<sub>SOURCE</sub> – V<sub>F</sub>) / I<sub>DESIRED </sub>= R</p> <p>Or the source voltage minus the LED’s forward voltage divided by the amount of current we desire gives us our resistor value.</p> <p>This is basic circuit analysis 101. For a good review on basic circuit analysis see <a href="https://www.circuitcrush.com/circuit-analysis/" target="_blank" rel="noopener noreferrer">Simple Circuit Analysis Techniques You Should Know</a>.</p> <p>Here’s something to think about: if our source voltage were lower, would the resistor value need to be bigger, smaller, or the same for 10 mA to flow through the LED?</p> <h3><strong>Pulsing LEDs<br /> </strong></h3> <p>If for some reason you need to run an LED at a current rating at or above the max, you can pulse the LED. To the human eye, the LED will appear to be on all the time (assuming the pulse rate is high enough). But the LED will actually switch on and off, giving the LED die time to cool.</p> <p>One should consult the data sheet for details, but, as an example, if it says the max DC current is 10 mA you may be able to feed it 40 mA using a pulse with a 25% duty cycle (on vs off time). Of course, the pulses need to be short enough to prevent overheating and degradation of the LED.</p> <p>This is an introduction to using LEDs, so that’s all were going to say about running LEDs like this for now.</p> <h3><strong>Using Multiple LEDs<br /> </strong></h3> <p>Our circuit with one LED and a resistor is pretty straight forward, but what if we have more than one LED?</p> <p>You can’t parallel multiple LEDs with a single resistor like we see in figure 7.</p> <p>This is because the LED with the lower forward voltage will pull the voltage down to that level. Remember, the voltage in a parallel circuit is the same across all legs of the circuit. In this case, the red LED pulls the parallel combination down to 1.5 V, so the blue LED doesn’t light. Even if you have two LEDs of the same color this is still not a good idea and may not work because the LEDs may not be perfectly identical.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-4092 aligncenter" src="http://www.circuitcrush.com/wp-content/uploads/Using-Multiple-LEDs.jpg" alt="LEDs in parallel" width="460" height="269" srcset="https://www.circuitcrush.com/wp-content/uploads/Using-Multiple-LEDs.jpg 460w, https://www.circuitcrush.com/wp-content/uploads/Using-Multiple-LEDs-300x175.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Using-Multiple-LEDs-150x88.jpg 150w" sizes="(max-width: 460px) 100vw, 460px" /></p> <p><strong><em>Figure 7: the blue LED in this circuit doesn’t light because the red one pulls the voltage at the node near the top down to 1.5 V. This is because LEDs act like zener diodes which are another special type of diode often used for voltage regulation.</em></strong></p> <p>There are a couple options to using multiple LEDs in a circuit correctly.</p> <p>First, each LED can have its own series resistor. This is the easiest and most common way to do things.</p> <p>If you are desperate to save resistors, you can also put multiple LEDs in series with a resistor as in figure 8. The downside is that your source voltage needs to be higher than the sum of all the LEDs’ forward voltages. This can be a problem when using more than a few LEDs. The upshot (other than saving a resistor or two) is that equal current will flow through all the LEDs since they’re in series.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-4093 aligncenter" src="http://www.circuitcrush.com/wp-content/uploads/Using-Multiple-LEDs-Correct.jpg" alt="LEDs in series" width="451" height="314" srcset="https://www.circuitcrush.com/wp-content/uploads/Using-Multiple-LEDs-Correct.jpg 451w, https://www.circuitcrush.com/wp-content/uploads/Using-Multiple-LEDs-Correct-300x209.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Using-Multiple-LEDs-Correct-150x104.jpg 150w" sizes="(max-width: 451px) 100vw, 451px" /></p> <p><strong><em>Figure 8: multiple LEDs in series with a resistor. The source voltage needs to be higher than the LEDs’ combined forward voltage, which in this case is 5 V. This set up also makes sure equal current flows through each LED.</em></strong></p> <h2><strong>Other Uses of LEDs<br /> </strong></h2> <p>Another common application of LEDs that may show up in your projects and gadgets you buy is the 7-segment display.</p> <p>Think of an old alarm clock with red numbers. These numbers are usually 7-segment displays which are in turn made of small LEDs. The appropriate segments are lit according to the number that needs to be displayed. Figure 9 depicts a typical 7-segent display. Displays that are capable of showing more than one digit are also available in one convenient package. Of course, similar devices with more than 7 segments in different patterns are available for displaying letters and different characters.</p> <p><img loading="lazy" decoding="async" class="wp-image-4094 aligncenter" src="http://www.circuitcrush.com/wp-content/uploads/7-Segment-Display.jpg" alt="7-Segment-Display" width="237" height="237" srcset="https://www.circuitcrush.com/wp-content/uploads/7-Segment-Display.jpg 500w, https://www.circuitcrush.com/wp-content/uploads/7-Segment-Display-300x300.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/7-Segment-Display-150x150.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/7-Segment-Display-100x100.jpg 100w" sizes="(max-width: 237px) 100vw, 237px" /></p> <p style="text-align: center;"><strong><em>Figure 9: a typical 7-segment display.</em></strong></p> <p>One thing that may surprise those new to electronics is that an LED can find use as a photo detector. They are not extremely sensitive and respond best to the color of light they’re designed to emit but they’re cheap and can be used this way in certain applications.</p> <p>LEDs also show up in optoisolators. These devices are good for electrically isolating different parts of circuits. Think of an optoisolator as a relay that uses light instead of a mechanical contact on the inside. Figure 10 shows such a device.</p> <p> </p> <p><img loading="lazy" decoding="async" class="wp-image-4095 aligncenter" src="http://www.circuitcrush.com/wp-content/uploads/Optoisolator.jpg" alt="Optoisolator" width="544" height="196" srcset="https://www.circuitcrush.com/wp-content/uploads/Optoisolator.jpg 906w, https://www.circuitcrush.com/wp-content/uploads/Optoisolator-300x108.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Optoisolator-150x54.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Optoisolator-768x276.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/Optoisolator-600x216.jpg 600w" sizes="(max-width: 544px) 100vw, 544px" /></p> <p><strong><em>Figure 10: an optoisolator (a) and schematic representation of its insides (b). Terminals 3 and 4 connect to a phototransistor which has a light-sensitive base.</em></strong></p> <h2>How LEDs Work: Summary & Recap<em><strong><br /> </strong></em></h2> <p>It’s time to try something new. All the skimmers will love this (though you should read the whole article). Below is a quick summary and recap of what we talked about.</p> <ul> <li>An LED or light emitting diode is a semiconductor device that emits light.</li> <li>LED lighting is starting to replace incandescent, fluorescent and other forms of lighting in homes and other buildings.</li> <li>The color of light the LED emits depends on the material the LED is made of.</li> <li>The cathode of an LED is the negative side and the anode is the positive side. To identify the cathode, look for the shorter leg and/or the flat spot on the epoxy case right below the dome. On a schematic, the cathode is identified by the perpendicular line on the tip of the triangle, just like a regular diode schematic symbol.</li> <li>IR LEDs have the lowest forward (or threshold) voltage with red coming in second lowest. Blue and white LEDs have the highest. The forward voltages typically range from 1.2 V on the low end to 3.5 V – 4 V on the high end.</li> <li>You NEED to use a series resistor with an LED to limit the current so it doesn’t burn out prematurely. The resistor’s value depends on the LED but it’s usually not hard to calculate. For details, see the example above.</li> <li>LEDs can often be pulsed which may allow you to use a higher current than what the data sheet recommends.</li> <li>It is not a good idea to put LEDs in parallel unless they each have their own series resistor.</li> <li>Several LEDs can be wired in series in with one resistor but the supply voltage needs to be high enough to overcome the sum of all the LED’s forward voltages plus a little more for the resistor drop.</li> <li>LEDs find use in 7-segment displays, optoisolators, and other things. An LED can make a cheap photodetector though it’s not extremely sensitive and responds best to the color of light the LED was designed to emit.</li> </ul> <h2><strong>Shedding Some Light on How LEDs Work<br /> </strong></h2> <p>Now that we’ve answered the questions <em>what is an LED?</em> and <em>how do LEDs work?</em></p> <p>It’s time to go forth and light the way…</p> <p>…Ok, I just had to put that bad pun in there.</p> <p>On a more serious tip, we’ve only scratched the surface. Just like all things in the world of electronics there is a lot more to say about LEDs. Many applications exist for them. There are other, newer types of LEDs like organic light emitting diodes (OLEDs) which can be used to make flexible displays. There’s a lot more behind the workings of even a typical bench top LED that we didn’t discuss in this introductory tutorial. And when it comes to diodes in general, there’s a whole myriad of types and applications and a ton to say about each.</p> <p>For now though, we have a good starting point on LEDs, especially for those new to electronics.</p> <p>Drop a comment and tell us about your latest super-cool projects or experiments involving LEDs. I’m sure we’d all love to hear about it!</p> <h2 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h2> <p><img loading="lazy" decoding="async" class="wp-image-4238 aligncenter" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="536" height="204" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 536px) 100vw, 536px" /></p> <a target="_blank" href="https://www.drpeterscode.com/index.php"><img src="https://www.circuitcrush.com/wp-content/plugins/dpabottomofpostpage/apixel1x1.jpg" ></a><table></table>]]></content:encoded> <wfw:commentRss>https://www.circuitcrush.com/how-leds-work-intro/feed/</wfw:commentRss> <slash:comments>1</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">4085</post-id> </item> <item> <title>C Programming Tutorial 9: Writing Functions in C</title> <link>https://www.circuitcrush.com/c-programming-tutorial-9-writing-functions/</link> <comments>https://www.circuitcrush.com/c-programming-tutorial-9-writing-functions/#respond</comments> <dc:creator><![CDATA[Brian]]></dc:creator> <pubDate>Fri, 19 Jun 2020 01:13:40 +0000</pubDate> <category><![CDATA[C Programming]]></category> <category><![CDATA[C programming]]></category> <category><![CDATA[functions]]></category> <guid isPermaLink="false">https://www.circuitcrush.com/?p=4067</guid> <description><![CDATA[C Programming Tutorial 5: Functions in C gives a short introduction to functions and also quickly glosses over function definitions and writing functions in C. While this is alright, I realize that there are many people new to C programming and that a better, more in-depth treatment of writing functions in C is in order. […]]]></description> <content:encoded><![CDATA[<p><a href="https://www.circuitcrush.com/c-programming-c-functions-5/" target="_blank" rel="noopener noreferrer">C Programming Tutorial 5: Functions in C</a> gives a short introduction to functions and also quickly glosses over function definitions and writing functions in C.</p> <p>While this is alright, I realize that there are many people new to C programming and that a better, more in-depth treatment of writing functions in C is in order. Enter this article, which goes into a bit more detail on writing your own C functions.</p> <p><span id="more-4067"></span></p> <h1><strong>Writing Functions in C<br /> </strong></h1> <p>We know that C comes with a lot of built-in functions which can save you time and work, but what if none of them do what you need?</p> <p>The answer is to write your own C function.</p> <p>These are referred to as user defined functions and this lesson will be a more detailed introduction to user defined functions, or simply, writing your own functions.</p> <p>The functions you write will be the bulk of a lot of your programs so it’s important to understand how this works. Luckily, creating your own functions is not that difficult.</p> <h2><strong>Quick Review on Functions in C and Abstractions<br /> </strong></h2> <p>Let’s start by doing a quick review on functions and say a few ’abstract’ words. If you need more of a review, I urge you to go back to the first lesson on functions.</p> <p>A common abstraction in the world of programming, computers, and electronics is the black box model. This black box has an input and an output. We don’t know what sort of circuitry, code, or combination of both is inside the box, all we know is the box takes an input, does some processing, and produces an output, sort of like a typical function.</p> <p> </p> <p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4069" src="http://www.circuitcrush.com/wp-content/uploads/Writing-Fucntions-in-C.jpg" alt="Writing-Fucntions-in-C" width="778" height="273" srcset="https://www.circuitcrush.com/wp-content/uploads/Writing-Fucntions-in-C.jpg 778w, https://www.circuitcrush.com/wp-content/uploads/Writing-Fucntions-in-C-300x105.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Writing-Fucntions-in-C-150x53.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Writing-Fucntions-in-C-768x269.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/Writing-Fucntions-in-C-600x211.jpg 600w" sizes="(max-width: 778px) 100vw, 778px" /></p> <p><strong><em>Figure 1: thinking of functions as a black box with an input and an output is a good abstraction.</em></strong></p> <p>Another abstract way to visualize functions that many of us may be familiar with is to think of them as kind of like a cake mix. When you buy a cake mix, you just add water and maybe some butter, and using the stuff in the box, you end up with a cake. If you’re a novice baker, you may not know what is inside the cake mix, nor care.</p> <p>Sure, you could grab some flour, sugar, salt and some other ingredients and mix them all together in the right proportions yourself — especially if you’re a baker with some experience, but it’s way easier to use the cake mix. The mix ‘abstracts away’ most of the complexity of baking a cake.</p> <p>But, since the black box model seems to be the dominant abstraction in the world of software, we’ll stick with that.</p> <p>Our black box has an input and an output. We can’t see what goes on inside the box and we don’t necessarily care. All we know is that our box takes an input, performs some sort of processing on the inside, and then gives us an output.</p> <h2><strong>Writing Your Own Functions in C<br /> </strong></h2> <p>But now we want to write our own functions, so it’s time to take a peek inside the box. We’ll not only see what’s going on but design how the machinery on the inside works and get it to do what we want it to do, because there’s a certain satisfaction about being a control freak.</p> <p>To write our own functions, we’ll need to think about the inputs, the outputs, and most importantly, the algorithm which is the ‘machinery’ so to speak inside of the box that makes the magic happen.</p> <p>Before we start writing our own functions, we need to know the proper syntax for user defined functions, so let’s jump right into that.</p> <p>Take a peek at figure 2. What we see here is the basic form for a function definition. The function definition tells us how our functions works. You can say that the function definition is the function itself. It defines the inputs, outputs, and contains the algorithm for how the function operates.</p> <p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-4071" src="http://www.circuitcrush.com/wp-content/uploads/Function-Definition.jpg" alt="Function-Definition" width="814" height="336" srcset="https://www.circuitcrush.com/wp-content/uploads/Function-Definition.jpg 814w, https://www.circuitcrush.com/wp-content/uploads/Function-Definition-300x124.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Function-Definition-150x62.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Function-Definition-768x317.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/Function-Definition-600x248.jpg 600w" sizes="(max-width: 814px) 100vw, 814px" /></p> <p><em><strong>Figure 2: function definition template/model.</strong></em></p> <p>All the functions you use have a function definition living somewhere, even the ones that come with the compiler.</p> <p>Refer to figure 2. Let’s start our discussion on function definition syntax by looking at the function’s output, which is also known as the return type.</p> <p>When we say type, we’re just referring to the data type it returns such as an <em>int</em> or <em>float</em>. By now you should be familiar with many of C’s data types.</p> <p>By return, we mean the stuff the function returns to the calling function. So, if the <em>main()</em> function in your program calls or invokes another function, which is quite common, the called function will often return some sort of value to <em>main()</em> or whatever function called it. So, when a function creates an output, or a value, it gives that value back to the caller.</p> <p>It’s kind of like calling a friend and leaving them a message asking a question. They’ll get the call and the message, think of a response, and then call you back with that response.</p> <p>So, the return type is just the data type the function returns. For example, <em>sqrt()</em> which is part of the <em>math.h</em> header file, returns a double. In case you didn’t know, this function takes the square root of a number.</p> <p>So, when we’re writing a function in C, we need to define what data type it’s going to return.</p> <p>However, not all functions return a value. Sometimes they just do something and that’s it. If you’re into Arduino, you know you program in a language similar to C and you’re familiar with <em>setup()</em> and <em>loop()</em>. These two essential Arduino functions don’t return anything. Another example is the Arduino <em>delay()</em> function. It doesn’t return anything — all it does is wait a certain number of milliseconds and that’s it.</p> <h3 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h3> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="342" height="130" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 342px) 100vw, 342px" /></p> <p>When writing a function definition for a function that doesn’t return anything , we’ll use the word <em>void</em> instead of a data type to indicate the function has no return. The snippet below shows such an example.</p> <pre>void example_function (int number) { //function body goes here }</pre> <p>Next, we can see the name of the function in figure 2. It’s a good idea to pick something meaningful, maybe like something that describes what the function does instead of using a generic name like function1 or my_function. For example, if I want to create a function that prints smiley faces, I may call it something like smileyPrinter.</p> <p>Next, we see a set of parentheses. Inside dwell the function’s parameters. This is the stuff the function takes in and does its magic on. In other words, these are the function’s inputs. Some functions, like <em>getchar()</em> take no inputs. Arduino functions <em>setup()</em> and <em>loop()</em> also take no inputs. Our old friend <em>void </em>shows up again here. When writing a function like this, we just put the word <em>void</em> in the parentheses, like below.</p> <pre>int another_example_function (void) { //function body goes here }</pre> <p>Some functions neither return a value nor take any inputs. We can write such a function like this:</p> <pre>void sad_function (void) { //function body goes here }</pre> <p>Many functions do take inputs. For example, <em>sqrt()</em> in C takes a double and <em>delay()</em> in Arduino takes an integer.</p> <p>When writing your own user defined function, you’ll need to specify what inputs it will take.</p> <p>First, it’s interesting to know that you can write a function that takes more than one input or parameter.</p> <p>Second, each input has two parts: the data type and the name. As before, the data type can be any valid type such as an <em>int</em>, <em>float</em>, <em>char</em> etc. The name is how you’ll refer to the value when you write the body, or the actual algorithm, of the function. If you need more than one parameter, separate them by commas.</p> <p>Refer back to figure 2. Next, we see a set of curly braces. Inside those braces is the body of the function which can be as short as a few lines of code or hundreds of lines or more. This is the algorithm and is the meat of the function. It’s the stuff inside the black box we keep talking about.</p> <p>Let’s do an easy example similar to the example from the last C tutorial on functions. Say we want to write a function that prints an arbitrary number of plus signs for some reason. Maybe the number of plus signs comes from a sensor reading, or maybe a user enters the number on a keyboard or touchscreen — it really doesn’t matter.</p> <pre>void plusPrinter (int plus_count) { for (int i=0; i< plus_count; i++) putchar('+'); }</pre> <p>Our function doesn’t really need to return anything, so we’re just going to put <em>void</em> in front as the return type.</p> <p>Next, we give it a descriptive name (plusPrinter) that gives us an idea of what our function will do.</p> <p>Now, we need to tell it what kind of datatype it will take in. Since we can’t print a fraction of a plus sign it makes sense to pick an integer data type. We’ll also give that integer a name that is somewhat descriptive. In the body of our function, when we need to refer to the value passed into that function, we’ll use the name plus_count.</p> <p>Then we have our first curly brace followed by the body of the function which is the actual algorithm that does the work. By now you should know all about <em>for</em> loops and printing things, so I won’t rehash that. Finally, we close with the 2<sup>nd</sup> curly brace.</p> <p>Let’s write another, more useful function, because, you know, printing a bunch of plus signs is boring.</p> <p>Say we have two temperature sensors in two different locations like one in the back of your refrigerator and another in the front, because, for some reason in the 2020’s it’s still impossible to build a fridge without wild temperature gradients. It really sucks when the food in the back is frozen while the stuff in the front is warm. Because of this, we want to take the temperature in each location and then average the two different temperatures. We have an ingenious idea on how to fix this age-old problem and will make millions if we solve it, so let’s go for it.</p> <p>We want to be more exact, so instead of using integers we’ll use floats. Also, our user defined function will need to take in 2 floats and return the result to the calling function. Here’s our function definition:</p> <pre>float fridge_temp_monitor (float reading1, float reading2) { float average = (reading1 + reading2) / 2; return average; }</pre> <p>Let’s step through it.</p> <p>First, we specify a return type. This time, it’s a float.</p> <p>Next, we give the function a meaningful name.</p> <p>Now we define the parameters. Since it has more than one parameter, we need to separate each one with a comma. We also use floats for the parameter and give them meaningful names.</p> <p>Unlike the last function, this one actually returns something. It returns the average of the two sensor readings, so we use the <em>return</em> statement. It’s important to note the function returns the <em>value</em> of the variable average, not the <em>name </em>of the variable.</p> <p>Let’s use our function in a real C program. I don’t have a circuit with sensors wired up in my refrigerator, so I’ll just assign reasonable values to the two variables and pretend they’re coming from the sensors.</p> <pre>#include <stdio.h> float fridge_temp_monitor (float reading1, float reading 2) { float average = (reading 1 + reading 2) / 2; return average; } int main(void) { float num1 = 35.0; float num2 = 40.0; float average = fridge_temp_monitor (num1, num2); printf("%f", average); return 0; }</pre> <p>There are a few things to note about this short program.</p> <p>First, there’s no function prototype. It turns out that we don’t have to use one if we have the function definition appear before the first function call, though it still may not be a bad idea to use a prototype.</p> <p>Second, the function call appears on the right of the assignment operator and assigns whatever value it returns to the variable <em>average</em>.</p> <p>Last, in the definition we named the parameters reading1 and reading2 but when we called the function, we passed it num1 and num2, which the function interprets as reading1 and reading2 when it does its processing.</p> <h2><strong>Function Definition Recap<br /> </strong></h2> <p>Let’s do a quick review of writing functions in C (a.k.a. user defined functions) and function definitions.</p> <ul> <li>First, we have the return type which is the data type of the value that the function we write returns. Sometimes, our function may not return anything so we use <em>void</em> instead of a data type in this case.</li> <li>Next, we have the function name. Try to make it meaningful.</li> <li>Then, there’s the parameter list, which are the inputs the function takes in or accepts. Here, we define the data types and names of the inputs. When there’s more than one parameter, we separate them with a comma. If our function doesn’t take any parameters, we just put <em>void</em> in the parentheses.</li> <li>Then, there is the body of the function. This is the actual algorithm that does the work. If we want to return a value, we use the keyword <em>return</em>.</li> </ul> <h2><strong>Function Definitions in C: Closing Thoughts<br /> </strong></h2> <p>Now we’ve taken a closer look at function definitions in C and writing functions. But there’s still more to say on functions. We’ll pick functions up again at a later time.</p> <p>Meanwhile, drop a comment and tell me about the functions you write. What are they for? How many lines of code? Or, just tell me about your latest project. I’d love to hear from you either way!</p> <h2 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h2> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="541" height="206" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 541px) 100vw, 541px" /></p> <a target="_blank" href="https://www.drpeterscode.com/index.php"><img src="https://www.circuitcrush.com/wp-content/plugins/dpabottomofpostpage/apixel1x1.jpg" ></a><table></table>]]></content:encoded> <wfw:commentRss>https://www.circuitcrush.com/c-programming-tutorial-9-writing-functions/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">4067</post-id> </item> <item> <title>Intro to DC Motors</title> <link>https://www.circuitcrush.com/intro-dc-motors/</link> <comments>https://www.circuitcrush.com/intro-dc-motors/#comments</comments> <dc:creator><![CDATA[Brian]]></dc:creator> <pubDate>Tue, 21 Apr 2020 02:19:16 +0000</pubDate> <category><![CDATA[Electric Motors]]></category> <category><![CDATA[DC Motors]]></category> <guid isPermaLink="false">https://www.circuitcrush.com/?p=3995</guid> <description><![CDATA[If your project involves any sort of movement, you’re most likely going to use some sort of DC motor to accomplish said movement. And if you’re into building or experimenting with robots, the use of DC motors is a necessity. There is a lot to say about DC motors and complete books exist on this […]]]></description> <content:encoded><![CDATA[<p>If your project involves any sort of movement, you’re most likely going to use some sort of DC motor to accomplish said movement. And if you’re into building or experimenting with robots, the use of DC motors is a necessity.</p> <p>There is a lot to say about DC motors and complete books exist on this exciting subject. This post is going to cover the ones that are most likely to cross your bench. Also, this will be an introductory article where we’ll take a look at each type of DC motor from a bird’s eye view and cover the basics.</p> <p>The various DC motors will get a more in-depth treatment each with their own article in the future.</p> <p>Enough said, let’s acclimate ourselves with some common DC motors!</p> <p><span id="more-3995"></span></p> <h1><strong>Intro to DC Motors<br /> </strong></h1> <h2><strong>DC Motors and AC Motors<br /> </strong></h2> <p>Some of you may be wondering about AC motors and asking yourselves why we’re only covering DC motors in this article.</p> <p>While a few of us may work with AC motors, most of us will gravitate towards DC motors unless we’re working on a project involving movement that plugs into an AC outlet. As far as robotics goes, it is definitely possible to build a robot with an AC motor, but if you do the length of the power cord will place a limit on your creation’s movement. Sure, you could use batteries, but you’d need some pretty hefty batteries and more circuitry to convert DC into AC which increases cost and complexity.</p> <p>In reality, AC motors are an essential part of modern life. Some AC motors have huge horsepower ratings of 100,000+. They find use in many commercial and industrial applications and are the workhorses of our society. And some of the appliances in your home use them, though brushless DC motors are starting to creep in and replace the AC versions in many home appliance applications. Needless to say, I’ll probably cover AC motors in a future post.</p> <p>One last thing to note about motors in general is that an electric motor and an electric generator are one in the same. If you spin the shaft of an electric motor, a voltage will appear at the terminals. And, as we already know, if we apply a voltage to the terminals of a motor the shaft will spin.</p> <h2><strong>Brushed DC Motors<br /> </strong></h2> <p>Brushed motors are the oldest type of DC motor (around since late the 1800’s) with origins that trace back to Michael Faraday, so we’ll take a look at them first.</p> <p>This type of DC motor consists of three main parts: a stator, armature and commutator. Figure 1 depicts a DC motor of this type. Figure 2 shows the insides of a smaller motor, one similar to the type you may use in a project. Note that brushed DC motors also find their way into commercial and industrial applications.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3996 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Brushed-DC-Motor.jpg" alt="Brushed-DC-Motor" width="300" height="300" srcset="https://www.circuitcrush.com/wp-content/uploads/Brushed-DC-Motor.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Brushed-DC-Motor-150x150.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Brushed-DC-Motor-100x100.jpg 100w" sizes="(max-width: 300px) 100vw, 300px" /></p> <p><strong><em>Figure 1: a brushed DC motor for use in commercial and industrial applications.</em></strong></p> <p> </p> <p><img loading="lazy" decoding="async" class=" wp-image-3997 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/DC-Motor-Inside.jpg" alt="DC-Motor-Inside" width="485" height="364" srcset="https://www.circuitcrush.com/wp-content/uploads/DC-Motor-Inside.jpg 600w, https://www.circuitcrush.com/wp-content/uploads/DC-Motor-Inside-300x225.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/DC-Motor-Inside-150x113.jpg 150w" sizes="(max-width: 485px) 100vw, 485px" /></p> <p><strong><em>Figure 2: the insides of a small brushed DC motor.</em></strong></p> <p> </p> <p>A different view can be seen in figure 3 below.</p> <p> </p> <p><img loading="lazy" decoding="async" class=" wp-image-3998 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Inside-Brushed-DC-Motor-2.jpg" alt="Inside-Brushed-DC-Motor-2" width="561" height="421" srcset="https://www.circuitcrush.com/wp-content/uploads/Inside-Brushed-DC-Motor-2.jpg 640w, https://www.circuitcrush.com/wp-content/uploads/Inside-Brushed-DC-Motor-2-300x225.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Inside-Brushed-DC-Motor-2-150x113.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Inside-Brushed-DC-Motor-2-600x450.jpg 600w" sizes="(max-width: 561px) 100vw, 561px" /></p> <p><strong><em>Figure 3: another view of the inside of a DC motor with brushes. Here we can see the stator which is made from the magnets covering the inside of the case.</em></strong></p> <p>As we can see from figure 3, a series of permanent magnets comprise the stator. Figure 2 shows us that the rotor of this particular DC motor has windings on it with the commutator at the end.</p> <p>The brushes (not shown in figure 2 or 3) are usually carbon or copper. They transfer electricity to the commutator and therefore make physical contact with it. This ultimately wears them down which is a draw back. Bigger, more expensive motors have replaceable brushes. Regardless, the brushes also cause a lot of electromagnetic interference due to sparking and arcing, which is another downside of this type of DC motor.</p> <p>The image in figure 4 gives a good view of how it all fits together with the brushes. In figure 5 we get a close up of what brushes look like.</p> <p> </p> <p><img loading="lazy" decoding="async" class=" wp-image-3999 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/DC-Motors.gif" alt="DC-Motors" width="483" height="342" /></p> <p><strong><em>Figure 4: cutaway view of DC motor with brushes visible.</em></strong></p> <p> </p> <p><img loading="lazy" decoding="async" class=" wp-image-4000 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/DC-Motor-Brushes.jpg" alt="DC-Motor-Brushes" width="322" height="322" srcset="https://www.circuitcrush.com/wp-content/uploads/DC-Motor-Brushes.jpg 432w, https://www.circuitcrush.com/wp-content/uploads/DC-Motor-Brushes-300x300.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/DC-Motor-Brushes-150x150.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/DC-Motor-Brushes-100x100.jpg 100w" sizes="(max-width: 322px) 100vw, 322px" /></p> <p><strong><em>Figure 5: close-up of typical DC motor brushes.</em></strong></p> <p>Even though brushes present some disadvantages to the motor, these devices are easily reversible, plus they sport high starting torque and high speed with easy control.</p> <h2><strong>Brushless DC Motors<br /> </strong></h2> <p>Brushless DC motors (a.k.a. BLDC motors or BLDCMs) are one of the newer kids on the block as far as motors go.</p> <p>As their name implies, they have no brushes. This makes them more efficient — brushes making contact with the commutator causes friction losses. This lack of brushes also makes them easier to maintain, and BLDC motors produce much less electromagnetic interference than their brush-bearing cousins because brushes cause arcing and sparking. This also makes them suitable for use in environments with flammable vapors and dust.</p> <p>On the downside, they tend to be more expensive pound for pound and control is more complex requiring speed controllers or other special circuitry.</p> <p>Internally, they are similar to the brush-toting variety, but with no brushes they need no commutator. Many brushless DC motors contain a Hall effect sensor or Hall effect IC to help with control. Figure 6 depicts the insides of two different types of BLDCMs.</p> <p> </p> <p><img loading="lazy" decoding="async" class="size-full wp-image-4001 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Inside-Brushless-DC-Motor.png" alt="Inside-Brushless-DC-Motor" width="896" height="329" srcset="https://www.circuitcrush.com/wp-content/uploads/Inside-Brushless-DC-Motor.png 896w, https://www.circuitcrush.com/wp-content/uploads/Inside-Brushless-DC-Motor-300x110.png 300w, https://www.circuitcrush.com/wp-content/uploads/Inside-Brushless-DC-Motor-150x55.png 150w, https://www.circuitcrush.com/wp-content/uploads/Inside-Brushless-DC-Motor-768x282.png 768w, https://www.circuitcrush.com/wp-content/uploads/Inside-Brushless-DC-Motor-600x220.png 600w" sizes="(max-width: 896px) 100vw, 896px" /></p> <p><strong><em>Figure 6: inside a typical brushless DC motor. The one in part (a) is the inrunner type meaning the rotor is on the inside. Part (b) shows the outrunner variety with the rotor on the outside.</em></strong></p> <p>Stepper motors are also brushless, but we’re going to treat them separately later in this post.</p> <p>As we can see from figure 6, the BLDC motor’s rotor supports permanent magnets (an even number of them). It’s the magnets that rotate in this type of motor while the windings stay put. This helps keep the windings in tact as they don’t suffer from the physical forces involving fast rotation.</p> <p>The more magnetic poles the rotor has the smaller the rotational steps are. This results in less torque ripple. Don’t get confused by the term “rotational steps.” Unlike the stepper we’re going to learn about in a minute, the brushless DC motor is meant for continuous rotation. But, like a stepper, the BLDC motor commutates (in this context “commutates” means certain coils turning on and off) according to a predetermined coil activation sequence. That’s about the only similarity between the two. Reversing this sequence reverses the motor. One thing to note is that brushless DC motors are not great at precise rotor alignment.</p> <p>Brushless DC motors are starting to replace their brushed predecessors, finding their way into cordless tools and home appliances like washing machines, DVD players and more. If you build drones you probably use BLDC motors.</p> <p>Advances in semiconductor technology and Moore’s Law made replacing brushes with electronic control feasible. Figure 7 depicts a typical hobby BLDC motor. For the most part brushless DC motors look similar to the brushed variety from the outside.</p> <h3 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h3> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="394" height="150" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 394px) 100vw, 394px" /></p> <p> </p> <p><img loading="lazy" decoding="async" class=" wp-image-4002 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Brushless-DC-Motor.jpg" alt="Brushless-DC-Motor" width="337" height="337" srcset="https://www.circuitcrush.com/wp-content/uploads/Brushless-DC-Motor.jpg 505w, https://www.circuitcrush.com/wp-content/uploads/Brushless-DC-Motor-300x300.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Brushless-DC-Motor-150x150.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Brushless-DC-Motor-100x100.jpg 100w" sizes="(max-width: 337px) 100vw, 337px" /></p> <p><strong><em>Figure 7: a typical hobby BLDCM. My drone build includes motors similar to the one here.</em></strong></p> <p>The BLDC motor in figure 7 is an <strong><em>outrunner</em></strong> type, meaning the outside rotates rather then the inside. The windings don’t move but form the core of the motor. In other words, the rotor is on the outside. As we can see from figure 6, <strong><em>Inrunner</em></strong> versions also exist where the rotor dwells on the inside. The coils attach to the inside of the casing and as before remain stationary.</p> <h2><strong>Stepper Motors<br /> </strong></h2> <p>Stepper motors are another common motor you’ll run into if you deal with robotics or anything that moves. Steppers are a type of brushless DC motor but deserve a portion of the spotlight on their own. They’re similar to brushless DC motors (they have no brushes either) but have many poles per rotation. One of their main advantages is the ability to control them without closed-loop feedback which can be complicated to implement. Open loop systems are usually simpler and cheaper.</p> <p>Two main types of stepper motors exist: unipolar and bipolar.</p> <p>A unipolar stepper uses a coil with a center tap on each pole and requires current to flow in one direction. Only half the coil on a particular pole is driven at a time. A bipolar stepper uses a single coil per pole, usually with twice the turns as that of a unipolar stepper. They also require the current to reverse direction. Bipolar steppers generally need more complex circuitry to accomplish this which can increase the cost of the controller. However, the power to weight ratio of the bipolar type surpasses that of the unipolar type since the whole coil is driven at once.</p> <p>Note that by <strong><em>pole</em></strong> we simply mean a north or south magnetic field that is generated by a permanent magnet or current passing through a coil of wire.</p> <p>Figure 8 shows a typical stepper motor. Note that from the outside, it sort of looks like the DC motors from the previous sections of this article, with the exception of the leads.</p> <p> </p> <p><img loading="lazy" decoding="async" class="size-full wp-image-4003 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Stepper-Motor.jpg" alt="Brushless-DC-Motor" width="420" height="420" srcset="https://www.circuitcrush.com/wp-content/uploads/Stepper-Motor.jpg 420w, https://www.circuitcrush.com/wp-content/uploads/Stepper-Motor-300x300.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Stepper-Motor-150x150.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Stepper-Motor-100x100.jpg 100w" sizes="(max-width: 420px) 100vw, 420px" /></p> <p><strong><em>Figure 8: a typical stepper motor.</em></strong></p> <p>Unlike the other DC motors we already know about, a stepper moves in discrete steps and does not rotate continuously, though they can run in forward motion or in reverse. For those who aren’t sure what I mean, imagine the second hand on an analog clock. It doesn’t rotate continuously, rather it “ticks” in small steps. Steppers are also very accurate in angular position which makes them great for robotics and anything requiring precise movement.</p> <p>Like the BLDC, we can’t just hook one lead to ground and the other to some voltage greater than zero and expect it to work. They need special control, and depending on the stepper, they can sport four to eight connecting wires. Fortunately, one can build their own circuit with transistors if they know what they’re doing or grab a stepper driver IC. Since steppers are inherently digital, they are also compatible with microcontrollers though you can’t drive one directly from the pin of a microcontroller since they draw too much current.</p> <p>A stepper needs to receive a rectangular pulse train to rotate its shaft a certain number of degrees. This is dictated by the number of pulses in the pulse train.</p> <p>The standard <strong><em>stepping resolution</em></strong> (i.e. step size) for most common steppers is 200 steps for 360 degrees of motion which translates into 1.8 degrees per step. We can use half-stepping if we wish; this doubles our count to 400 steps per 360 degrees or 0.9 degrees per step. Some steppers are capable of micro-stepping and can obtain thousands of steps per revolution. Most hobbyists won’t need this level of precision though.</p> <p>Figures 9 and 10 give a general idea of what the inside of a stepper motor looks like.</p> <p> </p> <p><img loading="lazy" decoding="async" class="size-full wp-image-4004 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Inside-Stepper-Motor.png" alt="Inside-Stepper-Motor" width="600" height="246" srcset="https://www.circuitcrush.com/wp-content/uploads/Inside-Stepper-Motor.png 600w, https://www.circuitcrush.com/wp-content/uploads/Inside-Stepper-Motor-300x123.png 300w, https://www.circuitcrush.com/wp-content/uploads/Inside-Stepper-Motor-150x62.png 150w" sizes="(max-width: 600px) 100vw, 600px" /></p> <p><strong><em>Figure 9: inside a stepper motor.</em></strong></p> <p> </p> <p><img loading="lazy" decoding="async" class="size-full wp-image-4005 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Inside-Stepper-Motor-2.jpg" alt="Inside-Stepper-Motor" width="472" height="280" srcset="https://www.circuitcrush.com/wp-content/uploads/Inside-Stepper-Motor-2.jpg 472w, https://www.circuitcrush.com/wp-content/uploads/Inside-Stepper-Motor-2-300x178.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Inside-Stepper-Motor-2-150x89.jpg 150w" sizes="(max-width: 472px) 100vw, 472px" /></p> <p><strong><em>Figure 10: inside a stepper motor from a different angle.</em></strong></p> <p>You can find stepper motors in printers, various computer drives (like old floppy drives), robots, and CNC machines.</p> <h2><strong>Servo Motors<br /> </strong></h2> <p>For most hobbyists, servo motors will be the go-to motor, especially for those into robotics.</p> <p>There is another complete article that focuses just on servo motors on this site (<a href="https://www.circuitcrush.com/servo-motor-introduction/" target="_blank" rel="noopener noreferrer">https://www.circuitcrush.com/servo-motor-introduction/</a>) so I’m not going to repeat too much of it here, but will quickly cover some servo basics to make things complete.</p> <p>Figure 11 depicts a variety of servo motors.</p> <p> </p> <p><img loading="lazy" decoding="async" class=" wp-image-3168 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Servo-Motors.jpg" alt="Various servo motors" width="524" height="349" srcset="https://www.circuitcrush.com/wp-content/uploads/Servo-Motors.jpg 600w, https://www.circuitcrush.com/wp-content/uploads/Servo-Motors-150x100.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Servo-Motors-300x200.jpg 300w" sizes="(max-width: 524px) 100vw, 524px" /></p> <p><strong><em>Figure 11: a variety of servo motors.</em></strong></p> <p>A servo motor is a special subset of a continuous DC motor.</p> <p>A servo motor has three leads. One is for power, one for ground, and the third is a control lead. Since a servo is a <em>closed feedback </em>system (unlike the stepper motor which is open loop), the control lead is needed to sense the position of the servo’s shaft and adjust it if necessary.</p> <p>All servos have at least three main parts:</p> <ul> <li>A DC motor</li> <li>Reduction gears</li> <li>Control circuitry</li> </ul> <p>Figure 12 shows the guts of a typical hobby servo motor and offers some explanation of the parts in the caption. A schematic drawing of a typical servo’s parts and how they fit together is shown in figure 13.</p> <p> </p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3169 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/How-Servos-Work.png" alt="How servo motors work" width="450" height="450" srcset="https://www.circuitcrush.com/wp-content/uploads/How-Servos-Work.png 450w, https://www.circuitcrush.com/wp-content/uploads/How-Servos-Work-300x300.png 300w, https://www.circuitcrush.com/wp-content/uploads/How-Servos-Work-100x100.png 100w, https://www.circuitcrush.com/wp-content/uploads/How-Servos-Work-150x150.png 150w" sizes="(max-width: 450px) 100vw, 450px" /></p> <p><strong><em>Figure 12: inside a typical hobby servo. We can see the DC motor, the control board, and the potentiometer (variable resistor; it’s the brown thing in the upper right next to the DC motor) that connects to the control board. The pot senses the position on the shaft. On the outside we can see some gears and a ‘horn’ attached to the end. The horn is the business end and can come in a variety of shapes and sizes depending on what it’s moving.</em></strong></p> <p> </p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3170 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Inside-a-Servo-Motor-Diagram.jpg" alt="Inside a servo motor" width="332" height="374" srcset="https://www.circuitcrush.com/wp-content/uploads/Inside-a-Servo-Motor-Diagram.jpg 332w, https://www.circuitcrush.com/wp-content/uploads/Inside-a-Servo-Motor-Diagram-133x150.jpg 133w, https://www.circuitcrush.com/wp-content/uploads/Inside-a-Servo-Motor-Diagram-266x300.jpg 266w" sizes="(max-width: 332px) 100vw, 332px" /></p> <p><strong><em>Figure 13: drawing of the insides of a servo and how they fit together. As we can see, the pot senses the position of the shaft. The “electronics” in the picture translate to the control board we can see in figure 12.</em></strong></p> <p>You can’t just connect a battery to a servo motor and watch it go. This is because servos need special control signals to operate correctly. The good thing is there are plenty of ways to easily do this with microcontrollers, boards like Arduino, or even simple electronic circuits.</p> <p>We’ll end our discussion on servo motors here, but for much more detail I urge you to see <a href="https://www.circuitcrush.com/servo-motor-introduction/" target="_blank" rel="noopener noreferrer">An Introduction to Servo Motors</a>.</p> <h2><strong>DC Motor Specs<br /> </strong></h2> <p>An intro to DC motors wouldn’t be complete without a quick overview of some important specs.</p> <p>The term <strong>operating voltage </strong>is self-explanatory. Generally, the more voltage you apply to a DC motor the faster it spins. However, there are limits to this and too much voltage can damage the motor.</p> <p>Most DC motors will run at voltages either lower or higher than the specs call for but there are some caveats. For example, a 6 V motor will likely run at 3 V, but it won’t be as powerful and it’ll run slower. Also, many motors may not run (or run very poorly) at voltages below 40 or 50 percent of their rating.</p> <p>Finally, try not to run a DC motor at more than 200% of its rating, or damage may result.</p> <p><strong>Current draw </strong>is another self-explanatory spec. It’s the amount of current the motor requires. Current draw for a motor with no load is going to be at its lowest. Once you apply a load, the current draw increases until it hits a maximum when the motor stalls. Keep this in mind when using motors in your projects. The power supply or batteries need to be able to handle the worst case scenario where the motor stops because it can no longer handle the load. Just imagine your small robot running into a wall. If it tries to keep going the wheels will either slip or the motors driving them will stall as they futilely try to push the robot through the wall.</p> <p>We all know what <strong>speed </strong>is. It’s usually given in RPMs (revolutions per minute). Most motors spin too fast and need some sort of gears on them to slow them down. Gearing also affects the next spec — torque.</p> <p><strong>Torque </strong>is turning power. Simply put, it’s the force a motor exerts on its load. People measure it by attaching a lever of known length to the end of the motor shaft and using a scale or weight gauge. When a DC motor stalls, it puts out max torque. Torque and current draw are proportional, that is, the more torque the motor puts out the more current it will draw until it stalls where both are maximum.</p> <h2><strong>How to Test the Current Draw of a DC Motor<br /> </strong></h2> <p>Let’s get practical. It’s possible to obtain the current draw of a particular motor with various loads (free running, stall, everything in between) so you can size your power supply right. You’ll need a multimeter with a 10 A input to do this. Please be sure this input has a fuse in case your motor happens to draw more than 10 A, or you’ll fry your meter.</p> <p><span style="text-decoration: underline;">Here’s how to do it:</span></p> <ul> <li>Plug positive the lead (the red one) into the 10 A input. Leave the black or common lead alone; it should be in the common or negative position.</li> <li>Place the meter leads in series with the motor. If possible, try to determine if the motor will draw more than 10 A before you do this. The motor specs or the Internet may help with this. If it does, you can’t use this method, but you may be able to use the alternate method below. If you’re not sure how to hook your meter up, see figure 14.</li> <li>Dial in the 10 A setting, power the motor and observe the output.</li> <li>You can place various loads on the shaft. Your fingers may suffice for small motors. Be careful when using pliers; this can damage the shaft and/or be downright dangerous if your motor is powerful enough. Also, you should make sure powerful motors are secured to something stable before trying to stall them. For every reaction there’s an equal and opposite reaction…</li> </ul> <p> </p> <p><img loading="lazy" decoding="async" class=" wp-image-4006 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Multimeter-in-series.jpg" alt="Multimeter-in-series" width="621" height="485" srcset="https://www.circuitcrush.com/wp-content/uploads/Multimeter-in-series.jpg 1000w, https://www.circuitcrush.com/wp-content/uploads/Multimeter-in-series-300x234.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Multimeter-in-series-150x117.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Multimeter-in-series-768x600.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/Multimeter-in-series-600x469.jpg 600w" sizes="(max-width: 621px) 100vw, 621px" /></p> <p><strong><em>Figure 14: here’s how to hook up your meter to test the current draw of a motor. The battery can be any given power supply. The fuse should be built into your meter. The switch is optional, and the load device is the motor.</em></strong></p> <p>So, what do we do if we suspect our motor draws more than 10 A?</p> <p>Fortunately, there is a solution though it’s a little bit more complex (but still not very hard).</p> <p>We can measure the current of a DC motor indirectly. We do this by using a power resistor and measuring the voltage across it. Using Ohm’s Law, we can then calculate the current. If you forgot about Ohm’s Law, see <a href="https://www.circuitcrush.com/circuit-analysis/" target="_blank" rel="noopener noreferrer">Simple Circuit Analysis Techniques You Should Know</a>.</p> <p><span style="text-decoration: underline;">Here’s the steps:</span></p> <ul> <li>You won’t need to put the positive lead in the 10 A jack, so just leave the positive (red) lead of your meter alone. Of course, you’ll want to leave the black lead alone also.</li> <li>Insert a power resistor in series with the motor. Use anything between 1 to 10 Ohms, but make sure it can handle at least 20 watts of power, the higher the better especially if your motor draws more than 10 A.</li> <li>Power up the circuit and measure the voltage across the resistor. If you’re not sure how to rig the set up, see figure 15.</li> <li>Use Ohm’s Law to get the current: I = V/R or current equals voltage (across the resistor) divided by the resistor’s value.</li> <li>Vary the load and get current draw under different conditions.</li> </ul> <p> </p> <p><img loading="lazy" decoding="async" class=" wp-image-4007 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Measuring-Current-Draw-of-DC-Motor.jpg" alt="Measuring-Current-Draw-of-DC-Motor" width="761" height="428" srcset="https://www.circuitcrush.com/wp-content/uploads/Measuring-Current-Draw-of-DC-Motor.jpg 1280w, https://www.circuitcrush.com/wp-content/uploads/Measuring-Current-Draw-of-DC-Motor-300x169.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Measuring-Current-Draw-of-DC-Motor-1024x576.jpg 1024w, https://www.circuitcrush.com/wp-content/uploads/Measuring-Current-Draw-of-DC-Motor-150x84.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Measuring-Current-Draw-of-DC-Motor-768x432.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/Measuring-Current-Draw-of-DC-Motor-600x338.jpg 600w" sizes="(max-width: 761px) 100vw, 761px" /></p> <p><strong><em>Figure 15: alternate indirect way to measure current draw of DC motor.</em></strong></p> <h2><strong>DC Motor Wrap-up<br /> </strong></h2> <p>That does it for our intro to DC motors.</p> <p>There are a few other specialized DC motors (such as linear motors), but they’re not as likely to end up on your bench.</p> <p>In future articles I’ll go into more detail on each type of motor.</p> <p>Meanwhile, comment and tell me about your projects involving motors. What are you building? What’s your go-to motor? I’d really enjoy hearing about it!</p> <h2 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h2> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="544" height="207" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 544px) 100vw, 544px" /></p> <a target="_blank" href="https://www.drpeterscode.com/index.php"><img src="https://www.circuitcrush.com/wp-content/plugins/dpabottomofpostpage/apixel1x1.jpg" ></a><table></table>]]></content:encoded> <wfw:commentRss>https://www.circuitcrush.com/intro-dc-motors/feed/</wfw:commentRss> <slash:comments>4</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">3995</post-id> </item> <item> <title>An Intro to Pointers in C</title> <link>https://www.circuitcrush.com/c-programming-tutorial-8-pointers-intro/</link> <comments>https://www.circuitcrush.com/c-programming-tutorial-8-pointers-intro/#comments</comments> <dc:creator><![CDATA[Brian]]></dc:creator> <pubDate>Thu, 02 Apr 2020 02:19:42 +0000</pubDate> <category><![CDATA[C Programming]]></category> <category><![CDATA[C programming]]></category> <category><![CDATA[Pointers]]></category> <guid isPermaLink="false">https://www.circuitcrush.com/?p=3969</guid> <description><![CDATA[Pointers in C are one of the most difficult things for many programmers to wrap their minds around and understand. I’m no exception, so this C tutorial on pointers was a re-learning experience for me. Pointers are a powerful mechanism to work on any array data type. They are also one of the most dangerous […]]]></description> <content:encoded><![CDATA[<p>Pointers in C are one of the most difficult things for many programmers to wrap their minds around and understand. I’m no exception, so this C tutorial on pointers was a re-learning experience for me.</p> <p>Pointers are a powerful mechanism to work on any array data type. They are also one of the most dangerous tools a programmer can use and a source of a large share of frustrating programming bugs.</p> <p>In fact, some languages, like Java, have banned their use altogether.</p> <p>Also, arrays and pointers in C share many similarities, and can be used interchangeably in a lot of instances, as we’ll soon see.</p> <p>In spite of all this, once you learn how to use pointers you’ll be glad you took the time to do so.</p> <p><span id="more-3969"></span></p> <h1><strong>Pointers in C<br /> </strong></h1> <h2><strong>What are Pointers?<br /> </strong></h2> <p>A pointer in C is a variable whose value is a memory address. Pointers indirectly refer to (or point to) other variables or part of their contents. While a variable normally contains a specific value, a pointer contains the address of a variable that contains a specific value. So, a variable name directly references a value, and a pointer in C indirectly references a value. Figure 1 sheds some light on this concept.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3971 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Pointers-in-C.jpg" alt="Pointers-in-C" width="555" height="250" srcset="https://www.circuitcrush.com/wp-content/uploads/Pointers-in-C.jpg 555w, https://www.circuitcrush.com/wp-content/uploads/Pointers-in-C-300x135.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Pointers-in-C-150x68.jpg 150w" sizes="(max-width: 555px) 100vw, 555px" /></p> <p><strong><em>Figure 1: how pointers in C work. While variables directly reference a value (like “count” directly references 7), pointers indirectly reference a variable by ‘pointing to’ the address of a variable (like “countPtr” points to the variable “count” which contains the value 7).</em></strong></p> <p>Pointers enable programs to create and manipulate dynamic data structures (data structures that grow and shrink) like queues, stacks, linked lists and more.</p> <p>Because the hardware instructions of computers and microcontrollers rely heavily on addresses, pointers enable you to express yourself in a way that is close to how the machine expresses itself. This makes programs with pointers efficient.</p> <p>Pointers also offer an efficient way to deal with arrays. In fact, arrays are simply pointers in disguise. More on this shortly.</p> <h2><strong>Declaring Pointers in C<br /> </strong></h2> <p>Like other variables, you must declare a pointer before using it. For example, the declaration</p> <pre>int *pointing, number;</pre> <p>declares the variable <strong>pointing</strong> to be of type int. You can read the declaration to say “<strong>pointing</strong> is a pointer to an integer.” The variable <strong>number </strong>is just a standard integer, not a pointer to an integer. The asterisk (*) in the declaration applies only to <strong>pointing</strong>. Each variable you want to declare as a pointer needs to be preceded by an asterisk. So, if I want to declare two pointers, I need to do something like the example below.</p> <pre>int *ptr1, *ptr2;</pre> <p>The * is known as the indirection operator or the dereferencing operator. The type specification identifies the type of variable the pointer points to and the * identifies the variable itself as a pointer. It is not enough to say that a variable is a pointer; you need to tell the compiler what kind of variable the pointer points to. The reason for this is that different variable types take up different amounts of storage and some pointer operations (more on these later) need knowledge of that storage size.</p> <p>One thing to note is that using a space between the * and the name of the pointer is optional. Some programmers will use the space in a declaration (which I did not do) and omit it when dereferencing a pointer. If you’re not sure what dereferencing means, we’ll talk about it a bit later.</p> <p>You can use pointers to reference (or point to) floats, longs, chars, and a host of other data types, not just ints.</p> <p>Consider the declaration below.</p> <pre>char *broil; // broil is a pointer to a character variable</pre> <p>The value of what <strong>broil </strong>points to is of type char but what about <strong>broil</strong> itself? The value of <strong>broil </strong>is an address which many systems represent as an unsigned integer. However, don’t think of a pointer as an integer type. You can do things with pointers you can’t do with integers and vice versa. For example, you can divide one integer by another, but you can’t divide one pointer by another. We’ll talk about what kind of arithmetic you can do with pointers a bit later.</p> <h2><strong>The Address Operator<br /> </strong></h2> <p>Before we venture deeper into the thickets of pointer forest, a few words on the address operator are in order.</p> <p>In many languages, the address of any given variable is the computer’s business and the programmer does not get that information. However, in C you can access the address of a variable using the address operator which is an ampersand (&).</p> <p>Though you can print the address of a variable if you’re really that curious about it that’s not the main use of the address operator. Using the address operator with pointers in C gives you the ability to manipulate addresses and their contents symbolically.</p> <h3 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h3> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="373" height="142" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 373px) 100vw, 373px" /></p> <p>When followed by a variable name, the address operator gives the address of that variable. For example, <strong>&myHouse</strong> gives the memory address of the variable <strong>myHouse</strong>.</p> <p>Suppose we declare a pointer with the name <strong>ptr</strong>. We can write a statement like the one below:</p> <pre>ptr = &myHouse; // this assigns myHouse’s address to ptr</pre> <p>We can say that <strong>ptr</strong> points to <strong>myHouse.</strong> However, the actual value of <strong>ptr </strong>is the memory address, in hexadecimal, of the variable <strong>myHouse</strong>. If you’re unfamiliar with hexadecimal numbers I suggest you read <a href="https://www.circuitcrush.com/hexadecimal-numbers-tutorial/" target="_blank" rel="noopener noreferrer">Breaking the Hex: Understanding Hexadecimal Numbers</a>.</p> <p>Let’s say <strong>myHouse</strong> is an integer whose value is 1234. If we use the indirection operator, we can dereference pointer <strong>ptr</strong> this way:</p> <pre>num = *ptr // assigns value at location ptr to num</pre> <p>by doing this, we assign the value 1234 to <strong>num</strong>.</p> <p>Let’s look at a simple program that swaps 2 numbers to demonstrate pointers and the address operator.</p> <pre>#include <stdio.h> void swapper (int *a, int *b); /* function prototype. For a review on functions see <a href="https://www.circuitcrush.com/c-programming-c-functions-5/" target="_blank" rel="noopener noreferrer">C Programming Tutorial 5</a> */ int main (void) { int y = 10, z = 20; printf(“First y = %d and z = %d. \n”, y, z); swapper (&y, &z); /* call function and send it addresses of y and z */ printf(“Now y = %d and z = %d. \n”, y, z); return 0; } void swapper (int *a, int *b) /* start the function definition */ { int temp; // temporary storage spot temp = *a; /* dereferencing a so temp gets value a points to */ *a = *b; *b = temp; }</pre> <p>Notice that instead of passing the explicit values of <strong>y</strong> and <strong>z</strong> we pass the addresses of <strong>y</strong> and <strong>z</strong> to swapper() which indirectly references the variables. Though C does not explicitly support <strong><em>pass by reference</em></strong>, this is a way to closely emulate it. However, C++ <em>does</em> support pass by reference, but this is a C tutorial so we shall say no more about that for now.</p> <p>Also, we need a third variable in the function definition to temporarily hold the value of integer <strong>a</strong>.</p> <p>Finally, it may be tempting to write something like</p> <pre>temp = a;</pre> <p>instead of</p> <pre>temp = *a;</pre> <p>But <strong>a</strong> has the value of <strong>&y</strong>, so it points to <strong>y</strong> which means <strong>*a</strong> gives the value of <strong>y</strong> (in other words, we’re dereferencing <strong>a</strong>). If we don’t use the indirection operator, we’ll likely get a memory address rather than the value we want.</p> <h2><strong>Arrays and Pointers in C<br /> </strong></h2> <p>Earlier we made the claim that arrays and pointers we basically the same thing. Let’s talk a bit more about that.</p> <p>First, if you need a review on arrays in C, check out <a href="https://www.circuitcrush.com/c-programming-tutorial-6-arrays-intro/" target="_blank" rel="noopener noreferrer">C Programming Tutorials 6</a> and <a href="https://www.circuitcrush.com/c-programming-tutorial-7-arrays-2/" target="_blank" rel="noopener noreferrer">7</a> which discuss arrays.</p> <p>Believe it or not, an array name is also the address of the first element of the array. So, if swagger is an array, then the following is true:</p> <pre>swagger == &swagger[0]; // name of array is the address of the first element</pre> <p>Both <strong>swagger</strong> and <strong>&swagger[0]</strong> represent the memory address of the first element.</p> <p>Various systems and platforms use different amounts of bytes to represent different data types. For example, in the Arduino IDE an integer takes up 2 bytes but on some other system it may take up 4 bytes.</p> <p>This is one reason why you have to declare the sort of object to which a pointer points. The address is not enough because the computer needs to know how many bytes it needs to store the data type. Figure 2 gives a simplified graphical depiction of this concept for clarification.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3972 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Pointers-and-Arrays.png" alt="Pointers in C 2" width="537" height="279" srcset="https://www.circuitcrush.com/wp-content/uploads/Pointers-and-Arrays.png 537w, https://www.circuitcrush.com/wp-content/uploads/Pointers-and-Arrays-300x156.png 300w, https://www.circuitcrush.com/wp-content/uploads/Pointers-and-Arrays-150x78.png 150w" sizes="(max-width: 537px) 100vw, 537px" /></p> <p><strong><em>Figure 2: pointer ptr pointing to an array of integers. Notice it contains the address of the first element, not the value of the first element. Here, each integer takes up 4 bytes, so the address of the first integer is 3000, the second is 3004 and so on. Other systems may use 2 byte integers in which case the second element of the array would have address 3002, the third 3004 and so on.</em></strong></p> <p>The take-away is that the value of a pointer is the address of the object to which it points. How the address is represented internally is hardware dependent. That’s why we need to use data types when declaring pointers.</p> <p>The relationship between arrays and pointers means that you can often use either one when writing a program. They’re usually interchangeable. However, there may be instances where using one over the other can yield benefits such as execution speed.</p> <p>To show this is the case, consider the following program that prints the number of days in each month.</p> <pre>#include <stdio.h> #define MONTHS 12 int main(void) { int days[MONTHS] = {31,28,31,30,31,30,31,31,30,31,30,31}; for (int i = 0; i < MONTHS; i++) printf("Month %d has %2d days.\n", i+1, days[i]); return 0; }</pre> <p>We can change the code within the <strong>main()</strong> function and accomplish the same result, as we can see below.</p> <pre>int main(void) { int days[MONTHS] = {31,28,31,30,31,30,31,31,30,31,30,31}; for (int i = 0; i < MONTHS; i++) printf("Month %d has %2d days.\n", i+1, *(days + i)); // *(days + i) is same as days[i] return 0; }</pre> <p>We still use an array to hold the number of days in each month, but when we print the days, we use a pointer instead. The addition in the pointer may be confusing to some. Let’s talk about that.</p> <h2><strong>Pointer Operations and Arithmetic<br /> </strong></h2> <p>Pointers in C are valid operands in arithmetic expressions, assignment expressions and comparison expressions. But not all operators that normally work with other data types work with pointers. For example, you can’t multiply one pointer by another.</p> <p>Let’s talk about what you <em>can</em> do with pointers in C.</p> <h3><strong>Dereferencing Pointers </strong></h3> <p>As we already know, a pointer can be dereferenced which gives the value in the address it points to. To dereference a pointer, we use the indirection operator (a.k.a. dereferencing operator) which is an asterisk (*).</p> <p>There is one caveat to watch for when dereferencing pointers. Be careful not to dereference an uninitialized pointer. As an example, consider the code snippet below.</p> <pre>int *ptr; // uninitialized pointer *ptr = 100; // error</pre> <p>This is a big no-no because the second line of code is telling the compiler to store the value 100 in the location to which <strong>ptr</strong> points. But <strong>ptr</strong> is uninitialized and has a random value, so there is no knowing where the 100 will go. It might end up somewhere harmless, it may overwrite data or code, or it might cause the program to completely crash.</p> <h3><strong>Getting an Address<br /> </strong></h3> <p>We already know that we can use the address operator to get the memory address of a variable. Like all variables, pointers also have an address. The & operator can tell you where the pointer itself is stored.</p> <h3><strong>Assignment<br /> </strong></h3> <p>You can assign an address to a pointer. Usually, you do this by using an array name or by using the address operator (&). The code fragment below illustrates this.</p> <pre>int array1[5] = {1,2,3,4,5}; int *ptr1; ptr1 = array1; // assigns an address to pointer ptr</pre> <p>When doing this the address should be compatible with the pointer type. In other words, don’t try to assign the address of a float to a pointer to an integer.</p> <h3><strong>Adding an Integer to a Pointer<br /> </strong></h3> <p>As our example program that prints the number of days in each month shows, you can add an integer to a pointer, and this can be quite useful. You can also add a pointer to an integer. In either case, the integer is multiplied by the number of bytes in the data type the pointer points to (refer to figure 2), and the result is added to the original address. The code fragment below shows this.</p> <pre>int array1[5] = {1,2,3,4,5}; int *ptr1, *ptr2; ptr1 = array1; // assigns an address to pointer ptr ptr2 = ptr1 + 4; //same as &array1[4] *ptr2 = ?????</pre> <p>In the fragment above we dereference <strong>ptr2</strong> which gives us the fourth element of <strong>array1</strong> giving us a value of 4.</p> <p>There is one caveat to be aware of when adding integers to pointers. The result is undefined if it lies outside of the array into which the original pointer points, except that the address one past the end element of the array is guaranteed to be valid. So, using the code fragment above, if I write</p> <pre>ptr2 = ptr1 + 17;</pre> <p>the result is meaningless since the array only has five elements.</p> <p>Just as we can add an integer to pointer, we can also subtract integers from pointers. As is similar to the addition case, the integer is multiplied by the number of bytes in the data type the pointer points to and the result is subtracted from the original address. And, as in addition, the result is undefined if it lies outside of the array into which the original pointer points, except that the address one past the end element of the array is guaranteed to be valid.</p> <h3><strong>Incrementing and Decrementing Pointers in C<br /> </strong></h3> <p>Programmers can use the ++ or – – operators to increment or decrement pointers just like other variables. This is useful when using pointers to step through loops. Incrementing a pointer to an array element makes it move to the next element of the array. Similarly, decrementing a pointer to an array element makes it move to the previous element of the array. Keep in mind that when doing either/or the actual address of the pointer itself remains the same.</p> <p>Finally, you can use both the prefix and postfix forms of the increment and decrement operators.</p> <p>Consider the code fragment below.</p> <pre>int array1[5] = {5,4,3,2,1}; int *ptr1; ptr1 = array1; // assigns an address to pointer ptr ptr1++;</pre> <p>In the example above <strong>ptr1</strong> was originally equal to the first element of the array (5) but at the end of the code it increments by one and is now equal to the second element of the array (4).</p> <p>One last thing to note is that pointer arithmetic is meaningless unless you use a pointer that points to an array. Do not assume that two variables are contiguous (next/near to each other) in memory unless they are adjacent elements of an array.</p> <h3><strong>Differencing Pointers in C<br /> </strong></h3> <p>You can find the difference between two pointers. Normally, you do this for two pointers to elements that are in the same array to find out how far apart the elements are. The result is in the same units as the type size. Note that if you subtract one pointer from another and they point to integers, and, say the result is 2, this indicates they are separated by 2 integers not necessarily by 2 bytes.</p> <p>Applying this operation to pointers to two different arrays might produce a value or could lead to a runtime error.</p> <h3><strong>Comparisons<br /> </strong></h3> <p>You can use the relational operators to compare the values of two pointers if the pointers are of the same type and in the same array. Pointer comparisons compare the addresses in the pointers. Such a comparison may show, for example, that one pointer points to a higher numbered element of the array then the other. One common use is determining if a pointer points to nothing (i.e. it is 0).</p> <h2><strong>Pointing Isn’t so Rude After All<br /> </strong></h2> <p>So now we some basics about pointers in C and how to use them. We’ve seen that they’re not so hard to understand after all and can be very useful in your programs.</p> <p>As usual, this is a somewhat deep subject which is capable of filling several posts. Because of this, I’m sure pointers will come up again in future C tutorials and other articles.</p> <p>Until then, drop a comment and tell me about your thoughts on pointers. Do you use them? Do you prefer arrays, pointers, or use both equally? Is there any important information concerning pointers I left out? I’d love to hear from you!</p> <h2 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h2> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="504" height="192" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 504px) 100vw, 504px" /></p> <a target="_blank" href="https://www.drpeterscode.com/index.php"><img src="https://www.circuitcrush.com/wp-content/plugins/dpabottomofpostpage/apixel1x1.jpg" ></a><table></table>]]></content:encoded> <wfw:commentRss>https://www.circuitcrush.com/c-programming-tutorial-8-pointers-intro/feed/</wfw:commentRss> <slash:comments>3</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">3969</post-id> </item> <item> <title>How BJTs Work</title> <link>https://www.circuitcrush.com/how-bjt-works/</link> <comments>https://www.circuitcrush.com/how-bjt-works/#comments</comments> <dc:creator><![CDATA[Brian]]></dc:creator> <pubDate>Tue, 17 Mar 2020 03:09:14 +0000</pubDate> <category><![CDATA[Transistors]]></category> <category><![CDATA[BJT]]></category> <category><![CDATA[transistors]]></category> <guid isPermaLink="false">https://www.circuitcrush.com/?p=3943</guid> <description><![CDATA[Let’s go into more detail on how the BJT (bipolar junction transistor) works. The last article on transistors (An Introduction to Transistors) started with a little history on the devices and what was in use before them. Then, it glossed over the two main types you’ll work with: BJTs and MOSFETs. Finally, the two modes […]]]></description> <content:encoded><![CDATA[<p>Let’s go into more detail on how the BJT (bipolar junction transistor) works.</p> <p>The last article on transistors (<a href="https://www.circuitcrush.com/what-is-a-transistor/" target="_blank" rel="noopener noreferrer">An Introduction to Transistors</a>) started with a little history on the devices and what was in use before them. Then, it glossed over the two main types you’ll work with: BJTs and MOSFETs. Finally, the two modes of transistor operation were briefly discussed.</p> <p>This time, we’re going to take a deeper dive into BJTs specifically. This article will go into a bit more detail on how the BJT or bipolar junction transistor works and some basics on using them in your creations.</p> <p><span id="more-3943"></span></p> <h1><strong>How BJTs Work<br /> </strong></h1> <h2><strong>BJT Basics Recap<br /> </strong></h2> <p>Let’s start with a quick recap on the basics of how a BJT works.</p> <p>I won’t regurgitate every single word about BJTs from the last article but for the sake of convenience I’ll present a quick review on the fundamentals.</p> <p>However, if you’re just learning about transistors I suggest you first read <a href="https://www.circuitcrush.com/how-diodes-work/" target="_blank" rel="noopener noreferrer">How Diodes Work – An Introduction</a> because it talks about basic semiconductor principles and then read <a href="https://www.circuitcrush.com/what-is-a-transistor/" target="_blank" rel="noopener noreferrer">An Introduction to Transistors</a>.</p> <p>Recall that there are two main types of BJTs and that the BJT is a three terminal device, as we can see in figure 1. The three terminals are the <em>base</em><em>, </em><em>collector</em><em>, </em>and <em>emitter</em>.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3791 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/BJT-Schematic-Symbol.jpg" alt="BJT-Schematic-Symbols" width="363" height="264" srcset="https://www.circuitcrush.com/wp-content/uploads/BJT-Schematic-Symbol.jpg 363w, https://www.circuitcrush.com/wp-content/uploads/BJT-Schematic-Symbol-150x109.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/BJT-Schematic-Symbol-300x218.jpg 300w" sizes="(max-width: 363px) 100vw, 363px" /></p> <p><strong><em>Figure 1: the two main types of bipolar junction transistors are NPN and PNP.</em></strong></p> <p>An NPN BJT sandwiches P-type semiconductor material between two layers of N-type semiconductor material. Conversely, a PNP BJT sandwiches N-type material between two layers of P-type material.</p> <p> </p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3944 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/BJT-Structures.jpg" alt="How BJTs work" width="514" height="191" srcset="https://www.circuitcrush.com/wp-content/uploads/BJT-Structures.jpg 514w, https://www.circuitcrush.com/wp-content/uploads/BJT-Structures-300x111.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/BJT-Structures-150x56.jpg 150w" sizes="(max-width: 514px) 100vw, 514px" /></p> <p><strong><em>Figure 2: conceptual structure of a PNP and an NPN BJT.</em></strong></p> <p>Finally, a BJT can find use as either a switch or an amplifier.</p> <h2><strong>How a BJT Works: A Closer Look at Structure<br /> </strong></h2> <p>The name <em>bipolar junction transistor</em> may make one think that the device has an unfortunate mental health issue. Of course, this is not the case.</p> <p>The term <strong>bipolar</strong> means the device is made from semiconductor material in which conduction relies on both positive and negative charge carriers. These “charge carriers” are holes and electrons, respectively.</p> <p>Figure 2 suggests that the three silicon regions of a BJT are segments of a bar which stack on top of each other (if you rotate the pic 90 degrees). While some of the first transistors from the late 1940s and early 1950s were made this way, modern transistors are not.</p> <p>Figure 3 depicts the structure of a modern BJT.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3945 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/BJT-Cross-Section.jpg" alt="Inside a BJT" width="504" height="633" srcset="https://www.circuitcrush.com/wp-content/uploads/BJT-Cross-Section.jpg 504w, https://www.circuitcrush.com/wp-content/uploads/BJT-Cross-Section-239x300.jpg 239w, https://www.circuitcrush.com/wp-content/uploads/BJT-Cross-Section-119x150.jpg 119w" sizes="(max-width: 504px) 100vw, 504px" /></p> <p><strong><em>Figure 3: structure of a modern BJT.</em></strong></p> <p>As we can see, the layers do not stack on top of one another. Instead, semiconductor manufacturers use a diffusion process which melts the base into the collector region and then melts the emitter region into the base region (for an NPN BJT). Thousands of transistors are diffused on a silicon wafer from which induvial transistors are then cut before being sealed in plastic or metal.</p> <p>One last thing to note about BJT structure is that the base region is lightly doped and very thin compared to the heavily doped emitter and moderately doped collector regions. The reason for this will become apparent shortly.</p> <h2><strong>How a BJT Works: Low Level Operation<br /> </strong></h2> <p>It’s time to get into some detail about how BJTs work. First, we’ll start with some basic low-level operation before going into more practical high-level operation.</p> <p>To illustrate how a BJT works, let’s take a look at what happens inside an NPN transistor. It will be helpful to think of the base-emitter (BE) and base-collector (BC) junctions as diodes, like figure 4 depicts.</p> <p><img loading="lazy" decoding="async" class=" wp-image-3946 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Transistors-as-Diodes.jpg" alt="Transistors-as-Diodes" width="558" height="314" srcset="https://www.circuitcrush.com/wp-content/uploads/Transistors-as-Diodes.jpg 1280w, https://www.circuitcrush.com/wp-content/uploads/Transistors-as-Diodes-300x169.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Transistors-as-Diodes-1024x576.jpg 1024w, https://www.circuitcrush.com/wp-content/uploads/Transistors-as-Diodes-150x84.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Transistors-as-Diodes-768x432.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/Transistors-as-Diodes-600x338.jpg 600w" sizes="(max-width: 558px) 100vw, 558px" /></p> <p><strong><em>Figure 4: it’s helpful to visualize the junctions in a BJT as diodes. If this were a PNP BJT each diode would be turned 180 degrees.</em></strong></p> <p>First, let’s talk about what happens when the transistor is off.</p> <p>Remember that a typical silicon diode needs about 0.7 V to turn on and conduct. So, with less than 0.7 V on the base the transistor is off because the low voltage does not forward bias the BE diode. If we were to apply a negative voltage to the NPN BJT in figure 4 the situation worsens; the p-n junction between the base and emitter widens.</p> <p>Applying a voltage of at least 0.7 V forward biases the BE diode and the transistor begins to turn on. As the voltage increases the depletion zone narrows and electrons head toward the positive base. Remember that the emitter is heavily doped and contains an excess of free electrons.</p> <p>Some of them will exit through the base but because it’s so thin with a light doping most of them (like more than 97%) that leave the emitter will get close enough to the collector side that they begin to jump into the collector. Increasing the base voltage increases this effect. During this time the BC diode is actually reversed biased, but the electric field set up by the collector supply voltage pulls the electrons through. It is this that makes the BJT act as a variable resistor; the wider the depletion region of the BC diode, the more resistance the device offers.</p> <p>In fact, any properly biased NPN BJT for use in amplification will have a forward biased BE junction (emitter diode on) and a reversed biased BC junction (collector diode off).</p> <h3 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h3> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="357" height="136" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 357px) 100vw, 357px" /></p> <p>Figure 5 below offers a graphical view of this process.</p> <p><img loading="lazy" decoding="async" class=" wp-image-3947 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/How-BJT-Works.jpg" alt="How-BJT-Works" width="723" height="382" srcset="https://www.circuitcrush.com/wp-content/uploads/How-BJT-Works.jpg 896w, https://www.circuitcrush.com/wp-content/uploads/How-BJT-Works-300x159.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/How-BJT-Works-150x79.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/How-BJT-Works-768x406.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/How-BJT-Works-600x317.jpg 600w" sizes="(max-width: 723px) 100vw, 723px" /></p> <p><strong><em>Figure 5: how a BJT works on a low-level. This is how electrons move through an NPN BJT. Note the picture uses electron flow rather than conventional current flow. The small white circles in the base are holes. Some electrons will combine with the holes in the base.</em></strong></p> <p>Notice that since the base is a p-type material it contains holes.</p> <p>Here’s another way to think of NPN BJT operation: for every hole that is filled in the base by an electron, a small negative charge is trapped in the base terminal. The only way to get rid of the charge is to draw electrons from the base. So, to maintain collector current all electrons that fall into holes need to be drained. This is why the base current controls the collector current.</p> <h2><strong>How a BJT Works: The Practical Side or High Level Operation<br /> </strong></h2> <p>Now that we know something about low-level BJT operation, let’s talk about the more practical, higher-level operation of the device.</p> <p>A BJT uses a small current at its base to control a much larger collector current.</p> <p>Before we go any further, it may be useful to define some important terms concerning the operation of a bipolar junction transistor.</p> <p><strong>Saturation </strong>refers to a region of operation where maximum collector current flows and the BJT acts like a closed switch from collector to emitter. In this mode the BC junction forward biases and maximum current flows. The collector current cannot increase any more, even with an increase in base current.</p> <p><strong>Cutoff </strong>refers to a region of operation where the BJT acts like an open switch, though a very small leakage current (which we can usually neglect) still flows.</p> <p>Finally, the <strong>active mode</strong> or <strong>active region</strong> describes operation in which the BE junction is forward biased, and the BC junction is revered biased. In this mode, the BJT is equivalent to a variable resistor between the emitter and collector. If we want to use a bipolar junction transistor for amplification, we need to operate it in this mode or region.</p> <p>Figure 6 graphically depicts these modes of operation with a family of collector characteristic curves. Here, several values of I<sub>B</sub> are used to plot I<sub>C</sub> vs V<sub>CE</sub>. The cutoff region lies along the horizontal axis. The saturation region is the area to the left of the near-vertical line. The straight, horizontal lines represent the active region. Put another way, these curves describe the effects the base current and emitter-to-collector voltage have on the emitter / collector currents.</p> <p><img loading="lazy" decoding="async" class=" wp-image-3948 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Bipolar-junction-Transistor-Characteristic-Curve.png" alt="Bipolar-junction-Transistor-Characteristic-Curve" width="515" height="424" srcset="https://www.circuitcrush.com/wp-content/uploads/Bipolar-junction-Transistor-Characteristic-Curve.png 611w, https://www.circuitcrush.com/wp-content/uploads/Bipolar-junction-Transistor-Characteristic-Curve-300x247.png 300w, https://www.circuitcrush.com/wp-content/uploads/Bipolar-junction-Transistor-Characteristic-Curve-150x123.png 150w, https://www.circuitcrush.com/wp-content/uploads/Bipolar-junction-Transistor-Characteristic-Curve-600x494.png 600w" sizes="(max-width: 515px) 100vw, 515px" /></p> <p><strong><em>Figure 6: BJT collector characteristic curves show how a BJT works for the 3 modes of operation.</em></strong></p> <p>Equation 1 gives the total current flowing in the emitter of a BJT. Since the base current I<sub>B</sub> is very small compared to the collector current I<sub>C</sub>, it is usually neglected and equation 2 suffices for most applications.</p> <p>I<sub>E</sub> = I<sub>C</sub> + I<sub>B</sub> (eq. 1)</p> <p>I<sub>E</sub> ≈ I<sub>C</sub> (eq. 2)</p> <p>We already know that a small base current causes a larger collector current to flow. Bipolar junction transistors relate the current flowing into the base and the collector current through a constant beta (ẞ). Beta is also sometimes referred to as h<sub>FE</sub>. Every single BJT has its own unique beta value ranging from 20 to 500. This is the transistor’s current gain. Equation 3 gives the formula for current gain as it relates to total beta and total collector current.</p> <p>I<sub>C</sub> = ẞI<sub>B </sub> (eq. 3)</p> <p>There are few important things to note about equation 3.</p> <p>First, the BJT needs to be in the <em>active region</em> of operation for it to apply. For this to be the case there are two rules that we need to heed.</p> <p><strong>Rule 1:</strong> The voltage at the collector must be at least a few tenths of a volt higher than the voltage at the emitter. This applies to NPN BJTs. For PNP BJTs, the emitter voltage must exceed the collector voltage by a similar amount. If this condition isn’t met, no current flows through the device regardless of the base voltage.</p> <p><strong>Rule 2:</strong> There is a voltage drop of about 0.7 V from base to emitter in an NPN BJT and a rise of 0.7 V from base to emitter for a PNP device. Using an NPN transistor as an example, this means that the base voltage must be at least 0.7 V higher than the emitter voltage to overcome the diode drop. If this isn’t the case, the transistor will not turn on. Equation 4 expresses this rule mathematically.</p> <p>V<sub>BE</sub> = V<sub>B</sub> – V<sub>E</sub> = 0.7 V (or -0.7 V for a PNP device) (eq. 4)</p> <p>Another less-often used constant pertaining to BJTs is the device’s alpha (α). Alpha describes the ratio of the DC collector current to the DC emitter current.</p> <p>α = I<sub>C</sub>/I<sub>E </sub> (eq. 5)</p> <p>Also:</p> <p>α = ẞ / (ẞ + 1) (eq. 6)</p> <p>Typical values of alpha range from 0.95 to 0.99 or more but it is always less than 1.</p> <p>Before we go any further, a simple example will help us analyze BJT circuits at DC.</p> <p><strong><u>Ex 1:</u></strong></p> <p>Refer to the figure below. Assume a beta of 150 and that R<sub>C</sub> = 100 Ω and R<sub>B</sub> = 10k Ω. Find I<sub>B</sub>, I<sub>C</sub>, I<sub>E</sub>, V<sub>BE</sub>, and V<sub>CB</sub>. V<sub>BB</sub> = 5 V and V<sub>CC</sub> = 10 V.</p> <p><img loading="lazy" decoding="async" class=" wp-image-3949 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/bjt-DC-circuit-analysis.png" alt="bjt-DC-circuit-analysis" width="333" height="258" srcset="https://www.circuitcrush.com/wp-content/uploads/bjt-DC-circuit-analysis.png 252w, https://www.circuitcrush.com/wp-content/uploads/bjt-DC-circuit-analysis-150x116.png 150w" sizes="(max-width: 333px) 100vw, 333px" /></p> <p> </p> <p><strong>Solution:</strong></p> <p>We know that V<sub>BE</sub> is about 0.7 V. We’ll use that info to get I<sub>B</sub> as follows:</p> <p>I<sub>B</sub> = (V<sub>BB</sub> – V<sub>BE</sub>) / 10k = (5 – 0.7) / 10k = 430 µA</p> <p>The equation above may be hard to understand for those new to electronics, but it’s just a basic application of Ohm’s Law. Since V<sub>BB</sub> is 5 V and V<sub>BE</sub> is 0.7 V, 4.3 V must drop across the base resistor. Once we know this, finding the base current is a cinch. If this is still confusing reading <a href="https://www.circuitcrush.com/circuit-analysis/" target="_blank" rel="noopener noreferrer">Simple Circuit Analysis Techniques You Should Know</a> may help.</p> <p>Onto I<sub>C</sub>…</p> <p>I<sub>C</sub> = ẞI<sub>B </sub>= (150)(430 µA) = 64.5 mA</p> <p>Let’s grab I<sub>E</sub> next…</p> <p>For most purposes it may be okeydokey to approximate and say that I<sub>E</sub> = I<sub>C</sub> = 64.5 mA.</p> <p>If we want to be exact, we can say I<sub>E</sub> = I<sub>B</sub> + I<sub>C</sub> = 430 µA + 64.5 mA = 64.9 mA. Notice there isn’t much of a difference.</p> <p>Now for V<sub>CE</sub>:</p> <p>Applying Ohm’s Law, we get V<sub>CE</sub> = V<sub>CC</sub> – I<sub>C</sub>R<sub>C </sub>= 10 V – (64.5 mA)(100) = 10 V – 6.45 V = 3.55 V</p> <p>Finally, let’s get V<sub>CB</sub>:</p> <p>V<sub>CB </sub>= V<sub>CE</sub> – V<sub>BE</sub> = 3.55 V – 0.7 V = 2.85 V</p> <p><em>Remember that the relation I<sub>C</sub> = </em><em>ẞI<sub>B</sub> is only valid for transistors in the active region and does not work for transistors in saturation.</em></p> <p>Let’s do another slightly different example to illustrate how a BJT works.</p> <p><strong><u>Ex 2:</u></strong></p> <p>Take a gander at the circuit below. Beta is 100. Determine all node voltages and branch currents.</p> <p><img loading="lazy" decoding="async" class=" wp-image-3950 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/BJT-Circuit-Analysis_2.jpg" alt="BJT-Circuit-Analysis_2" width="311" height="346" srcset="https://www.circuitcrush.com/wp-content/uploads/BJT-Circuit-Analysis_2.jpg 383w, https://www.circuitcrush.com/wp-content/uploads/BJT-Circuit-Analysis_2-270x300.jpg 270w, https://www.circuitcrush.com/wp-content/uploads/BJT-Circuit-Analysis_2-135x150.jpg 135w" sizes="(max-width: 311px) 100vw, 311px" /></p> <p>The base it at 4 V and the emitter is at ground, so it’s safe to assume that the BE junction is forward biased.</p> <p>V<sub>E</sub> = 4 – V<sub>BE</sub> = 4 – 0.7 = 3.3 V</p> <p>Now let’s get I<sub>E</sub>:</p> <p>I<sub>E</sub> = (V<sub>E</sub> – 0) / R<sub>E</sub> = 3.3 / 3.3k = 1 mA</p> <p>We don’t know the base current yet, but we can rearrange equation 5 by multiplying both sides by I<sub>E</sub>:</p> <p>I<sub>C</sub> = αI<sub>E</sub></p> <p>Next let’s use equation 6 to find alpha:</p> <p>α = ẞ / (ẞ + 1) = 100/101 = 0.99</p> <p>Now we can get I<sub>C</sub>:</p> <p>I<sub>C</sub> = (0.99)(1 mA) = 0.99 mA</p> <p>Using Ohm’s Law, we can grab the collector voltage:</p> <p>V<sub>C</sub> = 10 – I<sub>C</sub>R<sub>C</sub> = 10 – ((0.99 mA)(4.7k)) = 5.3 V</p> <p>Finally, we need the base current:</p> <p>I<sub>B </sub>= I<sub>E</sub> / (ẞ + 1) = 1 mA / 101 = 0.01 mA</p> <h3><strong>BJTs in Saturation: The Transistor as a Switch<br /> </strong></h3> <p>Unless you’re into designing amplifiers and analog circuits you’ll probably be using the BJT as a switch most of the time.</p> <p>Some may ask why bother using a transistor as a switch when we can just use a mechanical switch. There are a few good reasons for this. First, transistors can switch on and off extremely fast, typically a fraction of a micro-second or less. Second, they can be driven from other circuits (such as a microcontroller) whereas a mechanical switch cannot. Mechanical switches wear out and the contacts bounce while transistors do not. And there are other reasons. If you’re still not convinced transistors make good switches, you’ll just have to take my word for it.</p> <p>When using a bipolar junction transistor as switch, you’ll operate it in cutoff and saturation modes.</p> <p>Cutoff mode is self-explanatory – the device is off and is not conducting any current (except for a negligible leakage current).</p> <p>In cutoff, equation 7 holds true.</p> <p>V<sub>CE</sub> = V<sub>CC</sub> (eq. 7)</p> <p>When the BE junction is forward biased and there is enough base current to produce a maximum collector current the transistor is saturated. Equation 8 gives the formula for collector current when the device saturates.</p> <p>I<sub>C(sat) </sub>= (V<sub>CC</sub> – V<sub>CE(sat)</sub>) / R<sub>C</sub> (eq. 8)</p> <p>Normally V<sub>CE(sat) </sub>is very small compared to V<sub>CC</sub> (the BJT is acting like a closed switch and there is ideally 0 V across a closed switch because it’s a short) and we can neglect it. The minimum base current the BJT needs for saturation is:</p> <p>I<sub>B(min)</sub> = I<sub>C(sat)</sub> / ẞ (eq. 9)</p> <p>Note that I<sub>B</sub> should be significantly greater than I<sub>B(min)</sub> to be sure the BJT stays well into saturation.</p> <p>Finally, some inquisitive readers may be asking if there is a formula for V<sub>CE(sat)</sub>. Indeed, there is, but as we’ve mentioned this quantity can usually be neglected and the formula involves some complexity that’s beyond the scope of this writing.</p> <p>Let’s do a quick, practical example of how a BJT works in saturation as a switch.</p> <p><strong><u>Ex 3:</u></strong></p> <p>The LED in the figure below needs 30 mA to emit an aesthetically pleasing level of light. So, the collector current should be about 30 mA. Determine the amplitude of the DC signal the transistor needs to saturate and light the LED. Use double the minimum base current as a safety margin because ruining the mood lighting (by having the LED turn off) would make her want to leave. Vcc = 9 V, V<sub>CE(sat)</sub> = 0.3 V, Rc = 270 Ω, R<sub>B</sub> = 3.3 kΩ and ẞ = 50.</p> <p><img loading="lazy" decoding="async" class=" wp-image-3951 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/BJT-Driving-LED.jpg" alt="BJT-Driving-LED" width="385" height="448" srcset="https://www.circuitcrush.com/wp-content/uploads/BJT-Driving-LED.jpg 512w, https://www.circuitcrush.com/wp-content/uploads/BJT-Driving-LED-258x300.jpg 258w, https://www.circuitcrush.com/wp-content/uploads/BJT-Driving-LED-129x150.jpg 129w" sizes="(max-width: 385px) 100vw, 385px" /></p> <p>Let’s get Ic:</p> <p>Ic = (Vcc – V<sub>CE(sat)</sub>) / Rc = (9 V – 0.3 V) / 270 Ω = 32.2 mA</p> <p>I<sub>B(min)</sub> = I<sub>C(sat)</sub> / ẞ = 32.2 mA / 50 = 644 µA</p> <p>Next let’s double the minimum to ensure saturation so our date sticks around. This gives us about 1.29 mA.</p> <p>Now:</p> <p>I<sub>B</sub> = V<sub>RB</sub> / R<sub>B</sub> = (V<sub>in</sub> – V<sub>BE)</sub>) / R<sub>B</sub> = (V<sub>in</sub> – 0.7 V) / 3.3 kΩ</p> <p>Solving for V<sub>in</sub></p> <p>V<sub>in </sub>– 0.7 V = 2I<sub>B(min)</sub> * R<sub>B </sub>= 1.29 mA * 3.3 kΩ</p> <p>V<sub>in</sub> = (1.29 mA)(3.3 kΩ) + 0.7 V = 4.96 V</p> <h2><strong>Some Final Thoughts on BJTs<br /> </strong></h2> <p>Let’s wrap this up with a few final tips and thoughts on BJTs.</p> <p>We know that the beta of any random BJT varies widely. Because beta is somewhat unpredictable, you should avoid designing and building circuits that depend specifically on beta values to work correctly. In other words, a circuit that depends on a particular value of beta is a bad circuit.</p> <p>Also, all transistors have a maximum collector current rating as well maximum collector to base, emitter to base, and collector to emitter breakdown voltages. You also need to be aware of the maximum power dissipation rating. Ignoring these specs can kill your BJT.</p> <p>Bipolar junction transistors come in a variety of packaging types. Some come in plastic, others in metal can-like packages. Look at the package to see if it has a pinout diagram on it. If it doesn’t, a good cross-reference (like NTE) of the Internet can help. If all else fails, you may have to use the transistor tester in your meter or “Ohm it out” if it doesn’t have one.</p> <h3><strong>Testing a BJT<br /> </strong></h3> <p>Speaking of multimeters, yours may come in handy for testing transistors you suspect may be bad.</p> <p>Remember how a BJT works — its like two diodes.</p> <p>A good diode shows high resistance with reverse bias and a low resistance with forward bias. An open diode will have a high resistance both ways. A shorted diode will have low resistance both ways. Many modern DMMs sport a diode and/or transistor test function to make this easier.</p> <p>That wraps up our intro to BJTs. Next time we talk about them we’ll go over some basic biasing techniques.</p> <p>Meanwhile, leave a comment and tell me about your latest endeavor using discrete BJTs. What are you driving? An LED? Speaker? Motor? Something else?</p> <p>Share it!</p> <h2 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h2> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="552" height="210" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 552px) 100vw, 552px" /></p> <p><em><strong> </strong></em></p> <a target="_blank" href="https://www.drpeterscode.com/index.php"><img src="https://www.circuitcrush.com/wp-content/plugins/dpabottomofpostpage/apixel1x1.jpg" ></a><table></table>]]></content:encoded> <wfw:commentRss>https://www.circuitcrush.com/how-bjt-works/feed/</wfw:commentRss> <slash:comments>4</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">3943</post-id> </item> <item> <title>Intro to Analog to Digital Converters</title> <link>https://www.circuitcrush.com/analog-digital-converters-tutorial/</link> <comments>https://www.circuitcrush.com/analog-digital-converters-tutorial/#comments</comments> <dc:creator><![CDATA[Brian]]></dc:creator> <pubDate>Thu, 27 Feb 2020 16:14:58 +0000</pubDate> <category><![CDATA[analog to digital conversion]]></category> <category><![CDATA[Electronics]]></category> <category><![CDATA[ADCs]]></category> <category><![CDATA[Analog to digital converters]]></category> <guid isPermaLink="false">https://www.circuitcrush.com/?p=3909</guid> <description><![CDATA[Like digital to analog converters or DACs, the analog to digital converter or ADC is everywhere. A while back, I published an article on DACs titled Digital to Analog Converters – An Introductory Tutorial. I strongly advise you check it out before reading this article if you haven’t already. There are a few reasons for […]]]></description> <content:encoded><![CDATA[<p>Like digital to analog converters or DACs, the analog to digital converter or ADC is everywhere.</p> <p>A while back, I published an article on DACs titled <a href="https://www.circuitcrush.com/digital-analog-converters-tutorial/" target="_blank" rel="noopener noreferrer">Digital to Analog Converters – An Introductory Tutorial</a>. I strongly advise you check it out before reading this article if you haven’t already.</p> <p>There are a few reasons for this. First, some analog to digital converters use DACs as part of their makeup. Second, a lot of the specs that apply to DACs also apply to analog to digital converters. Finally, ADCs are more complicated, but a good understanding of DACs can help you better understand how ADCs work.</p> <p>Like the DAC post, this one is introductory, so we won’t cover every analog to digital converter that exists; rather I’ll discuss the most common ones in use today. <span id="more-3909"></span>And, as before, we won’t go into huge detail about how these ADCs work, but we will cover the basics.</p> <h1><strong>How the Analog to Digital Converter Works<br /> </strong></h1> <h2><strong>Analog to Digital Conversion 101<br /> </strong></h2> <p>Sometimes, I start my posts with an interesting historical tidbit. This one will be no exception.</p> <p>Toward that end, according to the Data Conversion Handbook by Walt Kester, the first commercial ADC showed up on the scene in 1954. The 11-bit device weighed 154 lbs. (70 kg) and slurped up at least 500 watts of power, often times more. It sold for $8,500 at the time which, according to some online inflation calculators, translates to more the $80,700 in 2019 dollars. Technology certainly has come a long way, hasn’t isn’t it?</p> <p>That’s enough history for now, let’s talk about how ADCs work.</p> <p>An analog to digital converter or ADC, transforms analog information in electrical form into digital data. In other words, an ADC takes a continuous analog input signal and converts it into a binary number which a computer or microcontroller can work with.</p> <p>Often, the analog to digital converters you’ll work with are part of the microcontroller or board of choice but ADCs in separate IC packages are available for certain applications.</p> <p>By the way, if you’re not 100% sure what the difference between digital and analog is, I urge you to see <a href="https://www.circuitcrush.com/analog-vs-digital/" target="_blank" rel="noopener noreferrer">Analog vs Digital: What’s the Difference?</a></p> <p>I’ll assume you know the difference from here on.</p> <p>Analog signals continuously vary with time, so to convert an analog signal into digital form an ADC must sample the analog signal at a certain rate or frequency.</p> <p>This rate is governed by the <strong><em>Nyquist theorem</em></strong>.</p> <p>The Nyquist theorem says that to avoid any loss of information the sampling rate must be at least twice as high as the highest frequency component we expect to see in the analog signal we’re sampling. Explaining why the Nyquist theorem works and finding frequency components of signals involves a lot of high-level math which is beyond the scope of this article, but perhaps a future post will cover the Nyquist sampling theorem in a bit more detail.</p> <p>Figures 1 and 2 offer a basic graphical depiction of sampling an analog signal.</p> <p><img loading="lazy" decoding="async" class="alignnone wp-image-3910" src="http://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal-1024x576.jpg" alt="How the analog to digital converter works - sampling a sine wave" width="756" height="425" srcset="https://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal-1024x576.jpg 1024w, https://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal-300x169.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal-150x84.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal-768x432.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal-600x338.jpg 600w, https://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal.jpg 1280w" sizes="(max-width: 756px) 100vw, 756px" /></p> <p><strong><em>Figure 1: sampling an analog signal. The time in between samples is the sampling period.</em></strong></p> <p><strong><em> </em></strong></p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3911 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal-2.jpg" alt="Sampling an analog signal" width="600" height="294" srcset="https://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal-2.jpg 600w, https://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal-2-300x147.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Sampling-Analog-Signal-2-150x74.jpg 150w" sizes="(max-width: 600px) 100vw, 600px" /></p> <p> </p> <p><strong><em>Figure 2: if we connect the samples in figure 1 with horizontal lines, we’ll get a staircase like this (in red). Notice how it sort of has the same shape as the sine wave (in blue). If we take more samples and reduce the sampling period, the red signal will get smoother and look more like the original sine wave.</em></strong></p> <p>Now that we have some general info on analog to digital converters, let’s go over the most common ones around today.</p> <h2><strong>Types of Analog to Digital Converters<br /> </strong></h2> <h3><strong>Flash ADC<br /> </strong></h3> <p>Also known as the <strong><em>simultaneous</em></strong> or <strong><em>parallel</em></strong> analog to digital converter, the flash ADC gets its name from its main strength — speed.</p> <p>The flash method uses comparators that compare reference voltages with the analog input voltage.</p> <p>Figure 3 depicts a diagram of a 3-bit flash analog to digital converter.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3912 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Flash-ADC.jpg" alt="A Flash ADC" width="728" height="574" srcset="https://www.circuitcrush.com/wp-content/uploads/Flash-ADC.jpg 728w, https://www.circuitcrush.com/wp-content/uploads/Flash-ADC-300x237.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Flash-ADC-150x118.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Flash-ADC-600x473.jpg 600w" sizes="(max-width: 728px) 100vw, 728px" /></p> <p><strong><em>Figure 3: a typical 3-bit flash ADC.</em></strong></p> <p>As we can see, the circuit consists of a resistive voltage divider, seven analog comparators, a priority encoder, and an output latch.</p> <p>The voltage divider in figure 3 has a total resistance of 8R. The resistors are picked to produce seven equally-spaced reference voltages (i.e. V<sub>ref</sub>/16, 3V<sub>ref</sub>/16, 5V<sub>ref</sub>/16 . . . 15V<sub>ref</sub>/16 with each being separated by V<sub>ref</sub>/8). Each reference voltage feeds the inverting input of a comparator.</p> <p>The comparator outputs a HIGH if the voltage at its noninverting (or +) input is higher than the voltage at the inverting (or -) input. If the inverting input voltage is greater than the noninverting input voltage, the comparator output goes LOW.</p> <p>The analog voltage (V<sub>a</sub> in figure 3) is applied to the noninverting inputs of all comparators simultaneously, so if V<sub>a</sub> exceeds the reference voltage of a particular comparator that comparator’s output goes HIGH.</p> <p>This all seems wonderful, but flash analog to digital converters have one major drawback…</p> <p>In general, a flash ADC requires 2<sup>n</sup>-1 comparators to convert an analog signal to an n-bit binary code. The flash ADC in figure 3 only needs seven comparators, however, most applications call for an ADC with a higher resolution.</p> <p>Let’s say we want a more practical flash ADC that has a 10-bit resolution. Applying our formula from above tells us that this one requires 1,023 comparators!</p> <p>Manufacturing high resolution flash analog to digital converters quickly becomes unwieldy and expensive. This is because putting analog circuits on silicon isn’t always easy. This is a big disadvantage.</p> <p>Regardless, flash converters with 10-or-more-bit resolutions are available.</p> <h3><strong>Successive Approximation ADC<br /> </strong></h3> <p>Out of the ADCs this article covers, the successive approximation analog to digital converter is one of the more popular ones. In fact, these converters are often integrated into microcontrollers. This is likely because this ADC has a faster conversion time than the other methods with the exception of the flash ADC. However, the successive approximation converter is easier to implement in silicon (one comparator vs many) than the flash converter, as we now know.</p> <p>The basic idea behind it is something a computer programmer may be familiar with – the binary search.</p> <p>Assume the analog voltage we want to convert is within a well-defined range of binary numbers, say 0 to 255. A binary search narrows down progressively smaller binary fractions of the range of numbers.</p> <p>So, staying with the assumption that the analog value will yield a binary number from 0 to 255, we can find the value of the said number in no more than eight tries since 2<sup>8</sup> = 256.</p> <p>The first approximation will determine which half of the range the number is in. The second iteration finds which half of that half (or which quarter), the third finds the eighth and so on until we run out of bits and get an answer.</p> <h3 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h3> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="336" height="128" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 336px) 100vw, 336px" /></p> <p><strong><u>Ex 1:</u></strong></p> <p>Let’s do a quick example to clarify this concept. We’ll find the value of a number from 0 to 127. Let’s say the answer is 44, but the ADC doesn’t know that yet, so we’ll call it <em>x</em> for now.</p> <p>We’ll converge on the answer by asking a series of yes or no questions. Ready?</p> <p><strong>Step 1</strong>: The number is either in the upper or lower half of the range, so we cut the range in half:</p> <p>0-63, 64-127</p> <p>Is <em>x</em> ≥ 64? Nope, so 0 ≤ <em>x</em> ≤ 63.</p> <p><strong>Step 2</strong>: Cut remaining range in half: 0-31 and 32-63.</p> <p>Is <em>x</em> ≥ 32? Yep, so 32 ≤ <em>x</em> ≤ 63</p> <p><strong>Step 3</strong>: Cut remaining range in half again: 32-47 and 48-63.</p> <p>Is <em>x</em> ≥ 48? No way, so 32 ≤ <em>x</em> ≤ 47.</p> <p><strong>Step 4</strong>: Cut remaining range in half again (you knew we’d do that, didn’t you?): 32-39 and 40-47.</p> <p>Is <em>x</em> ≥ 40? Hell yeah, so 40 ≤ <em>x</em> ≤ 47.</p> <p><strong>Step 5</strong>: Rinse and repeat: 40-43 and 44-47.</p> <p>Is <em>x</em> ≥ 44? You bet, so 44 ≤ <em>x</em> ≤ 47.</p> <p><strong>Step 6</strong>: Halvies again: 44-45 and 46-47.</p> <p>Is <em>x</em> ≥ 46? Not a chance, so 44 ≤ <em>x</em> ≤ 45.</p> <p><strong>Step 7</strong>: cut ‘er in half one more time: 44 or 45.</p> <p>Is <em>x</em> ≥ 45? Nah, so <em>x</em> = 44.</p> <p>Notice how it took us exactly seven tries to converge on an answer because 2<sup>7</sup> = 128.</p> <p>Figure 4 depicts what something like this may look like if you hooked an oscilloscope to a successive approximation ADC during a conversion.</p> <p><img loading="lazy" decoding="async" class="alignnone wp-image-3913 size-full" src="http://www.circuitcrush.com/wp-content/uploads/Binary-Search-Scope-image.png" alt="Binary search successive approximation analog to digital converter" width="513" height="237" srcset="https://www.circuitcrush.com/wp-content/uploads/Binary-Search-Scope-image.png 513w, https://www.circuitcrush.com/wp-content/uploads/Binary-Search-Scope-image-300x139.png 300w, https://www.circuitcrush.com/wp-content/uploads/Binary-Search-Scope-image-150x69.png 150w" sizes="(max-width: 513px) 100vw, 513px" /></p> <p> </p> <p><strong><em>Figure 4: ADC scope output. Notice how the output bounces up and down with each try or iteration until the ADC converges on an answer at the end.</em></strong></p> <p>Before we go any further, let’s have a peek at a block diagram of a successive approximation analog to digital converter.</p> <p><img loading="lazy" decoding="async" class="alignnone wp-image-3914 size-full" src="http://www.circuitcrush.com/wp-content/uploads/Successive-Approximation-ADC.jpg" alt="Successive-Approximation-ADC" width="539" height="245" srcset="https://www.circuitcrush.com/wp-content/uploads/Successive-Approximation-ADC.jpg 539w, https://www.circuitcrush.com/wp-content/uploads/Successive-Approximation-ADC-300x136.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Successive-Approximation-ADC-150x68.jpg 150w" sizes="(max-width: 539px) 100vw, 539px" /></p> <p> </p> <p><strong><em>Figure 5: simplified block diagram of a successive approximation ADC.</em></strong></p> <p>One of the first things to notice about figure 5 is that successive approximation analog to digital converters contain a digital to analog converter (DAC). This may sound odd, but we’ll see why in a minute.</p> <p>The following gives a basic description of how this device works.</p> <p>First, the input bits of the DAC are set to 1 one at a time, starting with the most significant bit (MSB). As each bit is enabled, the comparator produces an output that indicates whether the analog input voltage is more or less than the output of the DAC. If the DAC output is greater, the comparator’s output goes LOW, which causes the bit in the successive approximation register to reset (become LOW or 0).</p> <p>If the DAC’s output is less than the analog input, the bit in the register stays at 1 or HIGH. This process starts with the MSB first, then the next most significant bit, then the next and so on. After the comparator tests all the bits of the DAC’s output (ending with the least significant bit or LSB) the conversion cycle completes.</p> <h3><strong>Dual Slope ADC<br /> </strong></h3> <p>Dual slope ADCs often find their way into digital multimeters, audio applications and more.</p> <p>The name of this analog to digital converter comes from the fact that the integrator output changes linearly over time, with two different slopes during the conversion process. You’ll see what I mean shortly.</p> <p>An integrator is a relatively simple op amp-based circuit. Its output accumulates the sum of all previous input values. Think of the integrator as a ramp generator. Figure 6 depicts such a circuit.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3915 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Op-Amp-Integrator.jpg" alt="Op-Amp-Integrator" width="443" height="196" srcset="https://www.circuitcrush.com/wp-content/uploads/Op-Amp-Integrator.jpg 443w, https://www.circuitcrush.com/wp-content/uploads/Op-Amp-Integrator-300x133.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Op-Amp-Integrator-150x66.jpg 150w" sizes="(max-width: 443px) 100vw, 443px" /></p> <p> </p> <p><strong><em>Figure 6: a basic op amp integrator.</em></strong></p> <p>Going into detail about the dual slope ADC’s method of operation requires some understanding of calculus (after all, it uses an integrator) which is beyond the scope of this post.</p> <p>However, I will attempt to give a basic overview of how this thing works. Take a peek at figure 7 for this discussion.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3916 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Dual-Slope-ADC.jpg" alt="Dual-Slope-ADC" width="482" height="568" srcset="https://www.circuitcrush.com/wp-content/uploads/Dual-Slope-ADC.jpg 482w, https://www.circuitcrush.com/wp-content/uploads/Dual-Slope-ADC-255x300.jpg 255w, https://www.circuitcrush.com/wp-content/uploads/Dual-Slope-ADC-127x150.jpg 127w" sizes="(max-width: 482px) 100vw, 482px" /></p> <p> </p> <p><strong><em>Figure 7: dual slope analog to digital converter block diagram.</em></strong></p> <p>First, a quick lesson on op amps and integrators.</p> <p>Remember that no current flows into the terminals of an ideal op amp. Also, the voltage on both terminals is the same. Notice that the positive input of the integrator in figure 7 is at ground. Because of this, the negative terminal is also at zero volts. This is known as a <strong><em>virtual ground</em></strong>.</p> <p>Rather than flowing into the op amp, the current flows into the capacitor, charging it up over time. This creates a line or a ramp.</p> <p>Let’s move on to the rest of the block diagram.</p> <p>Before conversion starts, an auto-zero circuit sets the comparator output to 0.</p> <p>Next, the analog input voltage causes the integrator output to ramp up (this is the first slope from figure 8 below). As soon as the integrator voltage becomes non-zero, the comparator enables a counter via the control logic.</p> <p>When that counter overflows, (flips to all zeros again because it can’t go any higher, like an odometer on a high mileage car), the integrator input is switched from the analog input voltage to -V<sub>ref</sub>. This causes the integrator output to move toward zero (the second, negative-going slope). The counter keeps counting (starting from zero after overflow) and when the integrator output hits zero the comparator disables it. The counter now contains the digital equivalent of the analog voltage.</p> <p>This works because the integrator output operates for a known time during the initial phase. This produces an output proportional to the input voltage. During the second phase, the output goes to zero at a known rate, reaching zero in a time proportional to the final voltage of the first phase.</p> <p>For those who like quick, easy to understand answers, what follows is the abridged version of the dual slope ADC’s operation. The dual slope analog to digital converter is based on counting the number of clock pulses during a capacitor charging process. If you forget everything else we covered so far, remember that.</p> <p>Figure 8 shows the integrator’s output during conversion. It’s easy to see where the dual slope ADC got its name from.</p> <p><img loading="lazy" decoding="async" class=" wp-image-3917 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Dual-Slope-ADC-Operation.gif" alt="Dual-Slope-ADC-Operation" width="557" height="212" /></p> <p> </p> <p><strong><em>Figure 8: its easy to see how this ADC got its name. The left half of the diagram depicts the integrator’s output during the first phase. The equation for the slope is also shown. The right part is the output of the integrator during the second phase. T is the time during the first phase and t<sub>x </sub>represents the time during the second phase. </em></strong></p> <p>The explanation on how it works may seem intimidating at first, but believe it or not, this ADC is simple and inexpensive. They are also very accurate and are able to reject noise. Since the parameters of the RC circuit in the integrator do not enter into the dual slope’s output, the stability of these components doesn’t matter much. Things like temperature and age can affect resistors and capacitors, but this converter is self-compensating. In fact, the clock frequency doesn’t even have to be highly stable.</p> <p>One short-coming is its relatively slow speed. This is mainly because the integration time is longer than it takes for, say, a successive approximation ADC to do its thing. Another disadvantage is that the dual slope ADC sports a conversion time that directly depends on the magnitude of the input signal.</p> <h3><strong>Sigma-Delta ADC<br /> </strong></h3> <p>One of the newer kids on the block, the sigma-delta analog to digital converter boasts conversions with very high accuracy. It also goes by the ∑-∆ ADC for the corresponding Greek letters. Some people transpose the letters and refer to it as the delta-sigma converter.</p> <p>For those who don’t know, the Greek letter sigma (∑) is the symbol for summation. Delta (∆) is the Greek letter representing change. So, one can think of sigma-delta as a <em>sum of changes</em>.</p> <p>Sigma-delta ADCs are also starting to show up in microcontrollers because they require a minimum of precision components thus making them are easier to realize in silicon.</p> <p>Figure 9 shows a typical simplified sigma-delta ADC block diagram.</p> <p><img loading="lazy" decoding="async" class="size-full wp-image-3918 alignnone" src="http://www.circuitcrush.com/wp-content/uploads/Sigma-Delta-Analog-to-Digital-Converter-ADC.jpg" alt="Sigma-Delta-Analog-to-Digital-Converter-ADC" width="747" height="290" srcset="https://www.circuitcrush.com/wp-content/uploads/Sigma-Delta-Analog-to-Digital-Converter-ADC.jpg 747w, https://www.circuitcrush.com/wp-content/uploads/Sigma-Delta-Analog-to-Digital-Converter-ADC-300x116.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Sigma-Delta-Analog-to-Digital-Converter-ADC-150x58.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Sigma-Delta-Analog-to-Digital-Converter-ADC-600x233.jpg 600w" sizes="(max-width: 747px) 100vw, 747px" /></p> <p><strong><em>Figure 9: typical simplified delta-signa ADC block diagram. The summing junction is often a difference amp. Also note the presence of an integrator and a DAC.</em></strong></p> <p>Sigma-delta converters are unusual in that their output is a serial stream of bits rather than a multi-bit parallel value. But it is this property that enables them to produce a highly accurate digital output up to 24 bits that parallel converters (like the flash ADC) simply cannot attain.</p> <p>Also, noise levels can be kept very low with the use of digital filtering (not shown in figure 9). This can, however, be a double edge sword and can be a disadvantage for high-speed conversion due to the need for other high-speed digital circuits to achieve this.</p> <p>Sigma-delta ADCs can be confusing, but I’ll do my best to explain them. What follows is the basic gist of how a sigma-delta analog to digital converter works.</p> <p>The circuit starts by integrating an input value and sending 1 or 0 to the DAC (via the comparator) depending on the integrator’s output relative to ground. The comparator generates a 1 if the input signal has increased. If it has decreased, it generates a 0. The DAC has two reference voltages (not shown in figure 9): +V<sub>ref</sub> and -V<sub>ref</sub>. It takes the comparator’s output and switches one of the two reference voltages into the summing junction (which is usually a difference amplifier). The difference amp (or summing junction in figure 9) subtracts the DAC’s output from the input voltage and feeds this to the integrator.</p> <p>In other words, the integrator sums the previous changes introduced by the DAC in the circuit’s feedback loop. This continues for a certain number of iterations and each iteration generates a bit in the serial output stream. The number of 1s in this stream is proportional to the fraction of full scale that represents the analog input voltage.</p> <h2><strong>Hold it Now! Practical Analog to Digital Converters<br /> </strong></h2> <p>For the sake of easier explanation, we’ve been assuming that the analog input voltage to the ADCs we’ve covered is constant.</p> <p>But many analog signals are not constant. The problem with this is that in order for an ADC to work correctly and give us an accurate result the input signal needs to be constant or <em>very</em> slowly varying.</p> <p>This is because the conversion process is not instantaneous and takes a finite amount of time. The incoming analog signal might be changing at a rate higher than the ADC conversion rate.</p> <p>The answer to this is something called a <strong>sample and hold circuit</strong>.</p> <p>This is becoming a long post, so I won’t go into any great detail of how they work. The basic gist is that they sample the input at periodic intervals and <strong><em>hold</em></strong> the value long enough for the conversion to take place.</p> <p>Sample and hold circuitry is almost always necessary. Let’s quickly gloss over an example to prove it. I won’t bore you with the details on how I got the answer, so you’ll just have to trust me.</p> <p>Say we have a 12-bit successive approximation ADC without a sample and hold circuit. Assume it takes 1 microsecond for each of the 12 steps needed for the complete conversion. This gives us a total conversion time of 12 microseconds.</p> <p>Let’s make the input a sine wave of constant frequency. Without the sample and hold, our ADC is limited to a frequency of only about 3 Hz even though it only takes 12 microseconds to do a conversion! This is clearly impractical for many applications.</p> <p>The take-away: you probably need a sample and hold circuit if it isn’t already built into your ADC.</p> <h2><strong>Wrapping up Analog to Digital Converters<br /> </strong></h2> <p>I’m starting to feel a case of information overload coming on and we haven’t even talked about ADC performance specs or choosing the right ADC. Nor did we go into great detail on Nyquist or about how the ADCs in this article work.</p> <p>And of course, there are other types of ADCs that we didn’t even discuss.</p> <p>Yep, like most topics concerning electronics there’s a lot more to say about analog to digital converters, but I’ll save that for later.</p> <p>In the future we’ll delve into the above topics and maybe some related topics like digital filtering and more detail on sample and hold circuits.</p> <p>Meanwhile, drop a comment and tell me about your latest microcontroller-driven project. Are you using the ADC? What sort of analog data are you trying to measure and manipulate?</p> <p>I’d love to hear about it!</p> <h2 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h2> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="570" height="217" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 570px) 100vw, 570px" /></p> <a target="_blank" href="https://www.drpeterscode.com/index.php"><img src="https://www.circuitcrush.com/wp-content/plugins/dpabottomofpostpage/apixel1x1.jpg" ></a><table></table>]]></content:encoded> <wfw:commentRss>https://www.circuitcrush.com/analog-digital-converters-tutorial/feed/</wfw:commentRss> <slash:comments>2</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">3909</post-id> </item> <item> <title>Test Your Knowledge with Electronics Quiz #3</title> <link>https://www.circuitcrush.com/electronics-quiz-3/</link> <comments>https://www.circuitcrush.com/electronics-quiz-3/#comments</comments> <dc:creator><![CDATA[Brian]]></dc:creator> <pubDate>Sun, 19 Jan 2020 17:12:12 +0000</pubDate> <category><![CDATA[Electronics]]></category> <category><![CDATA[electronics]]></category> <category><![CDATA[Quiz]]></category> <guid isPermaLink="false">https://www.circuitcrush.com/?p=3872</guid> <description><![CDATA[It’s been almost 2 years since the last electronics related quiz, so it’s time for our third installment! As before, the quiz is here to assess your knowledge, perhaps help you learn something along the way, and most of all, have some fun. This electronics quiz will be similar to the last. The answers to […]]]></description> <content:encoded><![CDATA[<p>It’s been almost 2 years since the <a href="https://www.circuitcrush.com/electronics-quiz-2/" target="_blank" rel="noopener noreferrer">last electronics related quiz</a>, so it’s time for our third installment! As before, the quiz is here to assess your knowledge, perhaps help you learn something along the way, and most of all, have some fun.</p> <p><span id="more-3872"></span></p> <p>This electronics quiz will be similar to the last.</p> <p><span id="more-1531"></span>The answers to all the questions in this quiz are hiding in the various blog posts on this site.</p> <p>As usual, the questions aren’t engineering level questions and aren’t terribly difficult. For some, you may know the answer right away; for others you may need to browse some of the posts to find an answer.</p> <p><u>Hint</u>: the search box is your helpful friend.</p> <p><strong>And, if you find yourself reading a post, be sure to leave your thoughts and suggestions in the comments section.</strong></p> <p>First, you’ll see the questions.</p> <p>There are 12 questions. After the last one, I’ll post the answers to each question with an explanation (or I’ll work the problem out, if appropriate). I’ll also post a link to the appropriate post with each answer.</p> <p>Ready to go?</p> <p>Remember, no cheating!</p> <p>Now let’s test your electrical knowledge once again…</p> <p> </p> <h1>Electronics Quiz #3</h1> <p>1) Another name for a band reject filter is a ______________________ filter.</p> <p>2) A BJT in saturation is comparable to this common mechanical device (2 words) _____________ _______________.</p> <p>3) Array indices in C programming start at what number?</p> <p>4) OBD II has been required in cars sold in the U.S. since what year?</p> <p>5) Normally, voltage and current are:</p> <p>a) Inversely proportional<br /> b) Good friends<br /> c) Proportional<br /> d) A hot mess</p> <p>6) In C programming, what’s the difference between = and == ?</p> <p>7) You want your robot to be able to sense shock and sound an alarm. That way you’ll know if your sadistic sibling kicks it. One sensor you might use for this is a ________________________________.</p> <p>8) Servo motors rely on _______________ to position themselves correctly.</p> <p>9) LEDs don’t like too much current and should always have a resistor in series with them. How much current flows though the LED in figure 1? Assume a 5 V source, a 0.7 V drop across the LED, and that the resistor = 240 Ω.</p> <figure id="attachment_1651" aria-describedby="caption-attachment-1651" style="width: 300px" class="wp-caption alignleft"><img loading="lazy" decoding="async" class="wp-image-1651 size-medium" src="http://www.circuitcrush.com/wp-content/uploads/LED-and-Resistor-300x211.jpg" alt="Resistor and LED" width="300" height="211" srcset="https://www.circuitcrush.com/wp-content/uploads/LED-and-Resistor-300x211.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/LED-and-Resistor-600x421.jpg 600w, https://www.circuitcrush.com/wp-content/uploads/LED-and-Resistor-150x105.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/LED-and-Resistor-768x539.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/LED-and-Resistor.jpg 961w" sizes="(max-width: 300px) 100vw, 300px" /><figcaption id="caption-attachment-1651" class="wp-caption-text"><strong> Figure 1</strong></figcaption></figure> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p>10) There is one type of control structure that you’ll often pair with arrays in C programming. What is it?</p> <p>11) MOSFETs are controlled by ____________ while BJTs are controlled by__________________.</p> <p>12) The number of other gates a particular logic gate can drive at its output is its ________________________.</p> <p> </p> <p><strong>Congratulations! </strong></p> <p>You survived electronics quiz 3. To keep everyone honest, the answers are written in invisible ink. To reveal them, simply highlight the area below with your mouse. <em>This is a little trickier on a phone or tablet, but you’re smart, so you’ll figure it out.</em></p> <h3 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h3> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="331" height="126" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 331px) 100vw, 331px" /></p> <h1>Electronics Quiz #3 Answers</h1> <p><span style="color: #ffffff;">1) Another name for a band reject filter is a <em>notch</em> filter.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/electrical-filters-intro/" target="_blank" rel="noopener noreferrer">Intro to Electrical Filters</a></span></p> <p><span style="color: #ffffff;">2) A BJT in saturation acts like a closed switch.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/what-is-a-transistor/" target="_blank" rel="noopener noreferrer">An Introduction to Transistors</a></span></p> <p><span style="color: #ffffff;">3) Array indices start at 0 in C.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/c-programming-tutorial-6-arrays-intro/" target="_blank" rel="noopener noreferrer">C Programming Tutorial 6: Intro to Arrays in C</a></span></p> <p><span style="color: #ffffff;">4) 1996.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/how-obd-ii-works/" target="_blank" rel="noopener noreferrer">How OBD-II Vehicle Diagnostics Work</a></span></p> <p><span style="color: #ffffff;">5) c) Proportional. But voltage and current have been known to get along well.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/what-is-voltage/" target="_blank" rel="noopener noreferrer">Back to the Basics: What is Voltage?</a></span></p> <p><span style="color: #ffffff;">6) In C, the = is the assignment operator which assigns a certain value to a variable. The == is the equality operator which finds use in comparisons and statements such as</span></p> <p><span style="color: #ffffff;">if (year == 2020)</span><br /> <span style="color: #ffffff;">//do something fun</span><br /> <span style="color: #ffffff;">else</span><br /> <span style="color: #ffffff;">//sleep until 2020</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/c-programming-tutorial-3/" target="_blank" rel="noopener noreferrer">C Programming Tutorial 3: Arithmetic & Logic in C</a></span></p> <p><span style="color: #ffffff;">7) Use an accelerometer. They often come with a gyroscope in the same package.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/common-types-of-sensors/" target="_blank" rel="noopener noreferrer">Intro to Common Sensors You’ll Use in Your Projects</a></span></p> <p><span style="color: #ffffff;">8) Feedback. Servos need to know their current position and how far they’ve moved to get to the right spot. Feedback accomplishes this.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/servo-motor-introduction/" target="_blank" rel="noopener noreferrer">An Introduction to Servo Motors</a></span></p> <p><span style="color: #ffffff;">9) This is a series circuit, so the same amount of current will flow through the resistor and the LED. Because 0.7 V drops across the LED, we know that 4.3 V drops across the resistor. Using this information, we get the current through the LED:<br /> I = V/R = 4.3/240 = 17.9 mA.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/circuit-analysis/" target="_blank" rel="noopener noreferrer">Simple Circuit Analysis Techniques You Should Know</a></span></p> <p><span style="color: #ffffff;">10) <i>for</i> loops and arrays are a match from heaven and are perfect for each other.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/c-programming-tutorial-6-arrays-intro/" target="_blank" rel="noopener noreferrer">C Programming Tutorial 6: Intro to Arrays in C</a></span></p> <p><span style="color: #ffffff;">11) MOSFETs are controlled by <em>voltage</em> while BJTs are controlled by <em>current</em>.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/what-is-a-transistor/" target="_blank" rel="noopener noreferrer">An Introduction to Transistors</a></span></p> <p><span style="color: #ffffff;">12) The number of other gates a particular logic gate can drive at its output is its <em>fanout</em>.<br /> Logic gates are electrical devices with finite current-driving capabilities. Because of this, there is a limit to the amount of gates a given logic gate can drive.</span></p> <p><span style="color: #ffffff;">Post: <a style="color: #ffffff;" href="https://www.circuitcrush.com/logic-gates-tutorial-2-electrical-properties/" target="_blank" rel="noopener noreferrer">Tutorial on Logic Gates Part 2: Electrical Properties of Gates</a></span></p> <h2></h2> <p> </p> <h2>How’d You Do on Electronics Quiz #3?</h2> <p>So, if you read (or at least skimmed) the right posts, you should have scored 100%, regardless of your level of electronics experience. If you scored an A or a B without reading or skimming any of the posts, props to you!</p> <p>Like last time, because all the answers are freely available on this blog, I won’t use a grading scale like I did with the first quiz. If you didn’t score 100%, go back and read the appropriate posts.</p> <p><strong>Were the questions too easy? Too hard? Were there too many or too few questions? </strong></p> <p><strong>Leave us a comment and tell us how you did and your thoughts!</strong></p> <h2 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h2> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="439" height="167" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 439px) 100vw, 439px" /></p> <a target="_blank" href="https://www.drpeterscode.com/index.php"><img src="https://www.circuitcrush.com/wp-content/plugins/dpabottomofpostpage/apixel1x1.jpg" ></a><table></table>]]></content:encoded> <wfw:commentRss>https://www.circuitcrush.com/electronics-quiz-3/feed/</wfw:commentRss> <slash:comments>6</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">3872</post-id> </item> <item> <title>C Programming Tutorial 7: More on Arrays in C</title> <link>https://www.circuitcrush.com/c-programming-tutorial-7-arrays-2/</link> <comments>https://www.circuitcrush.com/c-programming-tutorial-7-arrays-2/#comments</comments> <dc:creator><![CDATA[Brian]]></dc:creator> <pubDate>Thu, 12 Dec 2019 21:32:09 +0000</pubDate> <category><![CDATA[C Programming]]></category> <category><![CDATA[C programming]]></category> <guid isPermaLink="false">https://www.circuitcrush.com/?p=3837</guid> <description><![CDATA[Welcome to C Programming Tutorial 7, Arrays in C Part 2! C Tutorial 6 was an introduction to arrays in C. This time, we’re going to go into a little bit more detail about arrays after a quick review. Let’s do this! Arrays in C Programming Part 2 Review of Array Basics An array in […]]]></description> <content:encoded><![CDATA[<p>Welcome to C Programming Tutorial 7, Arrays in C Part 2!</p> <p><a href="https://www.circuitcrush.com/c-programming-tutorial-6-arrays-intro/" target="_blank" rel="noopener noreferrer">C Tutorial 6 was an introduction to arrays</a> in C.</p> <p>This time, we’re going to go into a little bit more detail about arrays after a quick review.</p> <p>Let’s do this!</p> <p><span id="more-3837"></span></p> <h1><strong>Arrays in C Programming Part 2<br /> </strong></h1> <h2><strong>Review of Array Basics<br /> </strong></h2> <p>An array in C programming is a group of sequential locations in memory that hold one data type such as integers, floats, or chars. An array in C can only hold one data type, so don’t try to create an array that mixes integers with floats, for example.</p> <p>There are a few different ways to declare an array in C.</p> <p>We can initialize an array with values if we already know what the array should contain. For example, letters[] is an array of four characters:</p> <pre>char letters[4] = {A,B,C,D}; /*declares and initializes an array of 4 characters.*/</pre> <p>Often though, we don’t know ahead of time what the array is going to contain, so we can’t initialize it. For example, who_knows is an array of fifty integers, but we don’t know what their exact value is yet.</p> <pre>int who_knows[50]; /*declares an array of 50 integers, which will take on values later as the program runs */</pre> <p>Array indexing starts at 0, not 1. This is a VERY important thing to remember because forgetting it can cause hard-to-find errors. People — even those with C programming experience, make this mistake all the time. Figure 1 is from the first C tutorial on arrays, but here it is again just to drive the point home.</p> <p><img loading="lazy" decoding="async" class="alignnone wp-image-3203 " src="http://www.circuitcrush.com/wp-content/uploads/Arrays-in-C-Programming-1024x576.jpg" alt="Arrays in C" width="702" height="395" srcset="https://www.circuitcrush.com/wp-content/uploads/Arrays-in-C-Programming-1024x576.jpg 1024w, https://www.circuitcrush.com/wp-content/uploads/Arrays-in-C-Programming-600x338.jpg 600w, https://www.circuitcrush.com/wp-content/uploads/Arrays-in-C-Programming-150x84.jpg 150w, https://www.circuitcrush.com/wp-content/uploads/Arrays-in-C-Programming-300x169.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Arrays-in-C-Programming-768x432.jpg 768w, https://www.circuitcrush.com/wp-content/uploads/Arrays-in-C-Programming.jpg 1280w" sizes="(max-width: 702px) 100vw, 702px" /></p> <p><strong><em>Figure 1: Like a character from a bad horror flick, it’s back! Here is a graphical representation of array indexing in C. The first element in the array Num[] is indexed at position 0.</em></strong></p> <p>Arrays and for loops are best friends that go way, way back. You’ll use arrays with for loops all the time.</p> <p>In an effort to not regurgitate everything from the last C tutorial, I’ll stop the review here. If you want a more in depth review on the basics of arrays in C programming see <a href="https://www.circuitcrush.com/c-programming-tutorial-6-arrays-intro/" target="_blank" rel="noopener noreferrer">C Programming Tutorial 6: Intro to Arrays in C</a>.</p> <h2><strong>Designated Initializers – Another Way to Initialize Arrays in C<br /> </strong></h2> <p>With C99 came a new capability called designated initializers.</p> <p>This feature allows the programmer to pick and choose which elements to initialize. For example, suppose that you just want to initialize the last element in an array. Using traditional C initialization syntax, you also have to initialize every element preceding the last one:</p> <pre>int repetitive_and_boring[7] = {0,0,0,0,0,0,339};</pre> <p>With this method, you can use an index in brackets in the initialization list to specify a particular element of the array:</p> <pre>int better_way[7] = {[6] = 339}; /* initializes last element of better_way[] to 339 */</pre> <p>The rest of the elements in our example above are simply set to 0.</p> <p>And here’s another cool thing about designated initializers – you can initialize more than one element if you wish, as in the example below.</p> <pre>int pretty_slick[10] = {[0]=1, [4]=2, [8]=3}; /* initializes elements 0, 4, and 8 to 1, 2, and 3 */</pre> <p>We can also write something like the following code fragment:</p> <pre>int days[12] = {31,28,[4]=31,30,31,[1]=28};</pre> <p>for clarity, the complete C program prints the number of days in each month (well, some of them) and may look something like this:</p> <pre>#include <stdio.h> int main(void) { int days[12] = {31,28,[4]=31,30,31,[1]=29}; for (int i = 0; i < 12; i++) printf("%2d %d\n", i + 1, days[i]); return 0; }</pre> <p>The output of the above code looks something like this:</p> <pre>1 31 2 29 3 0 4 0 5 31 6 30 7 31 8 0 9 0 10 0 11 0 12 0</pre> <p>There are a few interesting things to note about the output.</p> <p>First, if the code follows a designated initializer with more values, like the sequence [4] = 31, 30, 31, these values are used to initialize the subsequent elements. In other words, after initializing days[4] to 31, the code initializes days[5] and days[6] to 30 and 31, respectively.</p> <p>Second, if the code initializes a certain element to a value more than once, the last initialization is the one that wins. For example, the start of the initialization list initializes days[1] to 28, but the last initialization [1] = 29 overrides it later, so the output is 29, not 28.</p> <p>Finally, the rest of the elements are automatically set to 0.</p> <p>Before we move on, I have a word of warning for all Arduino and C++ enthusiasts.</p> <p><strong><em>Neither C++ nor the Arduino IDE support this as of the time of this writing</em></strong>.</p> <p>However, C PIC programmers should be safe.</p> <h3 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h3> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="339" height="129" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 339px) 100vw, 339px" /></p> <h2><strong>Multidimensional Arrays in C<br /> </strong></h2> <p>Pretend for a moment that you want to make a home-brew weather station. You’re an ambitious person and in this for the long haul, so you decide to track monthly rainfall over a period of five years.</p> <p>First, you think about using an array with 60 elements, but perhaps it’s more elegant (and smart) if you keep each year’s data separate. Another alternative is to use five arrays, each with 12 elements, but that is clumsy and could get really nutso if you decide to track 20 years’ worth of rainfall (remember, you’re in this for the long haul).</p> <p>The smarter, slicker approach is to use an array of arrays. The master array would have five elements, one for each year. Each of those elements, in turn, would be a 12-element array — one for each month. Here is how to declare such an array:</p> <pre>float rain[5][12]; /* array of 5 arrays of 12 floats */</pre> <p>So how do we interpret this?</p> <p>One way to do so is to first look at the inner portion (the [5] part). It tells us that rain[] is an array with five elements. But what the heck are those elements?</p> <p>Now have a peek at the remaining part of the declaration (the [12] part). This tells us that each element is of type float[12], that is, each of the five elements of rain[] is, in itself, an array of 12 floats.</p> <p>Toward that end, rain[0], being the first element of rain[], is an array of 12 values. So are rain[1], rain[2], etc. So, if rain[0] is an array, its first element is rain[0][0], its second element is rain[0][1] and so on. In short, rain[] is a five-element array of 12-element arrays of floats, rain[0] is an array of 12 floats, and rain[0][0] is a float.</p> <p>To access, say, the value in row 3, column 4, use rain[3][4] (Remember, array indexing starts at 0, so row 3 is the fourth row, with row 0 being the first row).</p> <p>If this is confusing (which is was to me when I first learned about multidimensional arrays) take a look at figure 2.</p> <p><img loading="lazy" decoding="async" class="alignnone wp-image-3838 size-full" src="http://www.circuitcrush.com/wp-content/uploads/Multidimensional-Arrays-in-C.jpg" alt="Multidimensional-Arrays-in-C" width="553" height="264" srcset="https://www.circuitcrush.com/wp-content/uploads/Multidimensional-Arrays-in-C.jpg 553w, https://www.circuitcrush.com/wp-content/uploads/Multidimensional-Arrays-in-C-300x143.jpg 300w, https://www.circuitcrush.com/wp-content/uploads/Multidimensional-Arrays-in-C-150x72.jpg 150w" sizes="(max-width: 553px) 100vw, 553px" /></p> <p> </p> <p><strong><em>Figure 2: You can visualize this array as a two-dimensional array consisting of five rows, each of 12 columns. By changing the second subscript, you move along a row, month by month. By changing the first subscript, you move vertically along a column, year by year.</em></strong></p> <p>Remember, internally, this array is stored sequentially in memory, beginning with the first 12-element array, followed by the second 12-element array, and so on.</p> <p>Everything we know about two-dimensional arrays applies to three-dimensional arrays and above, though I don’t recommend going more than three dimensions as it becomes unwieldy after that.</p> <p>You can declare a three-dimensional array this way:</p> <pre>int three_dee[10][15][20];</pre> <p>To aid in visualization, think of a one-dimensional array as a row of data, a two-dimensional array as a table of data, and a three-dimensional array as a stack of data tables. For example, you can visualize the three-dee[] array as 10 two-dimensional arrays (each 15×20) stacked atop each other.</p> <p>The other way to think of three-dee[] is as an array of arrays of arrays. So, it is a 10-element array, each element of which is a 15-element array. Each 15-element array then has elements that are 20-element arrays. Or, you can simply think of arrays in terms of the number of indices needed.</p> <h2><strong>How to Initialize a Multidimensional Array<br /> </strong></h2> <p>Initializing a two-dimensional array builds on the technique for initializing a one-dimensional array.</p> <p>We’ll stick with two dimensions for the purposes of demonstration and clarity. Going back to our rain tracking example, suppose we already have five years’ worth of rainfall data we want to load into the program. In this case, we need to initialize our two-dimensional array rain[] with the data we have. To do so, we need to do something like this:</p> <pre>const float rain[12][5] = { {4.3, 5.3, 6.3, 3.0, 2.0, 1.2, 0.2, 0.2, 0.4, 2.4, 3.5, 6.6}, /*rainfall data year 1*/ {6.5, 8.5, 1.2, 1.6, 2.4, 0.0, 5.2, 0.9, 0.3, 0.9, 1.4, 7.3}, /*rainfall data year 2*/ {9.1, 7.5, 6.7, 4.3, 3.1, 0.8, 0.2, 1.2, 1.1, 2.5, 6.1, 8.4}, /*rainfall data year 3*/ {5.2, 9.9, 6.4, 3.3, 1.2, 2.8, 0.4, 0.0, 0.6, 1.6, 5.3 ,6.2}, /*you get it now*/ {1.6, 5.7, 6.8, 3.4, 3.5, 1.2, 0.9, 0.4, 1.6, 1.6, 3.6, 7.2} };</pre> <p>A few notes on initializing multidimensional arrays are in order.</p> <p>First, since the array holds data that should not be modified, we’re using the const modifier when declaring the array. After all, these values represent rain fall from the past and we’re not going to travel back in time and change the weather.</p> <p>Second, the initialization uses five lists of numbers, each of which are enclosed by braces. All five lists are enclosed by one outer set of braces. You could omit the interior braces and just retain the two outermost braces. As long as you have the right number of entries, the effect is the same. However, this tends to be confusing, especially if you come back later to modify the program, so I don’t recommend doing this.</p> <p>The data in the first interior set of braces is assigned to the first row of the array, the data in the second interior set goes to the second row, and so on.</p> <p>Finally, the rules about mismatches between data and array sizes apply to each row (see <a href="https://www.circuitcrush.com/c-programming-tutorial-6-arrays-intro/" target="_blank" rel="noopener noreferrer">C Programming Tutorial 6</a> for a review on this). That is, if the first inner set of braces encloses 10 numbers, only the first 10 elements of the first row are affected. The last two elements in that row are then initialized by default to zero. If there are too many numbers, it is an error; the numbers do not move to the next row.</p> <h2><strong>An Array of Information<br /> </strong></h2> <p>This wraps up our treatment of arrays in C programming for now.</p> <p>You’ll see and use arrays a lot if you do any C programming, program microcontrollers, or are an Arduino enthusiast. Don’t be afraid of them and don’t forget to pair them with your <em>for</em> loops! The two are a perfect match for each other.</p> <p>Drop me a comment and let me know what you thought of this tutorial. Or, tell me about your latest C programming or microcontroller-driven project. I love to hear about that stuff.</p> <p>Until next time, keep making!</p> <h2 style="text-align: center;">Become the Maker you were born to be. Try <a href="https://learnarduinonow.com">Arduino Academy</a> for FREE!</h2> <p><img loading="lazy" decoding="async" class="aligncenter wp-image-4238" src="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png" alt="" width="533" height="203" srcset="https://www.circuitcrush.com/wp-content/uploads/FB_Cover2.png 828w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-300x114.png 300w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-150x57.png 150w, https://www.circuitcrush.com/wp-content/uploads/FB_Cover2-768x292.png 768w" sizes="(max-width: 533px) 100vw, 533px" /></p> <a target="_blank" href="https://www.drpeterscode.com/index.php"><img src="https://www.circuitcrush.com/wp-content/plugins/dpabottomofpostpage/apixel1x1.jpg" ></a><table></table>]]></content:encoded> <wfw:commentRss>https://www.circuitcrush.com/c-programming-tutorial-7-arrays-2/feed/</wfw:commentRss> <slash:comments>5</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">3837</post-id> </item> </channel> </rss>