Category Archives: Arduino小组

Resistors

Take a Stance, The Resist Stance

Resistors - the most ubiquitous of electronic components. They are a critical piece in just about every circuit. And they play a major role in our favorite equation, Ohm’s Law.

resistors

In this, our pièce de résistance, we’ll cover:

  • What is a resistor?!
  • Resistor units
  • Resistor circuit symbol(s)
  • Resistors in series and parallel
  • Different variations of resistors
  • Color coding decoding
  • Surface mount resistor decoding
  • Example resistor applications

Consider reading…

Some of the concepts in this tutorial build on previous electronics knowledge. Before jumping into this tutorial, consider reading (at least skimming) these first:


Resistor Basics

Resistors are electronic components which have a specific, never-changing electrical resistance. The resistor’s resistance limits the flow of electrons through a circuit.

They are passive components, meaning they only consume power (and can’t generate it). Resistors are usually added to circuits where they complement active components like op-amps, microcontrollers, and other integrated circuits. Commonly resistors are used to limit current, divide voltages, and pull-up I/O lines.

Resistor units

The electrical resistance of a resistor is measured in ohms. The symbol for an ohm is the greek capital-omega: Ω. The (somewhat roundabout) definition of 1Ω is the resistance between two points where 1 volt (1V) of applied potential energy will push 1 ampere (1A) of current.

As SI units go, larger or smaller values of ohms can be matched with a prefix like kilo-, mega-, or giga-, to make large values easier to read. It’s very common to see resistors in the kilohm (kΩ) and megaohm (MΩ) range (much less common to see miliohm (mΩ) resistors). For example, a 4,700Ω resistor is equivalent to a 4.7kΩ resistor, and a 5,600,000Ω resistor can be written as 5,600kΩ or (more commonly as) 5.6MΩ.

Schematic symbol

All resistors have two terminals, one connection on each end of the resistor. When modeled on a schematic, a resistor will show up as one of these two symbols:

Resistor schematic symbols

Two common resistor schematic symbols. R1 is an American-style 1kΩ resistor, and R2 is an international-style 47kΩ resistor.

The terminals of the resistor are each of the lines extending from the squiggle (or rectangle). Those are what connect to the rest of the circuit.

The resistor circuit symbols are usually enhanced with both a resistance value and a name. The value, displayed in ohms, is obviously critical for both evaluating and actually constructing the circuit. The name of the resistor is usually an R preceding a number. Each resistor in a circuit should have a unique name/number. For example, here’s a few resistors in action on a 555 timer circuit:

Example schematic with resistors - a 555 timer

In this circuit, resistors play a key role in setting the frequency of the 555 timer’s output. Another resistor (R3) limits the current through an LED.


Types of Resistors

Resistors come in a variety of shapes and sizes. They might be through-hole or surface-mount. They might be a standard, static resistor, a pack of resistors, or a special variable resistor.

Termination and mounting

Resistors will come in one of two termination-types: through-hole or surface-mount. These types of resistors are usually abbreviated as either PTH (plated through-hole) or SMD/SMT (surface-mount technology or device).

Through-hole resistors come with long, pliable leads which can be stuck into a breadboard or hand-soldered into a prototyping board or printed circuit board (PCB). These resistors are usually more useful in breadboarding, prototyping, or in any case where you’d rather not solder tiny, little 0.6mm-long SMD resistors. The long leads usually require trimming, and these resistors are bound to take up much more space than their surface-mount counterparts.

The most common through-hole resistors come in an axial package. The size of an axial resistor is relative to its power rating. A common ½W resistor measures about 9.2mm across, while a smaller ¼W resistor is about 6.3mm long.

1/4 and 1/2 watt resistors

A half-watt (½W) resistor (above) sized up to a quarter-watt (¼W).

Surface-mount resistors are usually tiny black rectangles, terminated on either side with even smaller, shiny, silver, conductive edges. These resistors are intended to sit on top of PCBs, where they’re soldered onto mating landing pads. Because these resistors are so small, they’re usually set into place by a robot, and sent through an oven where solder melts and holds them in place.

SMD resistor on a quarter

A tiny 0603 330Ω resistor hovering over shiny George Washington’s nose on top of a U.S. quarter.

SMD resistors come in standardized sizes; usually either 0805 (0.8mm long by 0.5mm wide), 0603, or 0402. They’re great for mass circuit-board-production, or in designs where space is a precious commodity. They take a steady, precise hand to manually solder, though!

Resistor composition

Resistors can be constructed out of a variety of materials. Most common, modern resistors are made out of either a carbon, metal, or metal-oxide film. In these resistors, a thin film of conductive (though still resistive) material is wrapped in a helix around and covered by an insulating material. Most of the standard, no-frills, through-hole resistors will come in a carbon-film or metal-film composition.

Peeled away view of carbon-film resistors

Peek inside the guts of a few carbon-film resistors. Resistance values from top to bottom: 27Ω, 330Ω and a 3.3MΩ. Inside the resistor, a carbon film is wrapped around an insulator. More wraps means a higher resistance. Pretty neat!

Other through-hole resistors might be wirewound or made of super-thin metallic foil. These resistors are usually more expensive, higher-end components specifically chosen for their unique characteristics like a higher power-rating, or maximum temperature range.

Surface-mount resistors are usually either thick or thin-film variety. Thick-film is usually cheaper but less precise than thin. In both resistor types, a small film of resistive metal alloy is sandwiched between a ceramic base and glass/epoxy coating, and then connected to the terminating conductive edges.

Special resistor packages

There are a variety of other, special-purpose resistors out there. Resistors may come in pre-wired packs of five-or-so resistor arrays. Resistors in these arrays may share a common pin, or be set up as voltage dividers.

Resistor Network

An array of five 330Ω resistors, all tied together at one end.

Resistors don’t have to be static either. Variable resistors, known as rheostats, are resistors which can be adjusted between a specific range of values. Similar to the rheostat is the potentiometer. Pots connect two resistors internally, in series, and adjust a center tap between them creating an adjustable voltage divider. These variable resistors are often used for inputs, like volume knobs, which need to be adjustable.

A smattering of potentiometers

A smattering of potentiometers. From top-left, clockwise: a standard 10k trimpot, 2-axis joystick, softpot, slide pot, classic right-angle, and a breadboard friendly 10k trimpot.


Decoding Resistor Markings

Though they may not display their value outright, most resistors are marked to show what their resistance is. PTH resistors use a color-coding system (which really adds some flair to circuits), and SMD resistors have their own value-marking system.

Decoding the color bands

Through-hole, axial resistors usually use the color-band system to display their value. Most of these resistors will have four bands of color circling the resistor.

Resistors showing their stripes

The first two bands indicate the two most-significant digits of the resistor’s value. The third band is a weight value, which multiplies the two significant digits by a power of ten.

The final band indicates the tolerance of the resistor. The tolerance explains how much more or less the actual resistance of the resistor can be compared to what its nominal value is. No resistor is made to perfection, and different manufacturing processes will result in better or worse tolerances. For example, a 1kΩ resistor with 5% tolerance could actually be anywhere between 0.95kΩ and 1.05kΩ.

How do you tell which band is first and last? The last, tolerance band is often clearly separated from the value bands, and usually it’ll either be silver or gold.

Here’s a table of each of the colors and which value, multiplier or tolerance they represent:

Color Digit value Multiplier Multiplied Out Tolerance
Black 0 100 1
Brown 1 101 10
Red 2 102 100
Orange 3 103 1,000
Yellow 4 104 10000
Green 5 105 100,000
Blue 6 106 1,000,000
Violet 7 107 10,000,000
Gray 8 108 100,000,000
White 9 109 1,000,000,000
Gold ±5%
Silver ±10%

Here’s an example of a 4.7kΩ resistor with four color bands:

Close-up of a 4.7kOhm resistor

When decoding the resistor color bands, consult a resistor color code table like the one above. For the first two bands, find that color’s corresponding digit value. The 4.7kΩ resistor has color bands of yellow and violet to begin - which have digit values of 4 and 7 (47). The third band of the 4.7kΩ is red, which indicates that the 47 should be multiplied by 102 (or 100). 47 times 100 is 4,700!

If you’re trying to commit the color band code to memory, a mnemonic device might help. There are a handful of (sometimes unsavory) mnemonics out there, to help remember the resistor color code. A good one, which spells out the difference between black and brown is:

"Big brown rabbits often yield great big vocal groans when gingerly snapped."

Or, if you remember “ROY G. BIV”, subtract the indigo (poor indigo, no one remembers indigo), and add black and brown to the front and gray and white to the back of the classic rainbow color-order.

Color Code Calculator

If you’d rather skip the math (we won’t judge :), and just use a handy calculator, give this a try!

 

Band 1 Band 2 Band 3 Band 4
Value 1 (MSV) Value 2 Weight Tolerance

Resistance:

1,000 Ω ±5%

Decoding surface-mount markings

SMD resistors, like those in 0603 or 0805 packages, have their own way of displaying their value. There are a few common marking methods you’ll see on these resistors. They’ll usually have three to four characters – numbers or letters – printed on top of the case.

If the three characters you’re seeing are all numbers, you’re probably looking at an E24 marked resistor. These markings actually share some similarity with the color-band system used on the PTH resistors. The first two numbers represent the first two most-significant digits of the value, the last number represents a magnitude.

Examples of E-24 marked SMD resistors

In the above example picture, resistors are marked 104, 105, 205, 751, and 754. The resistor marked with 104 should be 100kΩ (10x104), 105 would be 1MΩ (10x105), and 205 is 2MΩ (20x105). 751 is 750Ω (75x101), and 754 is 750kΩ (75x104).

Another common coding system is E96, and it’s the most cryptic of the bunch. E96 resistors will be marked with three characters – two numbers at the beginning and a letter at the end. The two numbers tell you the first three digits of the value, by corresponding to one of the not-so-obvious values on this lookup table.

Code Value Code Value Code Value Code Value Code Value Code Value
01 100 17 147 33 215 49 316 65 464 81 681
02 102 18 150 34 221 50 324 66 475 82 698
03 105 19 154 35 226 51 332 67 487 83 715
04 107 20 158 36 232 52 340 68 499 84 732
05 110 21 162 37 237 53 348 69 511 85 750
06 113 22 165 38 243 54 357 70 523 86 768
07 115 23 169 39 249 55 365 71 536 87 787
08 118 24 174 40 255 56 374 72 549 88 806
09 121 25 178 41 261 57 383 73 562 89 825
10 124 26 182 42 267 58 392 74 576 90 845
11 127 27 187 43 274 59 402 75 590 91 866
12 130 28 191 44 280 60 412 76 604 92 887
13 133 29 196 45 287 61 422 77 619 93 909
14 137 30 200 46 294 62 432 78 634 94 931
15 140 31 205 47 301 63 442 79 649 95 953
16 143 32 210 48 309 64 453 80 665 96 976

The letter at the end represents a multiplier, matching up to something on this table:

Letter Multiplier Letter Multiplier Letter Multiplier
Z 0.001 A 1 D 1000
Y or R 0.01 B or H 10 E 10000
X or S 0.1 C 100 F 100000

Resistors marked with E-96 codes

So a 01C resistor is our good friend, 10kΩ (100x100), 01B is 1kΩ (100x10), and 01D is 100kΩ. Those are easy, other codes may not be. 85A from the picture above is 750Ω (750x1) and 30C is actually 20kΩ.


Power Rating

The power rating of a resistor is one of the more hidden values. Nevertheless it can be important, and it’s a topic that’ll come up when selecting a resistor type.

Power is the rate at which energy is transformed into something else. It’s calculated by multiplying the voltage difference across two points by the current running between them, and is measured in units of a watt (W). Light bulbs, for example, power electricity into light. But a resistor can only turn electrical energy running through it into heat. Heat isn’t usually a nice playmate with electronics; too much heat leads to smoke, sparks, and fire!

Every resistor has a specific maximum power rating. In order to keep the resistor from heating up too much, it’s important to make sure the power across a resistor is kept under it’s maximum rating. The power rating of a resistor is measured in watts, and it’s usually somewhere between ⅛W (0.125W) and 1W. Resistors with power ratings of more than 1W are usually referred to as power resistors, and are used specifically for their power dissipating abilities.

Finding a resistor’s power rating

A resistor’s power rating can usually be deduced by observing its package size. Standard through-hole resistors usually come with ¼W or ½W ratings. More special purpose, power resistors might actually list their power rating on the resistor.

Some examples of power resistors

These power resistors can handle a lot more power before they blow. From top-right to bottom-left there are examples of 25W, 5W and 3W resistors, with values of 2Ω, 3Ω 0.1Ω and 22kΩ. Smaller power-resistors are often used to sense current.

The power ratings of surface mount resistors can usually be judged by their size as well. Both 0402 and 0603-size resistors are usually rated for 1/16W, and 0805’s can take 1/10W.

Measuring power across a resistor

Power is usually calculated by multiplying voltage and current (P = IV). But, by applying Ohm’s law, we can also use the resistance value in calculating power. If we know the current running through a resistor, we can calculate the power as:

P=I^2*R

Or, if we know the voltage across a resistor, the power can be calculated as:

P=V^2/R


Series and Parallel Resistors

Resistors are paired together all the time in electronics, usually in either a series or parallel circuit. When resistors are combined in series or parallel, they create a total resistance, which can be calculated using one of two equations. Knowing how resistor values combine comes in handy if you need to create a specific resistor value.

Series resistors

When connected in series resistor values simply add up.

Schematic of resistors in series

Equation for adding resistors in series

N resistors in series. The total resistance is the sum of all series resistors.

So, for example, if you just have to have a 12.33kΩ resistor, seek out some of the more common resistor values of 12kΩ and 330Ω, and butt them up together in series.

Parallel resistors

Finding the resistance of resistors in parallel isn’t quite so easy. The total resistance of N resistors in parallel is the inverse of the sum of all inverse resistances. This equation might make more sense than that last sentence:

Schematic of resistors in parallel

Equation for adding resistors in parallel

N resistors in parallel. To find the total resistance, invert each resistance value, add them up, and then invert that.

(The inverse of resistance is actually called conductance, so put more succinctly: the conductance of parallel resistors is the sum of each of their conductances).

As a special case of this equation: if you have just two resistors in parallel, their total resistance can be calculated with this slightly-less-inverted equation:

Equation for calculating two resistors in parallel

As an even more special case of that equation, if you have two parallel resistors of equal value the total resistance is half of their value. For example, if two 10kΩ resistors are in parallel, their total resistance is 5kΩ.

A shorthand way of saying two resistors are in parallel is by using the parallel operator: ||. For example, if R1 is in parallel with R2, the conceptual equation could be written as R1||R2. Much cleaner, and hides all those nasty fractions!

Resistor networks

As a special introduction to calculating total resistances, electronics teachers just love to subject their students to finding that of crazy, convoluted resistor networks.

A tame resistor network question might be something like: “what’s the resistance from terminals A to B in this circuit?”

An example of a resistor network

To solve such a problem, start at the back-end of the circuit and simplify towards the two terminals. In this case R7, R8and R9 are all in series and can be added together. Those three resistors are in parallel with R6, so those four resistors could be turned into one with a resistance of R6||(R7+R8+R9). Making our circuit:

Resistor network simplified

Now the four right-most resistors can be simplified even further. R4, R5 and our conglomeration of R6 - R9 are all in series and can be added. Then those series resistors are all in parallel with R3.

Resistor network further simplified

And that’s just three series resistors between the A and B terminals. Add ‘em on up! So the total resistance of that circuit is: R1+R2+R3||(R4+R5+R6||(R7+R8+R9)).


Example Applications

Resistors exist in just about every electronic circuit ever. Here are a few examples of circuits, which heavily depend on our resistor friends.

LED Current Limiting

Resistors are key in making sure LEDs don’t blow up when power is applied. By connecting a resistor in series with an LED, current flowing through the two components can be limited to a safe value.

Current limiting resistor schematic

When sizing out a current-limiting resistor, look for two characteristic values of the LED: the typical forward voltage, and the maximum forward current. The typical forward voltage is the voltage which is required to make an LED light up, and it varies (usually somewhere between 1.7V and 3.4V) depending upon the color of the LED. The maximum forward current is usually around 20mA for basic LEDs; continuous current through the LED should always be equal to or less than that current rating.

Once you’ve gotten ahold of those two values, you can size up a current-limiting resistor with this equation:

Current limiting resistor = (Vs-Vf)/If

VS is the source voltage – usually a battery or power supply voltage. VF and IF are the LED’s forward voltage and the desired current that runs through it.

For example, assume you have a 9V battery to power an LED. If your LED is red, it might have a forward voltage around 1.8V. If you want to limit the current to 10mA, use a series resistor of about 720Ω.

Current limiting example equation R=(9-1.8)/.010

Voltage Dividers

A voltage divider is a resistor circuit which turns a large voltage into a smaller one. Using just two resistors in series, an output voltage can be created that’s a fraction of the input voltage.

Here’s the voltage divider circuit:

Voltage divider circuit

Two resistors, R1 and R2, are connected in series and a voltage source (Vin) is connected across them. The voltage from Vout to GND can be calculated as:

Voltage divider equation

For example, if R1 was 1.7kΩ and R2 was 3.3kΩ, a 5V input voltage could be turned into 3.3V at the Vout terminal.

Voltage dividers are very handy for reading resistive sensors, like photocells, flex sensors, and force-sensitive resistors. One half of the voltage divider is the sensor, and the part is a static resistor. The output voltage between the two components is connected to an analog-to-digital converter on a microcontroller (MCU) to read the sensor’s value.

A photocell and resistor make a light sensor

Here a resistor R1 and a photocell create a voltage divider to create a variable voltage output.

Pull-up Resistors

A pull-up resistor is used when you need to bias a microcontroller’s input pin to a known state. One end of the resistor is connected to the MCU’s pin, and the other end is connected to a high voltage (usually 5V or 3.3V).

Without a pull-up resistor, inputs on the MCU could be left floating. There’s no guarantee that a floating pin is either high (5V) or low (0V).

Pull-up resistors are often used when interfacing with a button or switch input. The pull-up resistor can bias the input-pin when the switch is open. And it will protect the circuit from a short when the switch is closed.

A resistor pulling up a button input

In the circuit above, when the switch is open the MCU’s input pin is connected through the resistor to 5V. When the switch closes, the input pin is connected directly to GND.

The value of a pull-up resistor doesn’t usually need to be anything specific. But it should be high enough that not too much power is lost if 5V or so is applied across it. Usually values around 10kΩ work well.


Resources and Going Further

Now that you’re a budding expert on all things resistor, how ‘bout exploring some more fundamental electronics concepts! Resistors certainly aren’t the only basic component we use in electronics, there’s also:

Or maybe you’d like to further explore resistor applications?

Capacitors

Introduction

A capacitor is a two-terminal, electrical component. Along with resistors and inductors, they are one of the most fundamental passive components we use. You would have to look very hard to find a circuit which didn’t have a capacitor in it.

Capacitor variety hour

What makes capacitors special is their ability to store energy; they’re like a fully charged electric battery. Caps, as we usually refer to them, have all sorts of critical applications in circuits. Common applications include local energy storage, voltage spike suppression, and complex signal filtering.

Covered in this Tutorial

In this tutorial, we’ll be examining all sorts of capacitor-related topics, including:

  • How a capacitor is made
  • How a capacitor works
  • Units of capacitance
  • Types of capacitors
  • How to recognize capacitors
  • How capacitance combines in series and parallel
  • Common capacitor applications

Suggested Reading

Some of the concepts in this tutorial build on previous electronics knowledge. Before jumping into this tutorial, consider reading (at least skimming) these first:


Symbols and Units

Circuit Symbols

There are two common ways to draw a capacitor in a schematic. They always have two terminals, which go on to connect to the rest of the circuit. The capacitors symbol consists of two parallel lines, which are either flat or curved; both lines should be parallel to each other, close, but not touching (this is actually representative of how the capacitor is made. Hard to describe, easier to just show:

Capacitor circuit symbols

(1) and (2) are standard capacitor circuit symbols. (3) is an example of capacitors symbols in action in a voltage regulator circuit.

The symbol with the curved line (#2 in the photo above) indicates that the capacitor is polarized, meaning it’s probably an electrolytic capacitor. More on that in the types of capacitors section of this tutorial.

Each capacitor should be accompanied by a name – C1, C2, etc.. – and a value. The value should indicate the capacitance of the capacitor; how many farads it has. Speaking of farads…

Capacitance Units

Not all capacitors are created equal. Each capacitor is built to have a specific amount of capacitance. The capacitance of a capacitor tells you how much charge it can store, more capacitance means more capacity to store charge. The standard unit of capacitance is called the farad, which is abbreviated F.

It turns out that a farad is a lot of capacitance, even 0.001F (1 milifarad – 1mF) is a big capacitor. Usually you’ll see capacitors rated in the pico- (10-12) to microfarad (10-6) range.

 

Prefix Name Abbreviation Weight Equivalent Farads
Picofarad pF 10-12 0.000000000001 F
Nanofarad nF 10-9 0.000000001 F
Microfarad µF 10-6 0.000001 F
Milifarad mF 10-3 0.001 F
Kilofarad kF 103 1000 F

When you get into the farad to kilofarad range of capacitance, you start talking about special caps called super or ultra-capacitors.


Capacitor Theory

Note: The stuff on this page isn’t completely critical for electronics beginners to understand…and it gets a little complicated towards the end. We recommend reading the How a Capacitor is Made section, the others could probably be skipped if they give you a headache.

How a Capacitor Is Made

The schematic symbol for a capacitor actually closely resembles how it’s made. A capacitor is created out of two metal plates and an insulating material called a dielectric. The metal plates are placed very close to each other, in parallel, but the dielectric sits between them to make sure they don’t touch.

Internal capacitor view

Your standard capacitor sandwich: two metal plates separated by an insulating dielectric.

The dielectric can be made out of all sorts of insulating materials: paper, glass, rubber, ceramic, plastic, or anything that will impede the flow of current.

The plates are made of a conductive material: aluminum, tantalum, silver, or other metals. They’re each connected to a terminal wire, which is what eventually connects to the rest of the circuit.

The capacitance of a capacitor – how many farads it has – depends on how it’s constructed. More capacitance requires a larger capacitor. Plates with more overlapping surface area provide more capacitance, while more distance between the plates means less capacitance. The material of the dielectric even has an effect on how many farads a cap has. The total capacitance of a capacitor can be calculated with the equation:

C=er*A/(4*pi*d)

Where εr is the dielectric’s relative permittivity (a constant value determined by the dielectric material), A is the amount of area the plates overlap each other, and d is the distance between the plates.

How a Capacitor Works

Electric current is the flow of electric charge, which is what electrical components harness to light up, or spin, or do whatever they do. When current flows into a capacitor, the charges get “stuck” on the plates because they can’t get past the insulating dielectric. Electrons – negatively charged particles – are sucked into one of the plates, and it becomes overall negatively charged. The large mass of negative charges on one plate pushes away like charges on the other plate, making it positively charged.

Charged Cap Drawing

The positive and negative charges on each of these plates attract each other, because that’s what opposite charges do. But, with the dielectric sitting between them, as much as they want to come together, the charges will forever be stuck on the plate (until they have somewhere else to go). The stationary charges on these plates create an electric field, which influence electric potential energy and voltage. When charges group together on a capacitor like this, the cap is storing electric energy just as a battery might store chemical energy.

Charging and Discharging

When positive and negative charges coalesce on the capacitor plates, the capacitor becomes charged. A capacitor can retain its electric field – hold its charge – because the positive and negative charges on each of the plates attract each other but never reach each other.

At some point the capacitor plates will be so full of charges that they just can’t accept any more. There are enough negative charges on one plate that they can repel any others that try to join. This is where the capacitance (farads) of a capacitor comes into play, which tells you the maximum amount of charge the cap can store.

If a path in the circuit is created, which allows the charges to find another path to each other, they’ll leave the capacitor, and it will discharge.

For example, in the circuit below, a battery can be used to induce an electric potential across the capacitor. This will cause equal but opposite charges to build up on each of the plates, until they’re so full they repel any more current from flowing. An LED placed in series with the cap could provide a path for the current, and the energy stored in the capacitor could be used to briefly illuminate the LED.

capacitor charge/discharge example

Calculating Charge, Voltage, and Current

A capacitor’s capacitance – how many farads it has – tells you how much charge it can store. How much charge a capacitor is currently storing depends on the potential difference (voltage) between its plates. This relationship between charge, capacitance, and voltage can be modeled with this equation:

Q=CV

Charge (Q) stored in a capacitor is the product of its capacitance (C) and the voltage (V) applied to it.

The capacitance of a capacitor should always be a constant, known value. So we can adjust voltage to increase or decrease the cap’s charge. More voltage means more charge, less voltage…less charge.

That equation also gives us a good way to define the value of one farad. One farad (F) is the capacity to store one unit of energy (coulombs) per every one volt.

Calculating Current

We can take the charge/voltage/capacitance equation a step further to find out how capacitance and voltage affect current, because current is the rate of flow of charge. The gist of a capacitor’s relationship to voltage and current is this: the amount of current through a capacitor depends on both the capacitance and how quickly the voltage is rising or falling. If the voltage across a capacitor swiftly rises, a large positive current will be induced through the capacitor. A slower rise in voltage across a capacitor equates to a smaller current through it. If the voltage across a capacitor is steady and unchanging, no current will go through it.

(This is ugly, and gets into calculus. It’s not all that necessary until you get into time-domain analysis, filter-design, and other gnarly stuff, so skip ahead to the next page if you’re not comfortable with this equation.) The equation for calculating current through a capacitor is:

i=Cdv/dt

The dV/dt part of that equation is a derivative (a fancy way of saying instantaneous rate) of voltage over time, it’s equivalent to saying “how fast is voltage going up or down at this very moment”. The big takeaway from this equation is that if voltage is steady, the derivative is zero, which means current is also zero. This is why current cannot flow through a capacitor holding a steady, DC voltage.


Types of Capacitors

There are all sorts of capacitor types out there, each with certain features and drawbacks which make it better for some applications than others.

When deciding on capacitor types there are a handful of factors to consider:

  • Size - Size both in terms of physical volume and capacitance. It’s not uncommon for a capacitor to be the largest component in a circuit. They can also be very tiny. More capacitance typically requires a larger capacitor.
  • Maximum voltage - Each capacitor is rated for a maximum voltage that can be dropped across it. Some capacitors might be rated for 1.5V, others might be rated for 100V. Exceeding the maximum voltage will usually result in destroying the capacitor.
  • Leakage current - Capacitors aren’t perfect. Every cap is prone to leaking some tiny amount of current through the dielectric, from one terminal to the other. This tiny current loss (usually nanoamps or less) is called leakage. Leakage causes energy stored in the capacitor to slowly, but surely drain away.
  • Equivalent series resistance (ESR) - The terminals of a capacitor aren’t 100% conductive, they’ll always have a tiny amount of resistance (usually less than 0.01Ω) to them. This resistance becomes a problem when a lot of current runs through the cap, producing heat and power loss.
  • Tolerance - Capacitors also can’t be made to have an exact, precise capacitance. Each cap will be rated for their nominal capacitance, but, depending on the type, the exact value might vary anywhere from ±1% to ±20% of the desired value.

Ceramic Capacitors

The most commonly used and produced capacitor out there is the ceramic capacitor. The name comes from the material from which their dielectric is made.

Ceramic capacitors are usually both physically and capacitance-wise small. It’s hard to find a ceramic capacitor much larger than 10µF. A surface-mount ceramic cap is commonly found in a tiny 0402 (0.4mm x 0.2mm), 0603 (0.6mm x 0.3mm) or 0805 package. Through-hole ceramic caps usually look like small (commonly yellow or red) bulbs, with two protruding terminals.

Ceramic Capacitors

Two caps in a through-hole, radial package; a 22pF cap on the left, and a 0.1µF on the right. In the middle, a tiny 0.1µF 0603 surface-mount cap.

Compared to the equally popular electrolytic caps, ceramics are a more near-ideal capacitor (much lower ESR and leakage currents), but their small capacitance can be limiting. They are usually the least expensive option too. These caps are well-suited for high-frequency coupling and decoupling applications.

Aluminum and Tantalum Electrolytic

Electrolytics are great because they can pack a lot of capacitance into a relatively small volume. If you need a capacitor in the range of 1µF-1mF, you’re most likely to find it in an electrolytic form. They’re especially well suited to high-voltage applications because of their relatively high maximum voltage ratings.

Aluminum electrolytic capacitors, the most popular of the electrolytic family, usually look like little tin cans, with both leads extending from the bottom.

Electrolytic caps

An assortment of through-hole and surface-mount electrolytic capacitors. Notice each has some method for marking the cathode (negative lead).

Unfortunately, electrolytic caps are usually polarized. They have a positive pin – the anode – and a negative pin called the cathode. When voltage is applied to an electrolytic cap, the anode must be at a higher voltage than the cathode. The cathode of an electrolytic capacitor is usually identified with a ‘-’ marking, and a colored strip on the case. The leg of the anode might also be slightly longer as another indication. If voltage is applied in reverse on an electrolytic cap, they’ll fail spectacularly (making a pop and bursting open), and permanently. After popping an electrolytic will behave like a short circuit.

These caps also notorious for leakage – allowing small amounts of current (on the order of nA) to run through the dielectric from one terminal to the other. This makes electrolytic caps less-than-ideal for energy storage, which is unfortunate given their high capacity and voltage rating.

Supercapacitors

If you’re looking for a capacitor made to store energy, look no further than supercapacitors. These caps are uniquely designed to have very high capacitances, in the range of farads.

Supercapacitor

A 1F (!) supercapacitor. High capacitance, but only rated for 2.5V. Notice these are also polarized.

While they can store a huge amount of charge, supercaps can’t deal with very high voltages. This 10F supercap is only rated for 2.5V max. Any more than that will destroy it. Super caps are commonly placed in series to achieve a higher voltage rating (while reducing total capacitance).

The main application for supercapacitors is in storing and releasing energy, like batteries, which are their main competition. While supercaps can’t hold as much energy as an equally sized battery, they can release it much faster, and they usually have a much longer lifespan.

Others

Electrolytic and ceramic caps cover about 80% of the capacitor types out there (and supercaps only about 2%, but they’re super!). Another common capacitor type is the film capacitor, which features very low parasitic losses (ESR), making them great for dealing with very high currents.

There’s plenty of other less common capacitors. Variable capacitors can produce a range of capacitances, which makes them a good alternative to variable resistors in tuning circuits. Twisted wires or PCBs can create capacitance (sometimes undesired) because each consists of two conductors separated by an insulator. Leyden Jars – a glass jar filled with and surrounded by conductors – are the O.G. of the capacitor family. Finally, of course, flux capacitors (a strange combination of inductor and capacitor) are critical if you ever plan on traveling back to the glory days.


Capacitors in Series/Parallel

Much like resistors, multiple capacitors can be combined in series or parallel to create a combined equivalent capacitance. Capacitors, however, add together in a way that’s completely the opposite of resistors.

Capacitors in Parallel

When capacitors are placed in parallel with one another the total capacitance is simply the sum of all capacitances. This is analogous to the way resistors add when in series.

Capacitors in parallel add

So, for example, if you had three capacitors of values 10µF, 1µF, and 0.1µF in parallel, the total capacitance would be 11.1µF (10+1+0.1).

Capacitors in Series

Much like resistors are a pain to add in parallel, capacitors get funky when placed in series. The total capacitance of N capacitors in series is the inverse of the sum of all inverse capacitances.

Capacitors in series are the inverse of the sum of their inverses

If you only have two capacitors in series, you can use the “product-over-sum” method to calculate the total capacitance:

Equation for 2 capacitors in series Ctot=C1*C2/(C1+C2)

Taking that equation even further, if you have two equal-valued capacitors in series, the total capacitance is half of their value. For example two 10F supercapacitors in series will produce a total capacitance of 5F (it’ll also have the benefit of doubling the voltage rating of the total capacitor, from 2.5V to 5V).


Application Examples

There are tons of applications for this nifty little (actually they’re usually pretty large) passive component. To give you an idea of their wide range of uses, here are a few examples:

Decoupling (Bypass) Capacitors

A lot of the capacitors you see in circuits, especially those featuring an integrated circuit, are decoupling. A decoupling capacitor’s job is to supress high-frequency noise in power supply signals. They take tiny voltage ripples, which could otherwise be harmful to delicate ICs, out of the voltage supply.

In a way, decoupling capacitors act as a very small, local power supply for ICs (almost like an uninterupptable power supply is to computers). If the power supply very temporarily drops its voltage (which is actually pretty common, especially when the circuit it’s powering is constantly switching its load requirements), a decoupling capacitor can briefly supply power at the correct voltage. This is why these capacitors are also called bypass caps; they can temporarily act as a power source, bypassing the power supply.

Decoupling capacitors connect between the power source (5V, 3.3V, etc.) and ground. It’s not uncommon to use two or more different-valued, even different types of capacitors to bypass the power supply, because some capacitor values will be better than others at filtering out certain frequencies of noise.

Decoupling capacitor schematic

In this schematic, three decoupling capacitors are used to help reduce the noise in an accelerometer’s voltage supply. Two ceramic 0.1µF and one tantalum electrolytic 10µF split decoupling duties.

While it seems like this might create a short from power to ground, only high-frequency signals can run through the capacitor to ground. The DC signal will go to the IC, just as desired. Another reason these are called bypass capacitors is because the high frequencies (in the kHz-MHz range) bypass the IC, instead running through the capacitor to get to ground.

When physically placing decoupling capacitors, they should always be located as close as possible to an IC. The further away they are, they less effective they’ll be.

ADXL345 breakout decoupling caps

Here’s the physical circuit layout from the schematic above. The tiny, black IC is surrounded by two 0.1µF capacitors (the brown caps) and one 10µF electrolytic tantalum capacitor (the tall, black/grey rectangular cap).

To follow good engineering practice, always add at least one decoupling capacitor to every IC. Usually 0.1µF is a good choice, or even add some 1µF or 10µF caps. They’re a cheap addition, and they help make sure the chip isn’t subjected to big dips or spikes in voltage.

Power Supply Filtering

Diode rectifiers can be used to turn the AC voltage coming out of your wall into the DC voltage required by most electronics. But diodes alone can’t turn an AC signal into a clean DC signal, they need the help of capacitors! By adding a parallel capacitor to a bridge rectifier, a rectified signal like this:

Rectification pre-Cap

Can be turned into a near-level DC signal like this:

Rectification post-cap

Capacitors are stubborn components, they’ll always try to resist sudden changes in voltage. The filter capacitor will charge up as the rectified voltage increases. When the rectified voltage coming into the cap starts its rapid decline, the capacitor will access its bank of stored energy, and it’ll discharge very slowly, supplying energy to the load. The capacitor shouldn’t fully discharge before the input rectified signal starts to increase again, recharging the cap. This dance plays out many times a second, over-and-over as long as the power supply is in use.

Power supply circuit

An AC-to-DC power supply circuit. The filter cap (C1) is critical in smoothing out the DC signal sent to the load circuit.

If you tear apart any AC-to-DC power supply, you’re bound to find at least one rather large capacitor. Below are the guts of a 9V DC wall adapter. Notice any capacitors in there?

alt text

There might be more capacitors than you think! There are four electrolytic, tin-can-looking caps ranging from 47µF to 1000µF. The big, yellow rectangle in the foreground is a high-voltage 0.1µF polypropylene film cap. The blue disc-shaped cap and the little green one in the middle are both ceramics.

Energy Storage and Supply

It seems obvious that if a capacitor stores energy, one of it’s many applications would be supplying that energy to a circuit, just like a battery. The problem is capacitors have a much lower energy density than batteries; they just can’t pack as much energy as an equally sized chemical battery (but that gap is narrowing!).

The upside of capacitors is they usually lead longer lives than batteries, which makes them a better choice environmentally. They’re also capable of delivering energy much faster than a battery, which makes them good for applications which need a short, but high burst of power. A camera flash might get its power from a capacitor (which, in turn, was probably charged by a battery).

Battery or Capacitor?

Battery Capacitor
Capacity
Energy Density
Charge/Discharge Rate
Life Span

 

Signal Filtering

Capacitors have a unique response to signals of varying frequencies. They can block out low-frequency or DC signal-components while allowing higher frequencies to pass right through. They’re like a bouncer at a very exclusive club for high frequencies only.

Filtering signals can be useful in all sorts of signal processing applications. Radio receivers might use a capacitor (among other components) to tune out undesired frequencies.

Another example of capacitor signal filtering is passive crossover circuits inside speakers, which separate a single audio signal into many. A series capacitor will block out low frequencies, so the remaining high-frequency parts of the signal can go to the speaker’s tweeter. In the low-frequency passing, subwoofer circuit, high-frequencies can mostly be shunted to ground through the parallel capacitor.

Crossover schematic

A very simple example of an audio crossover circuit. The capacitor will block out low frequencies, while the inductor blocks out high frequencies. Each can be used to deliver the proper signal to tuned audio drivers.

De-rating

When working with capacitors, it’s important to design your circuits with capacitors that have a much higher tolerance than the potentially highest voltage spike in your system.

Here’s an excellent video from SparkFun Engineer Shawn about what happens to different types of capacitors when you fail to de-rate your capacitors and exceed their maximum voltage specs. You can read more about his experiments here.


Purchasing Capacitors

Store up on these little energy storage components or put them to work a beginning power supply kit.

Our recommendations:


Resources and Going Further

Whew. Feel like a capacitor expert?! Want to keep learning more about the fundamentals of electronics? If you haven’t already, consider reading about some of the other common electronics components:

Or maybe some of these tutorials will catch your attention?

How to Use a Breadboard

Introduction

Breadboards are one of the most fundamental pieces when learning how to build circuits. In this tutorial, you will learn a little bit about what breadboards are, why they are called breadboards, and how to use one. Once you are done you should have a basic understanding of how breadboards work and be able to build a basic circuit on a breadboard.

A Breadboard

Suggested Reading

Here are some tutorials and concepts you may want to explore before learning about breadboards:


History

If you wanted to build a circuit prior to the 1960s, chances are you would have used a technique called wire-wrap. Wire wrap is a process that involves wrapping wires around conductive posts attached to a perfboard (a.k.a. a protoboard). As you can see, the process can get rather complex very quickly.Although this method is still used today, there is something that makes prototyping much easier, breadboards!

wire-wrap circuit

A wire-wrap circuit (image courtesy of Wikipedia user Wikinaut)

What’s in a Name?

When you picture a breadboard in your head, you may envision a big piece of wood and a large loaf of freshly baked bread. You wouldn’t be too far off either.

A literal breadboard

Bread on a breadboard

So why do we call this electronic “circuit builder” a breadboard? Many years ago, when electronics were big and bulky, people would grab their mom’s breadboard, a few nails or thumbtacks, and start connecting wires onto the board to give themselves a platform on which to build their circuits.

Circuit built on literal breadboard

Circuit on an “original” breadboard (image courtesy of mischka and their awesome literal breadboard tutorial)

Since then, electronic components have gotten a lot smaller, and we’ve come up with better ways to connect circuits, making moms all over the world happy to have their breadboards back. However, we are stuck with the confusing name. Technically, these are still breadboards, but this discussion is going to be on modern, “solderless” breadboards.


Why Use Breadboards?

An electronics breadboard (as opposed to the type on which sandwiches are made) is actually referring to a solderless breadboard. These are great units for making temporary circuits and prototyping, and they require absolutely no soldering.

Prototyping is the process of testing out an idea by creating a preliminary model from which other forms are developed or copied, and it is one of the most common uses for breadboards. If you aren’t sure how a circuit will react under a given set of parameters, it’s best to build a prototype and test it out.

For those new to electronics and circuits, breadboards are often the best place to start. That is the real beauty of breadboards–they can house both the simplest circuit as well as very complex circuits. As you’ll see later in this tutorial, if your circuit outgrows its current breadboard, others can be be attached to accommodate circuits of all sizes and complexities.

Another common use of breadboards is testing out new parts, such as Integrated circuits (ICs). When you are trying to figure out how a part works and constantly rewiring things, you don’t want to have to solder your connections each time.

As mentioned, you don’t always want the circuit you build to be permanent. When trying to duplicate a customer’s problem, SparkFun’s Technical Support team will often use breadboards to build, test, and analyze the circuit. They can connect the parts the customer has, and once they’ve gotten the circuit setup and figured out the problem, they can take everything apart and put it aside for the next time they need to do some troubleshooting.

A circuit built on a solderless breadboard

A circuit built on a solderless breadboard


Anatomy of a Breadboard

The major features of a Breadboard

The major features of a Breadboard

The best way to explain how a breadboard works is to take it apart and see what’s inside. Using a smaller breadboard it’s easier to see just how they function.

Terminal Strips

Here we have a breadboard where the adhesive backing has been removed. You can see lots of horizontal rows of metal strips on the bottom of the breadboard.

SparkFun Mini Breadboard

A SparkFun Mini Breadboard from the top (left) and the same breadboard flipped over with the adhesive back removed (right).

The tops of the metal rows have little clips that hide under the plastic holes. These clips allow you to stick a wire or the leg of a component into the exposed holes on a breadboard, which then hold it in place.

Clip

A single strip of conductive metal removed from the above breadboard.

Once inserted that component will be electrically connected to anything else placed in that row. This is because the metal rows are conductive and allow current to flow from any point in that strip.

Notice that there are only five clips on this strip. This is typical on almost all breadboards. Thus, you can only have up to five components connected in one particular section of the breadboard. The row has ten holes, so why can you only connect five components? You’ll also notice that each horizontal row is separated by a ravine, or crevasse, in the middle of the breadboard. This ravine isolates both sides of a given row from one another, and they are not electrically connected. We’ll discuss the purpose of this in just a bit, but, for now, just know that each side of a given row is disconnected from the other, leaving you with five spots for components on either side.

LED in Breadboard

An LED inserted into a breadboard. Notice how each leg of the LED is placed on either side of the ravine. This prevents the connections to the LED from being shorted.

Power Rails

Now that we’ve seen how the connections in a breadboard are made, let’s look at a larger, more typical breadboard. Aside from horizontal rows, breadboards usually have what are called power rails that run vertically along the sides.

Front and back, medium breadboard with power rails exposed

A medium-size breadboard with the adhesive back removed to expose the power rails.

These power rails are metal strips that are identical to the ones that run horizontally, except they are, typically*, all connected. When building a circuit, you tend to need power in lots of different places. The power rails give you lots of easy access to power wherever you need it in your circuit. Usually they will be labeled with a ‘+’ and a ‘-’ and have a red and blue or black stripe, to indicate the positive and negative side.

It is important to be aware that the power rails on either side are not connected, so if you want the same power source on both sides, you will need to connect the two sides with some jumper wires. Keep in mind that the markings are there just as a reference. There is no rule that says you have to plug power into the ‘+’ rail and ground into the ‘-'rail, though it’s good practice to keep everything in order.

Jumper wires connecting both sides of the power rails

Two jumper wires used to connect the power rails on both sides. Always attach the ‘+’ to ‘+’ and the ‘-’ to ‘-’.

DIP Support

Earlier we mentioned the ravine that isolates the two sides of a breadboard. This ravine serves a very important purpose. Many integrated circuits, often referred to as ICs or, simply, chips, are manufactured specifically to fit onto breadboards. In order to minimize the amount of space they take up on the breadboard, they come in what is known as a Dual in-line Package, or DIP.

These DIP chips (salsa anyone?) have legs that come out of both sides and fit perfectly over that ravine. Since each leg on the IC is unique, we don’t want both sides to be connected to each other. That is where the separation in the middle of the board comes in handy. Thus, we can connect components to each side of the IC without interfering with the functionality of the leg on the opposite side.

alt text

Two DIP ICs, the LM358 (top), a very common op-amp, and the ever-popular ATmega328 microcontroller (bottom).

Rows and Columns

You may have noticed that many breadboards have numbers and letters marked on various rows and columns. These don’t serve any purpose other than to help guide you when building your circuit. Circuits can get complicated quickly, and all it takes is one misplaced leg of a component to make the entire circuit malfunction or not work at all. If you know the row number of the connection you are trying to make, it makes it much simpler to plug a wire into that number rather than eyeballing it.

These are also helpful when using instruction booklets, such as the one found in the SparkFun Inventor’s Kit. Many books and guides have circuit diagrams for you to follow along while building your circuit. Just remember that the circuit you’re building doesn’t have to be in the exact same location on the breadboard as the one in the book. In fact, it doesn’t even have to look similar. As long as all the electrical connections are being made, you can build your circuit any way you’d like!

Binding Posts

Some breadboards come on a platform that has binding posts attached to it. These posts allow you to connect all kinds of different power sources to your breadboard. We’ll cover these more in the next section.

Other Features

When building your circuit, you are not confined to stay on just one breadboard. Some circuits will require a lot more space. Many breadboards have little nubbins and slots on the sides, and some even have them on the tops and bottoms. These allow you to connect multiple breadboards together to form the ultimate prototyping surface.

Four SparkFun mini breadboards connected togethe

Four SparkFun mini breadboards connected together.

Some breadboards also have an adhesive backing that allow you to stick them to many different surfaces. These can come in handy if you want to attach your breadboard to the inside on an enclosure or other project case.

*Some larger breadboards will often isolate one half of the breadboard’s power rails form the other half (think top and bottom half, not the sides). This is convenient if you have two different voltages with which you need to power your circuit, such as 3.3V and 5V. However, if you’re unaware whether the power rials are or aren’t isolated, it can often lead to issues while building your circuit. It’s always a good idea to use a multimeter to check for the absence or presence of continuity in your breadboard’s power rails.

Providing Power to a Breadboard

When it comes to providing power to you breadboard, there are numerous options.

Borrowing from Other Power Sources

If you are working with a development board such as an Arduino, then you can simply pull power from the Arduino’s female headers. The Arduino has multiple power and ground pins that you can connect to the power rails or other rows on a breadboard.

Sharing power with an Arduino

Connecting the Ground (GND) pin from an Arduino to a row on a mini breadboard. Now any leg or wire connected to that row will also be connected to Ground.

The Arduino usually gets its power from the USB port on a computer or an external power supply such as a battery pack or a wall wart.

Binding Posts

As mentioned in the previous section, some breadboards have binding posts that allow you to connect external power sources.

The first step to using the binding posts is to connect them to the breadboard using some jumper wires. Although it would seem that the posts are connected to the breadboard, they are not. If they were, you would be limited to where you could and couldn’t provide power. As we’ve seen, breadboards are meant to be totally customizable, so it would make sense that the binding posts are no different.

With that, we have to connect wires to the posts in order to connect them to the breadboard. To do that, unscrew the post until the hole going through it is exposed. Slide the stripped end of your jumper wire through the hole, and screw the post back down until the wire is firmly connected.

Conneting wire to the binding posts

Typically, you only need to connect a power and ground wire from the posts to the breadboard. If you need an alternate power source, you can use the third post.

Now your posts are connected to the the breadboard, but there is still no power. You can use many different methods to connect power to the posts, and, thus, to the breadboard.

Benchtop Power Supplies

Many electronics labs have benchtop power supplies that allow you to provide a wide range of voltage and current to your circuit. Using a banana connector you can provide power from the supply to the binding posts.

A breadboard being powered through the binding posts from banana cables

A breadboard being powered through the binding posts from banana cables.

Alternatively, you could use alligator clips, IC hooks, or any other cables with a banana connection to hook your breadboard up to a number of different supplies.

Another method of using the binding posts is to solder a barrel jack to some wires, and then connect them to the binding posts. This is a more advanced technique, and it requires some intermediate soldering skills.

A breadboard being powered through the binding posts with a barrel jack

The barrel jack is soldered to two wires that share the same holes on the binding posts as the wires going to the breadboard. If your breadboard doesn’t have binding posts, you could just plug the wires from the barrel jack directly into the power rails.

Breadboard Power Supplies

Yet another method for powering your breadboard is to use one of the many breadboard power supplies available. SparkFun carries a number of kits and boards that you can use to plug power directly into your breadboard. Some allow you to plug a wall wart directly into the breadboard. Others allow you to pull power directly from your computer via the USB connections. And, almost all of them have the capability to adjust the voltage, giving you a full range of the common voltages needed when building circuits.

A SparkFun USB Breadboard Power Supply

A SparkFun USB Breadboard Power Supply that pulls power from your computer’s USB and has the option to choose between 3.3V and 5V.


Building Your First Breadboard Circuit

Now that we’re familiar with the internals of a breadboard and how to provide power to them, what do we do with them? We are going to start with a simple circuit.

What You’ll Need

Here is a parts list to follow along with this circuit. If you have other electronic bits and pieces, feel free to use them and change the circuit up. Remember, there is often more ways than one to build any given circuit. Some even have dozens of different ways that you can build them.

This wish list assumes you don’t have any parts/tools and is generous with quantities etc. For example, you only need one LED for this project, but the pack listed has 20 LEDs in it. The same is true with the hook-up wire. You don’t need that much (or all those colors), but if you keep playing with circuits, it could come in handy. If you don’t want the higher quantities check the bottom of the product pages in the section called “Related Products” and you should be able to find smaller quantities. Also, the breadboard power supply doesn’t have headers, if you know how to solder and have the tools, solder the headers on yourself. If not, solderless headers have been included in the wishlist as well.

Build the Circuit

Here is a small circuit on a breadboard.

Picture of Circuit

A simple circuit, involving a button, an LED, and a resistor, built two different ways.

The red board you see a Breadboard Power Supply, which supplies 5V to the power rails when it is connected to a 9V wall wart.

The circuit goes as follows:

  • There is a wire connecting the 5V power rail to the positive, anode leg of an LED.
  • The negative, cathode leg of the LED is connected to a 330Ω resistor.
  • The resistor is then connected to a button.
  • When the button is pushed, it connects the circuit to ground completing the circuit and turning on the LED.

Circuit Schematics

We cover how to read a schematic in another tutorial. However, it is a very important part of building circuits, so it will be covered here in short.

Schematics are universal pictograms that allow people all over the world to understand and build electronics. Every electronic component has a very unique schematic symbol. These symbols are then assembled into circuits using a variety of programs. You could also draw them out by hand. If you want to dive deeper in the world of electronics and circuit building, learning to read schematics is a very important step in doing so.

Here we have a schematic for the above circuit. Power (5V) is represented by the arrow at the top. It then goes to the LED (the triangle and line with arrows emitting out of it). The LED is then connected to the resistor (the squiggly line). That is connected to the button (the latch-looking symbol). Last the button is connect to ground (the horizontal line at the bottom).

Schematic

This may seem like a funny way to draw a circuit, but it is a fundamental process that has been around for decades. Schematics allow people from different nationalities and languages to build and collaborate on circuits designed by anyone. As mentioned, you can build a circuit in many different ways, but, as this schematic shows, there are certain connections that must be made. Diverging from this schematic will give you an entirely different circuit.

Practice Makes Perfect

The last bit of knowledge to leave you with is that there are tons of resources and programs you can use to build circuits without having to actually use your breadboard. One very common program used by SparkFun is Fritzing. Fritzing is a free program that allows you to build your own circuits on a virtual breadboard. It also provides schematic views for all the circuits you build. Here we can see the same circuits as above built using Fritzing.

Fritzing Diagram

Notice that the green lines indicate to which rows and columns each component is connected.

There are many other programs like Fritzing. Some are free, and some are paid. Some will even allow you to build a circuit and test its functionality through simulations. Go explore the internet, and find the tools that work best for you.


Purchasing a Breadboard

A great way to start using breadboards is to purchase one as part of a kit. The Sparkfun Inventor’s Kit includes everything you need to complete 16 different circuits. We’ve also listed a few basic stand-alone breadboards in different sizes for your projects.

Our recommendations:


Resources and Going Further

Hopefully you now have a better understanding of what a breadboard is and how it works. Now the real fun begins. We’ve barely scratched the surface of building circuits on breadboards. Here are some other tutorials you can check out to learn more about components and how to integrate them into your breadboard circuits.

Educators may be interested in these links.

Or, if you have mastered your circuit building skills and want to move to the next level, check out these tutorials.

Lessons in Algorithms

Introduction

Earlier this year, Nathan Seidle, founder of SparkFun, created the Crowdsourcing Algorithms Challenge (aka, the Speed Bag Challenge). After numerous fantastic entries, one was chosen. The winner, Barry Hannigan, was asked to write up his process involved in solving this problem. This article is Barry Hannigan’s winning approach to solving real-world problems, even when the problem is not tangibly in front of you.

Firmware Resources

You can view Barry’s code by clicking the link below.

 

BARRY'S SPEED BAG CHALLENGE GITHUB REPO


As the winner of Nate’s Speed Bag Challenge, I had the wonderful opportunity to meet with Nate at SparkFun’s headquarters in Boulder, CO. During our discussions, we thought it would be a good idea to create a tutorial describing how to go about solving a complex problem in an extremely short amount of time. While I’ll discuss specifics to this project, my hope is that you’ll be able to apply the thought process to your future projects—big or small.

Where to Start

In full-fledged software projects, from an Engineer’s perspective, you have four major phases:

  • Requirements
  • Design
  • Implementation
  • Test

Let’s face it; the design and coding is what everyone sees as interesting, where their creative juices can flow and the majority of the fun can be had. Naturally, there is the tendency to fixate on a certain aspect of the problem being solved and jump right in designing and coding. However, I will argue that the first and last phase can be the most important in any successful project, be it large or small. If you doubt that, consider this: my solution to the speed bag problem was designed wickedly fast, and I didn’t have a bag to test it on. But, with the right fixes applied in the end, the functionality was tested to verify that it produced the correct results. Conversely, a beautiful design and elegant implementation that doesn’t produce the required functionality will surely be considered a failure.

I didn’t mention prototype as a phase, because depending on the project it can happen in different phases or multiple phases. For instance, if the problem isn’t fully understood, a prototype can help figure out the requirements, or it can provide a proof of concept, or it can verify the use of a new technology. While important, prototyping is really an activity in one or more phases.

Getting back to the Speed Bag Challenge, in this particular case, even though it is a very small project, I suggest that you spend a little time in each of the four areas, or you will have a high probability of missing something important. To get a full understanding of what’s required, let’s survey everything we had available as inputs. The web post for the challenge listed five explicit requirements, which you can find here. Next, there was a link to Nate’s Github repository that had information on the recorded data format and a very brief explanation of how the speed bag device would work.

In this case, I would categorize what Nate did with the first speed bag counter implementation as a prototype to help reveal additional requirements. From Nate’s write-up on how he built the system, we know it used an accelerometer attached to the base of a speed bag and that the vibration data samples about every 2ms are to be used to count punches. We also now know that applying a polynomial smoothing function and looking for peaks above a threshold doesn’t accurately detect punches.

While trying not to be too formal for a small project, I kept these objectives (requirements) in mind while working the problem:

  • The algorithm shall be able to produce the correct number of hits from the recorded data sets
  • The solution shall be able to run on 8-bit and 32-bit micros
  • Produce documentation and help others learn from the solution put forth
  • Put code and documents in a public repository or website
  • Disclose the punch count and the solution produced for the Mystery data sets
  • Accelerometer attached to top of speed bag base, orientation unknown except +Z is up -Z is down
  • Complex data patterns will need more than polynomial filtering; you need to adjust to incoming data amplitude variations—as Nate suspects, resonance is the likely culprit
  • You have 15 days to complete (Yikes!)

Creating the Solution

As it goes in all projects, now that you know what should be done, the realization that there isn’t enough time sets in. Since I didn’t have the real hardware and needed to be able to visually see the output of my algorithm, I started working it out quickly in Java on my PC. I built in a way to plot the results of the waveforms on my screen. I’ve been using NetBeans for years to do Java development, so I started a new speed bag project. I always use JFreeChart library to plot data, so I added it to my project. Netbeans has a really good IDE and built-in GUI designer. All I had to do was create a GUI layout with a blank panel where I want the JFreeChart to display and then, at run time, create the JFreeChart object and add it to the panel. All the oscilloscope diagrams in this article were created by the JFreeChart display. Here is an image from my quick and dirty oscilloscope GUI design page.

NetBeans IDE

This algorithm was needed in a hurry, so my first pass is to be very object oriented and use every shortcut afforded me by using Java. Then, I’ll make it more C like in nature as I nail down the algorithm sequence. I jumped right in and plotted the X, Y and Z wave forms as they came from the recorded results. Once I got a look at the raw data, I decided to remove any biases first (i.e., gravity) and then sum the square of each waveform and take the square root. I added some smoothing by way of averaging a small number of values and employed a minimum time between threshold crossings to help filter out spikes. All in all, this seemed to make the data even worse on the plot. I decided to throw away X and Y, since I didn’t know in what orientation it was mounted and if it would be mounted the same on different speed bag platforms anyway. To my horror, even with just the Z axis, it still just looked like a mess of noise! I’m seeing peaks in the data way too close together. Only my minimum time between thresholds gate is helping make some sense of the punch count, but there really isn’t anything concrete in the data. Something’s not adding up. What am I missing?

Below is an image of the runF1 waveform. The blue signal is the filtered z axis, and the red line is a threshold for counting punches. As I mentioned, if it weren’t for my 250ms minimum between punch detections, my counter would be going crazy. Notice the way I have introduced two 5 millisecond delays in my runF1() processing so thresholding would be a little better if the red line were moved to the right by 10 milliseconds. I’ll talk more about aligning signals later in this article, but you can see in this image how time aligning signals is crucial for getting accurate results.

First filter with many peaks

The blue signal is the filtered z axis, and the red line is a threshold for counting punches.

If you look at the virtual oscilloscope output, you can see that between millisecond 25,000 and 26,000, which is 1 second in time, there are around nine distinct acceleration events. No way Nate is throwing nine punches in a second. Exactly how many punches should I expect to see per second? Back to the drawing board. I need another approach. Remember humility is your friend; if you just rush in on your high horse you usually will be knocked off it in a hurry.

Understand the Domain

Typically the requirements are drafted in the context of the domain of the problem that’s being solved, or some design aspects are developed from a requirement with domain knowledge applied. I don’t know the first thing about boxing speed bags, so time to do some Googling.

The real nugget I unearthed was that a boxer hits a speed bag, and it makes three contacts with the base: once forward (in punch direction), then it comes all the way back (opposite of punch direction) and strikes the base, and then it goes all the way forward again striking the base (in punch direction). Then the boxer punches it on its way back toward the boxer. This actually gives four opportunities to generate movement to the base, once from the shock of the boxer contacting the bag, and then three impacts with the base.

Now, what I see on the waveforms makes more sense. There isn’t a shock of the bag hitting the base once per punch. My second thought was how many punches can a boxer throw at a speed bag per second. Try as I might, I could not find a straight answer to this question. I found lots of websites with maximum shadow boxing punches and actual punches being thrown maximums but not a maximum for a speed bag. Time to derive my own conclusion: I thought about how far the speed bag must travel per punch and concluded that there must be a minimum amount of force to make the bag travel the distance it needs to impact the base three times. Since I’m not a boxer, all I could do is visualize hitting the bag as slowly as possible and it making three contacts. I concluded from the video in my mind’s eye that it would be difficult to hit a bag less than twice per second. OK, that’s a minimum; how about a maximum? Again, I summoned my mind’s eye video and this time moved my fist to strike the imaginary bag. I concluded with the distance the bag needed to travel and the amount of time to move a fist in and out of the path of the bag that about four per second is all that is possible, even with a skilled boxer. OK, it’s settled. I need to find events in the data that are happening between 2 and 4 hertz. Time to get back to coding and developing!

Build a little, Test a little, Learn a lot

While everyone’s brain works a little differently, I suggest that you try an iterative strategy, especially when you are solving a problem that does not have a clearly defined methodology going into it. I also suggest that when you feel you are ready to make a major tweak to an algorithm, you make a copy of the algorithm before starting to modify the copy, or start with an empty function and start pulling in pieces of the previous iteration. You can use source control to preserve your previous iteration, but I like having the previous iteration(s) in the code so I can easily reference it when working on the next iteration. I usually don’t like to write more than 10 or 20 lines of code without at minimum verifying it complies, but I really want to run it and print something out as confirmation that my logic and assumptions are correct. I’ve done this my entire career and will usually complain if I don’t have target hardware available to actually run what I’m coding. Around 2006, I heard a saying from a former Rear Admiral:

 

Build a little, Test a little, Learn a lot.

-Wayne Meyers, Rear Admiral, U.S. Navy

I really identify with that statement, as it succinctly states why I always want to keep running and testing what I’m writing. It either allows you to confirm your assumptions or reveals you are heading down the wrong path, allowing you to quickly get on the right path without throwing away a lot of work. This was yet another reason that I chose Java as my prototype platform, as I could quickly start running and testing code plus graph it out visually, in spite of not having the actual speed bag hardware.

Additionally, you will see in the middle of all six runFx() functions there is code that keeps track of the current time in milliseconds and verifies that the time stamp delta in milliseconds has elapsed or it sleeps for 1 millisecond. This allowed me to watch the data scroll by in my Java plotting window and see how the filtering output looks. I passed in X, Y and Z acceleration data along with an X, Y and Z average value. Since I only used Z data in most algorithms, I started cheating and sending in other values to be plotted, so it’s a little confusing when looking at the graphs of one through five since they don’t match the legend. However, plotting in real time allowed me to see the data and watch the hit counter increment. I could actually see and feel a sense of the rhythm into which the punches were settling and how the acceleration data was being affected by the resonance at prolonged constant rhythm. In addition to the visual output using the Java System.out.println() function, I can output data to a window in the NetBeans IDE.

If you look in the Java subdirectory in my GitHub repository, there is a file named MainLoop.java. In that file, I have a few functions named run1() through run6(). These were my six major iterations of the speed bag algorithm code.

Here are some highlights for each of the six iterations.

runF1

runF1() used only the Z axis, and employed weak bias removal using a sliding window and fixed amplification of the filtered Z data. I created an element called delay, which is a way to delay input data so it could be aligned later with output of averaged results. This allowed the sliding window average to be subtracted from Z axis data based on surrounding values, not by previous values. Punch detection used straight comparison of amplified filter data being greater than average of five samples with a minimum of 250 milliseconds between detections.

runF2

runF2() used only Z axis, and employed weak bias removal via a sliding window but added dynamic beta amplification of the filtered Z data based on the average amplitude above the bias that was removed when the last punch was detected. Also, a dynamic minimum time between punches of 225ms to 270ms was calculated based on delta time since last punch was detected. I called the amount of bias removed noise floor. I added a button to stop and resume the simulation so I could examine the debug output and the waveforms. This allowed me to see the beta amplification being used as the simulation went along.

runF3

runF3() used X and Z axis data. My theory was that there might be a jolt of movement from the punching action that could be additive to the Z axis data to help pinpoint the actual punch. It was basically the same algorithm as RunF2 but added in the X axis. It actually worked pretty well, and I thought I might be onto something here by correlating X movement and Z. I tried various tweaks and gyrations as you can see in the code lots of commented out experiments. I started playing around with what I call a compressor, which took the sum of five samples to see if it would detect bunches of energy around when punches occur. I didn’t use it in the algorithm but printed out how many times it crossed a threshold to see if it had any potential as a filtering element. In the end, this algorithm started to implode on itself, and it was time to take what I learned and start a new algorithm.

runF4

In runF4(), I increased the bias removal average to 50 samples. It started to work in attenuation and sample compression along with a fixed point LSB to preserve some decimal precision to the integer attenuate data. Since one of the requirements was this should be able to run on 8-bit microcontrollers, I wanted to avoid using floating point and time consuming math functions in the final C/C++ code. I’ll speak more to this in the components section, but, for now, know that I’m starting to work this in. I’ve convinced myself that finding bursts of acceleration is the way to go. At this point, I am removing the bias from both Z and X axis then squaring. I then attenuate each, adding the results together but scaling X axis value by 10. I added a second stage of averaging 11 filtered values to start smoothing the bursts of acceleration. Next, when the smoothed value gets above a fixed threshold of 100, the unsmoothed combination of Z and X squared starts getting loaded into the compressor until 100 samples have been added. If the compressor output of the 100 samples is greater than 5000, it is recorded as a hit. A variable time between punches gate is employed, but it is much smaller since the compressor is using 100 samples to encapsulate the punch detection. This lowers the gate time to between 125 and 275 milliseconds. While showing some promise, it was still too sensitive. While one data set would be spot on another would be off by 10 or more punches. After many tweaks and experiments, this algorithm began to implode on itself, and it was once again time to take what I’ve learned and start anew. I should mention that at this tim I’m starting to think there might not be a satisfactory solution to this problem. The resonant vibrations that seem to be out of phase with the contacts of the bag just seems to wreak havoc on the acceleration seen when the boxer gets into a good rhythm. Could this all just be a waste of time?

runF5

runF5()’s algorithm started out with the notion that a more formal high pass filter needed to be introduced rather than an average subtracted from the signal. The basic premise of the high pass filter was to use 99% of the value of new samples added to 1% of the value of average. An important concept added towards the end of runF5’s evolution was to try to simplify the algorithm by removing the first stage of processing into its own file to isolate it from later stages. Divide and Conquer; it’s been around forever, and it really holds true time and time again. I tried many experiments as you can see from the many commented out lines in the algorithm and in the FrontEndProcessorOld.java file. In the end, it was time to carry forward the new Front End Processor concept and start anew with divide and conquer and a need for a more formal high pass filter.

runF6

With time running out, it’s time to pull together all that has been learned up to now, get the Java code ready to port to C/C++ and implement real filters as opposed to using running averages. In runF6(), I had been pulling together the theory that I need to filter out the bias on the front end with a high pass filter and then try to use a low pass filter on the remaining signal to find bursts of acceleration that occur at a 2 to 4 Hertz frequency. No way was I going to learn how to calculate my own filter tap values to implement the high and low pass filters in the small amount of time left before the deadline. Luckily, I discovered the t-filter web site. Talk about a triple play. Not only was I able to put in my parameters and get filter tap values, I was also able to leverage the C code it generated with a few tweaks in my Java code. Plus, it converted the tap values to fixed point for me! Fully employing the divide and conquer concept, this final version of the algorithm introduced isolated sub algorithms for both Front End Processor and Detection Processing. This allowed me to isolate the two functions from each other except for the output signal of one becoming the input to the other, which enabled me to focus easily on the task at hand rather than sift through a large group of variables where some might be shared between the two stages.

With this division of responsibility, it is now easy to focus on making the clear task of the Front End Processor to remove the bias values and output at a level that is readily acceptable for input into the Detection Processor. Now the Detection processor can clearly focus on filtering and implementing a state machine that can pick out the punch events that should occur between 2 and 4 times per second.

One thing to note is that this final algorithm is much smaller and simpler than some of the previous algorithms. Even though its software, at some point in the process you should still do a technique called Muntzing. Muntzing is a technique to go back and look at what can be removed without breaking the functionality. Every line of code that is removed is one less line of code that can have a bug. You can Google Earl “Madman” Muntz to get a better understanding and feel for the spirit of Muntzing.

Final output of DET

Final output of DET

Above is the visual output from runF6. The Green line is 45 samples delayed of the output of the low pass filter, and the yellow line is an average of 99 values of the output of the low pass filter. The Detection Processor includes a detection algorithm that detects punches by tracking min and max crossings of the Green signal using the Yellow signal as a template for dynamic thresholding. Each minimum is a Red spike, and each maximum is a Blue spike, which is also a punch detection. The timescale is in milliseconds. Notice there are about three blue spikes per second inside the 2 to 4Hz range predicted. And the rest is history!

Algorithm Components

Here is a brief look at each type of component I used in the various algorithms.

Delay

This is used to buffer a signal so you can time align it to some other operation. For example, if you average nine samples and you want to subtract the average from the original signal, you can use a delay of five samples of the original signal so you can use values that are itself plus the four samples before and four samples after.

Attenuate

Attenuation is a simple but useful operation that can scale a signal down before it is amplified in some fashion with filtering or some other operation that adds gain to the signal. Typically attenuation is measured in decibels (dB). You can attenuate power or amplitude depending on your application. If you cut the amplitude by half, you are reducing it by -6 dB. If you want to attenuate by other dB values, you can check the dB scale here. As it relates to the Speedbag algorithm, I’m basically trying to create clear gaps in the signal, for instance squelching or squishing smaller values closer to zero so that squaring values later can really push the peaks higher but not having as much effect on the values pushed down towards zero. I used this technique to help accentuate the bursts of acceleration versus background vibrations of the speed bag platform.

Sliding Window Average

Sliding Window Average is a technique of calculating a continuous average of the incoming signal over a given window of samples. The number of samples to be averaged is known as the window size. The way I like to implement a sliding window is to keep a running total of the samples and a ring buffer to keep track of the values. Once the ring buffer is full, the oldest value is removed and replaced with the next incoming value, and the value removed from the ring buffer is subtracted from the new value. That result is added to the running tally. Then simply divide the running total by the window size to get the current average whenever needed.

Rectify

This is a very simple concept which is to change the sign of the values to all positive or all negative so they are additive. In this case, I used rectification to change all values to positive. As with rectification, you can use a full wave or half wave method. You can easily do full wave by using the abs() math function that returns the value as positive. You can square values to turn them positive, but you are changing the amplitude. A simple rectify can turn them positive without any other effects. To perform half wave rectification, you can just set any value less than zero to zero.

Compression

In the DSP world Compression is typically defined as compressing the amplitudes to keep them in a close range. My compression technique here is to sum up the values in a window of samples. This is a form of down-sampling as you only get one sample out each time the window is filled, but no values are being thrown away. It’s a pure total of the window, or optionally an average of the window. This was employed in a few of the algorithms to try to identify bursts of acceleration from quieter times. I didn’t actually use it in the final algorithm.

FIR Filter

Finite Impulse Response (FIR) is a digital filter that is implemented via a number of taps, each with its assigned polynomial coefficient. The number of taps is known as the filter’s order. One strength of the FIR is that it does not use any feedback, so any rounding errors are not cumulative and will not grow larger over time. A finite impulse response simply means that if you input a stream of samples that consisted of a one followed by all zeros, the output of the filter would go to zero within at most the order +1 amount of 0 value samples being fed in. So, the response to that single sample of one lives for a finite amount of samples and is gone. This is essentially achieved by the fact there isn’t any feedback employed. I’ve seen DSP articles claim calculating filter tap size and coefficients is simple, but not to me. I ended up finding an online app called tFilter that saved me a lot of time and aggravation. You pick the type of filter (low, high, bandpass, bandstop, etc) and then setup your frequency ranges and sampling frequency of your input data. You can even pick your coefficients to be produced in fixed point to avoid using floating point math. If you’re not sure how to use fixed point or never heard of it, I’ll talk about that in the Embedded Optimization Techniques section.

Embedded Optimization Techniques

Magnitude Squared

Mag Square is a technique that can save computing power of calculating square roots. For example, if you want to calculate the vector for X and Z axis, normally you would do the following: val = sqr((X * X) + (Y * Y)). However, you can simply leave the value in (X * X) + (Y * Y), unless you really need the exact vector value, the Mag Square gives you a usable ratio compared to other vectors calculated on subsequent samples. The numbers will be much larger, and you may want to use attenuation to make them smaller to avoid overflow from additional computation downstream.

I used this technique in the final algorithm to help accentuate the bursts of acceleration from the background vibrations. I only used Z * Z in my calculation, but I then attenuated all the values by half or -6dB to bring them back down to reasonable levels for further processing. For example, after removing the bias if I had some samples around 2 and then some around 10, when I squared those values I now have 4 and 100, a 25 to 1 ratio. Now, if I attenuate by .5, I have 2 and 50, still a 25 to 1 ratio but now with smaller numbers to work with.

Fixed Point

Using fixed point numbers is another way to stretch performance, especially on microcontrollers. Fixed point is basically integer math, but it can keep precision via an implied fixed decimal point at a particular bit position in all integers. In the case of my FIR filter, I instructed tFilter to generate polynomial values in 16-bit fixed point values. My motivation for this was to ensure I don’t use more than 32-bit integers, which would especially hurt performance on an 8-bit microcontroller.

Rather than go into the FIR filter code to explain how fixed point works, let me first use a simple example. While the FIR filter algorithm does complex filtering with many polynomials, we could implement a simple filter that outputs the same input signal but -6dB down or half its amplitude. In floating point terms, this would be a simple one tap filter to multiply each incoming sample by 0.5. To do this in fixed point with 16 bit precision, we would need to convert 0.5 into its 16-bit fixed point representation. A value of 1.0 is represented by 1 * (216) or 65,536. Anything less than 65536 is a value less than 1. To create a fixed point integer of 0.5, we simply use the same formula 0.5 * (216), which equals 32,768. Now we can use that value to lower the amplitude by .5 of every sample input. For example, say we input into our simple filter a sample with the value of 10. The filter would calculate 10 * 32768 = 327,680, which is the fixed point representation. If we no longer care about preserving the precision after the calculations are performed, it can easily be turned back into a non-fixed point integer by simply right shifting by the number of bits of precision being used. Thus, 327680 >> 16 = 5. As you can see, our filter changed 10 into 5 which of course is the one half or -6dB we wanted out. I know 0.5 was pretty simple, but if you had wanted 1/8 the amplitude, the same process would be used, 65536 * .125 = 8192. If we input a sample of 16, then 16 * 8192 = 131072, now change it back to an integer 131072 >> 16 = 2. Just to demonstrate how you lose the precision when turning back to integer (the same as going float to integer) if we input 10 into the 1/8th filter it would yield the following, 10 * 8192 = 81920 and then turning it back to integer would be 81920 >> 16 = 1, notice it was 1.25 in fixed point representation.

Getting back to the FIR filters, I picked 16 bits of precision, so I could have a fair amount of precision but balanced with a reasonable amount of whole numbers. Normally, a signed 32-bit integer can have a range of - 2,147,483,648 to +2,147,483,647, however there now are only 16 bits of whole numbers allowed which is a range of -32,768 to +32,767. Since you are now limited in the range of numbers you can use, you need to be cognizant of the values being fed in. If you look at the FEPFilter_get function, you will see there is an accumulator variable accZ which sums the values from each of the taps. Usually if your tap history values are 32 bit, you make your accumulator 64-bit to be sure you can hold the sum of all tap values. However, you can use a 32 bit value if you ensure that your input values are all less than some maximum. One way to calculate your maximum input value is to sum up the absolute values of the coefficients and divide by the maximum integer portion of the fixed point scheme. In the case of the FEP FIR filter, the sum of coefficients was 131646, so if the numbers can be 15 bits of positive whole numbers + 16 bits of fractional numbers, I can use the formula (231)/131646 which gives the FEP maximum input value of + or - 16,312. In this case, another optimization can be realized which is not to have a microcontroller do 64-bit calculations.

Walking the Signal Processing Chain

Delays Due to Filtering

Before walking through the processing chain, we should discuss delays caused by filtering. Many types of filtering add delays to the signal being processed. If you do a lot of filtering work, you are probably well aware of this fact, but, if you are not all that experienced with filtering signals, it’s something of which you should be aware. What do I mean by delay? This simply means that if I put in a value X and I get out a value Y, how long it takes for the most impact of X to show up in Y is the delay. In the case of a FIR filter, it can be easily seen by the filter’s Impulse response plot, which, if you remember from my description of FIR filters, is a stream of 0’s with a single 1 inserted. T-Filter shows the impulse response, so you can see how X impacts Y’s output. Below is an image of the FEP’s high pass filter Impulse Response taken from the T-Filter website. Notice in the image that the maximum impact on X is exactly in the middle, and there is a point for each tap in the filter.

Impulse response from T-Filter

Below is a diagram of a few of the FEP’s high pass filter signals. The red signal is the input from the accelerometer or the newest sample going into the filter, the blue signal is the oldest sample in the filter’s ring buffer. There are 19 taps in the FIR filter so they represent a plot of the first and last samples in the filter window. The green signal is the value coming out of the high pass filter. So to relate to my X and Y analogy above, the red signal is X and the green signal is Y. The blue signal is delayed by 36 milliseconds in relation to the red input signal which is exactly 18 samples at 2 milliseconds, this is the window of data that the filter works on and is the Finite amount of time X affects Y.

Delayed Signal Example

Notice the output of the high pass filter (green signal) seems to track changes from the input at a delay of 18 milliseconds, which is 9 samples at 2 milliseconds each. So, the most impact from the input signal is seen in the middle of the filter window, which also coincides with the Impulse Response plot where the strongest effects of the 1 value input are seen at the center of the filter window.

It’s not only a FIR that adds delay. Usually, any filtering that is done on a window of samples will cause a delay, and, typically, it will be half the window length. Depending on your application, this delay may or may not have to be accounted for in your design. However, if you want to line this signal up with another unfiltered or less filtered signal, you are going to have to account for it and align it with the use of a delay component.

Front End Processor

I’ve talked at length about how to get to a final solution and all the components that made up the solution, so now let’s walk through the processing chain and see how the signal is transformed into one that reveals the punches. The FEP’s main goal is to remove bias and create an output signal that smears across the bursts of acceleration to create a wave that is higher in amplitude during increased acceleration and lower amplitude during times of less acceleration. There are four serial components to the FEP: a High Pass FIR, Attenuator, Rectifier and Smoothing via Sliding Window Average.

The first image is the input and output of the High Pass FIR. Since they are offset by the amount of bias, they don’t overlay very much. The red signal is the input from the accelerometer, and the blue is the output from the FIR. Notice the 1g of acceleration due to gravity is removed and slower changes in the signal are filtered out. If you look between 24,750 and 25,000 milliseconds, you can see the blue signal is more like a straight line with spikes and a slight ringing on it, while the original input has those spikes but meandering on some slow ripple.

FEP Highpass In Out

Next is the output of the attenuator. While this component works on the entire signal, it lowers the peak values of the signal, but its most important job is to squish the quieter parts of the signal closer to zero values. The image below shows the output of the attenuator, and the input was the output of the High Pass FIR. As expected, peaks are much lower but so is the quieter time. This makes it a little easier to see the acceleration bursts.

FEP Atten Out

Next is the rectifier component. Its job is to turn all the acceleration energy in the positive direction so that it can be used in averaging. For example, an acceleration causing a positive spike of 1000 followed by a negative spike of 990 would yield an average of 5, while a 1000 followed by a positive of 990 would yield an average of 995, a huge difference. Below is an image of the Rectifier output. The bursts of acceleration are slightly more visually apparent, but not easily discernable. In fact, this image shows exactly why this problem is such a tough one to solve; you can clearly see how resonant shaking of the base causes the pattern to change during punch energy being added. The left side is lower and more frequent peaks, the right side has higher but less frequent peaks.

FEP Rectifier Out

The 49 value sliding window is the final step in the FEP. While we have done subtle changes to the signal that haven’t exactly made the punches jump out in the images, this final stage makes it visually apparent that the signal is well on its way of yielding the hidden punch information. The fruits of the previous signal processing magically show up at this stage. Below is an image of the Sliding Window average. The blue signal is its input or the output of the Rectifier, and the red signal is the output of the sliding window. The red signal is also the final output of the FEP stage of processing. Since it is a window, it has a delay associated with it. Its approximately 22 samples or 44 milliseconds on average. It doesn’t always look that way because sometimes the input signal spikes are suddenly tall with smaller ringing afterwards. Other times there are some small spikes leading up to the tall spikes and that makes the sliding window average output appear inconsistent in its delay based on where the peak of the output shows up. Although these bumps are small, they are now representing where new acceleration energy is being introduced due to punches.

FEP Final Out

Detection Processor

Now it’s time to move on to the Detection Processor (DET). The FEP outputs a signal that is starting to show where the bursts of acceleration are occurring. The DET’s job will be to enhance this signal and employ an algorithm to detect where the punches are occurring.

The first stage of the DET is an attenuator. Eventually, I want to add exponential gain to the signal to really pull up the peaks, but, before doing that, it is important to once again squish down the lower values towards zero and lower the peaks to keep from generating values too large to process in the rest of the DET chain. Below is an image of the output from the attenuator stage, it looks just like the signal output from the FEP, however notice the signal level peaks were above 100 from the FEP, and now peaks are barely over 50. The vertical scale is zoomed in with the max amplitude set to 500 so you can see that there is a viable signal with punch information.

DET-Atten-Out

With the signal sufficiently attenuated, it’s time to create the magic. The Magnitude Square function is where it all comes together. The attenuated signal carries the tiny seeds from which I’ll grow towering Redwoods. Below is an image of the Mag Square output, the red signal is the attenuated input, and the blue signal is the mag square output. I’ve had to zoom out to a 3,000 max vertical, and, as you can see, the input signal almost looks flat, yet the mag square was able to pull out unmistakable peaks that will aid the detection algorithm to pick out punches. You might ask why not just use these giant peaks to detect punches. One of the reasons I’ve picked this area of the signal to analyze is to show you how the amount of acceleration can vary greatly as you can see the peak between 25,000 and 25,250 is much smaller than the surrounding peaks, which makes pure thresholding a tough chore.

DET Mag Square

Next, I decided to put a Low Pass filter to try to remove any fast changing parts of the signal since I’m looking for events that occur in the 2 to 4 Hz range. It was tough on T-Filter to create a tight low pass filter with a 0 to 5 Hz band pass as it was generating filters with over 100 taps, and I didn’t want to take that processing hit, not to mention I would then need a 64-bit accumulator to hold the sum. I relaxed the band pass with a 0 to 19 Hz range and the band stop at 100 to 250 Hz. Below is an image of the low pass filter output. The blue signal is the input, and the red signal is the delayed output. I used this image because it allows the input and output signal to be seen without interfering with each other. The delay is due to 6 sample delay of the low pass FIR, but I have also introduced a 49 sample delay to this signal so that it is aligned in the center of the 99 sample sliding window average that follows in the processing chain. So it is delayed by a total of 55 samples or 110 milliseconds. In this image, you can see the slight amplification of the slow peaks by their height and how it is smoothed as the faster changing elements are attenuated. Not a lot going on here but the signal is a little cleaner, Earl Muntz might suggest I cut the low pass filter out of the circuit, and it might very well work without it.

Low pass delayed DET

The final stage of the signal processing is a 99 sample sliding window average. I built into the sliding window average the ability to return the sample in the middle of the window each time a new value is added and that is how I produced the 49 sample delayed signal in the previous image. This is important because the detection algorithm is going to have 2 parallel signals passed into it, the output of the 99 sliding window average and the 49 sample delayed input into the sliding window average. This will perfectly align the un-averaged signal in the middle of the sliding window average. The averaged signal is used as a dynamic threshold for the detection algorithm to use in its detection processing. Here, once again, is the image of the final output from the DET.

DET Final Out

In the image, the green and yellow signals are inputs to the detection algorithm, and the blue and red are outputs. As you can see, the green signal, which is a 49 samples delayed, is aligned perfectly with the yellow 99 sliding window average peaks. The detection algorithm monitors the crossing of the yellow by the green signal. This is accomplished by both maximum and minimum start guard state that verifies the signal has moved enough in the minimum or maximum direction in relation to the yellow signal and then switches to a state that monitors the green signal for enough change in direction to declare a maximum or minimum. When the peak start occurs and it’s been at least 260ms since the last detected peak, the state switches to monitor for a new peak in the green signal and also makes the blue spike seen in the image. This is when a punch count is registered. Once a new peak has been detected, the state changes to look for the start of a new minimum. Now, if the green signal falls below the yellow by a delta of 50, the state changes to look for a new minimum of the green signal. Once the green signal minimum is declared, the state changes to start looking for the start of a new peak of the green signal, and a red spike is shown on the image when this occurs.

Again, I’ve picked this time in the recorded data because it shows how the algorithm can track the punches even during big swings in peak amplitude. What’s interesting here is if you look between the 24,750 and 25,000 time frame, you can see the red spike detected a minimum due to the little spike upward of the green signal, which means the state machine started to look for the next start of peak at that point. However, the green signal never crossed the yellow line, so the start of peak state rode the signal all the way down to the floor and waited until the cross of the yellow line just before the 25,250 mark to declare the next start of peak. Additionally, the peak at the 25,250 mark is much lower than the surrounding peaks, but it was still easily detected. Thus, the dynamic thresholding and the state machine logic allows the speed bag punch detector algorithm to “Roll with the Punches”, so to speak.

Final Thoughts

To sum up, we’ve covered a lot of ground in this article. First, the importance of fully understanding the problem as it relates to the required end item along with the domain knowledge needed to get there. Second, for a problem of this nature creating a scaffold environment to build the algorithm was imperative, and in this instance, it was the Java prototype with visual display of the signals. Third, was implement for the target environment, on a PC you have wonderful optimizing compilers for powerful CPUs with tons of cache, for a microcontroller the optimization is really left to you. Use every optimization trick you know to keep processing as quick as possible. Fourth, iterative development can help you on problems like this. Keep reworking the problem while folding in the knowledge you are learning during the development process.

When I look back on this project and think about what ultimately made me successful, I can think of two main things. Creating the right tools for the job was invaluable. Being able to see how my processing components were affecting the signal was really invaluable. Not only plotting the output signal, but having it plot in realtime, allowed me to fully understand the acceleration being generated. It was as if Nate was in the corner punching the bag, and I was watching the waveform roll in on my screen. However, the biggest factor was realizing that in the end I am looking for something that happens 2 to 4 times per second. I latched on to that and relentlessly pursued how to translate the raw incoming signal into something that would show those events. There was nothing for me to Google to find that answer. Remember knowledge doesn’t really come from books, it gets recorded in books. First, someone had to go off script and discover something and then it becomes knowledge. Apply the knowledge you have and can find, but don’t be afraid to use your imagination to try what hasn’t been tried before to solve an unsolved problem. So remember in the future, metaphorically when you come to the end of the paved road. Will you turn around looking for a road already paved ,or will you lock in the hubs and keep plowing ahead to make your own discovery. I wasn’t able to just Google how to count punches with an accelerometer, but now someone can.

Pull-up Resistors

Introduction

Pull-up resistors are very common when using microcontrollers (MCUs) or any digital logic device. This tutorial will explain when and where to use pull-up resistors, then we will do a simple calculation to show why pull-ups are important.

What is a Pull-up Resistor

Let’s say you have an MCU with one pin configured as an input. If there is nothing connected to the pin and your program reads the state of the pin, will it be high (pulled to VCC) or low (pulled to ground)? It is difficult to tell. This phenomena is referred to as floating. To prevent this unknown state, a pull-up or pull-down resistor will ensure that the pin is in either a high or low state, while also using a low amount of current.

For simplicity, we will focus on pull-ups since they are more common than pull-downs. They operate using the same concepts, except the pull-up resistor is connected to the high voltage (this is usually 3.3V or 5V and is often refereed to as VCC) and the pull-down resistor is connected to ground.

Pull-ups are often used with buttons and switches.

With a pull-up resistor, the input pin will read a high state when the button is not pressed. In other words, a small amount of current is flowing between VCC and the input pin (not to ground), thus the input pin reads close to VCC. When the button is pressed, it connects the input pin directly to ground. The current flows through the resistor to ground, thus the input pin reads a low state. Keep in mind, if the resistor wasn’t there, your button would connect VCC to ground, which is very bad and is also known as a short.

So what value resistor should you choose?

The short and easy answer is that you want a resistor value on the order of 10kΩ for the pull-up.

A low resistor value is called a strong pull-up (more current flows), a high resistor value is called a weak pull-up (less current flows).

The value of the pull-up resistor needs to be chosen to satisfy two conditions:

  1. When the button is pressed, the input pin is pulled low. The value of resistor R1 controls how much current you want to flow from VCC, through the button, and then to ground.
  2. When the button is not pressed, the input pin is pulled high. The value of the pull-up resistor controls the voltage on the input pin.

For condition 1, you don’t want the resistor’s value too low. The lower the resistance, the more power will be used when the button is hit. You generally want a large resistor value (10kΩ), but you don’t want it too large as to conflict with condition 2. A 4MΩ resistor might work as a pull-up, but its resistance is so large (or weak) that it may not do its job 100% of the time.

The general rule for condition 2 is to use a pull-up resistor (R1) that is an order of magnitude (1/10th) less than the input impedance (R2) of the input pin. An input pin on a microcontroller has an impedance that can vary from 100k-1MΩ. For this discussion, impedance is just a fancy way of saying resistance and is represented by R2 in the picture above. So, when the button is not pressed, a very small amount of current flows from VCC through R1 and into the input pin. The pull-up resistor R1 and input pin impedance R2 divides the voltage, and this voltage needs to be high enough for the input pin to read a high state.

For example, if you use a 1MΩ resistor for the pull-up R1 and the input pin’s impedance R2 is on the order of 1MΩ (forming a voltage divider), the voltage on the input pin is going to be around half of VCC, and the microcontroller might not register the pin being in a high state. On a 5V system, what does the MCU read on the input pin if the voltage is 2.5V? Is it a high or a low? The MCU doesn’t know and you might read either a high or a low. A resistance of 10k to 100kΩ for R1 should avoid most problems.

Since pull-up resistors are so commonly needed, many MCUs, like the ATmega328 microcontroller on the Arduino platform, have internal pull-ups that can be enabled and disabled. To enable internal pull-ups on an Arduino, you can use the following line of code in your setup() function:

pinMode(5, INPUT_PULLUP); // Enable internal pull-up resistor on pin 5

Another thing to point out is that the larger the resistance for the pull-up, the slower the pin is to respond to voltage changes. This is because the system that feeds the input pin is essentially a capacitor coupled with the pull-up resistor, thus forming a RC filter, and RC filters take some time to charge and discharge. If you have a really fast changing signal (like USB), a high value pull-up resistor can limit the speed at which the pin can reliably change state. This is why you will often see 1k to 4.7KΩ resistors on USB signal lines.

All of these factors play into the decision on what value pull-up resistor to use.

Calculating a Pull-up Resistor Value

Let’s say you want to limit the current to approximately 1mA when the button is pressed in the circuit above, where Vcc = 5V. What resistor value should you use?

It is easy to show how to calculate the pull-up resistor using Ohm’s Law:

alt text

Referring to the schematic above, Ohm’s Law now is:

alt text

Rearrange the above equation with some simple algebra to solve for the resistor:

alt text

Remember to convert all of your units into volts, amps and Ohms before calculating (e.g. 1mA = 0.001 Amps). The solution is to use a 5kΩ resistor.

Now you should be familiar with what a pull-up resistor is and how it works.

Serial Communication

CONTRIBUTORS:  JIMB0

 FAVORITE25

 SHARE

Share on TwitterShare on FacebookPin It

Introduction

Embedded electronics is all about interlinking circuits (processors or other integrated circuits) to create a symbiotic system. In order for those individual circuits to swap their information, they must share a common communication protocol. Hundreds of communication protocols have been defined to achieve this data exchange, and, in general, each can be separated into one of two categories: parallel or serial.

Parallel vs. Serial

Parallel interfaces transfer multiple bits at the same time. They usually require buses of data - transmitting across eight, sixteen, or more wires. Data is transferred in huge, crashing waves of 1’s and 0’s.

1

            An 8-bit data bus, controlled by a clock, transmitting a byte every clock pulse. 9 wires are used.

Serial interfaces stream their data, one single bit at a time. These interfaces can operate on as little as one wire, usually never more than four.

1.5

            Example of a serial interface, transmitting one bit every clock pulse. Just 2 wires required!

Think of the two interfaces as a stream of cars: a parallel interface would be the 8+ lane mega-highway, while a serial interface is more like a two-lane rural country road. Over a set amount of time, the mega-highway potentially gets more people to their destinations, but that rural two-laner serves its purpose and costs a fraction of the funds to build.

Parallel communication certainly has its benefits. It’s fast, straightforward, and relatively easy to implement. But it requires many more input/output (I/O) lines. If you’ve ever had to move a project from a basic Arduino Uno to a Mega, you know that the I/O lines on a microprocessor can be precious and few. So, we often opt for serial communication, sacrificing potential speed for pin real estate.

Asynchronous Serial

Over the years, dozens of serial protocols have been crafted to meet particular needs of embedded systems. USB (universal serial bus), and Ethernet, are a couple of the more well-known computing serial interfaces. Other very common serial interfaces include SPI, I2C, and the serial standard we’re here to talk about today. Each of these serial interfaces can be sorted into one of two groups: synchronous or asynchronous.

A synchronous serial interface always pairs its data line(s) with a clock signal, so all devices on a synchronous serial bus share a common clock. This makes for a more straightforward, often faster serial transfer, but it also requires at least one extra wire between communicating devices. Examples of synchronous interfaces include SPI, and I2C.

            Asynchronous means that data is transferred without support from an external clock signal. This transmission method is perfect for minimizing the required wires and I/O pins, but it does mean we need to put some extra effort into reliably transferring and receiving data. The serial protocol we’ll be discussing in this tutorial is the most common form of asynchronous transfers. It is so common, in fact, that when most folks say “serial” they’re talking about this protocol (something you’ll probably notice throughout this tutorial).

The clock-less serial protocol we’ll be discussing in this tutorial is widely used in embedded electronics. If you’re looking to add a GPS module, Bluetooth, XBee’s, serial LCDs, or many other external devices to your project, you’ll probably need to whip out some serial-fu.

Rules of Serial

The asynchronous serial protocol has a number of built-in rules - mechanisms that help ensure robust and error-free data transfers. These mechanisms, which we get for eschewing the external clock signal, are:

  • Data bits,
  • Synchronization bits,
  • Parity bits,
  • and Baud rate.

Through the variety of these signaling mechanisms, you’ll find that there’s no one way to send data serially. The protocol is highly configurable. The critical part is making sure that both devices on a serial bus are configured to use the exact same protocols.

Baud Rate

The baud rate specifies how fast data is sent over a serial line. It’s usually expressed in units of bits-per-second (bps). If you invert the baud rate, you can find out just how long it takes to transmit a single bit. This value determines how long the transmitter holds a serial line high/low or at what period the receiving device samples its line.

Baud rates can be just about any value within reason. The only requirement is that both devices operate at the same rate. One of the more common baud rates, especially for simple stuff where speed isn’t critical, is 9600 bps. Other “standard” baud are 1200, 2400, 4800, 19200, 38400, 57600, and 115200.

The higher a baud rate goes, the faster data is sent/received, but there are limits to how fast data can be transferred. You usually won’t see speeds exceeding 115200 - that’s fast for most microcontrollers. Get too high, and you’ll begin to see errors on the receiving end, as clocks and sampling periods just can’t keep up.

Framing the data

Each block (usually a byte) of data transmitted is actually sent in a packet or frame of bits. Frames are created by appending synchronization and parity bits to our data.

2

            A serial frame. Some symbols in the frame have configurable bit sizes.

Let’s get into the details of each of these frame pieces.

Data chunk

The real meat of every serial packet is the data it carries. We ambiguously call this block of data a chunk, because its size isn’t specifically stated. The amount of data in each packet can be set to anything from 5 to 9 bits. Certainly, the standard data size is your basic 8-bit byte, but other sizes have their uses. A 7-bit data chunk can be more efficient than 8, especially if you’re just transferring 7-bit ASCII characters.

After agreeing on a character-length, both serial devices also have to agree on the endianness of their data. Is data sent most-significant bit (msb) to least, or vice-versa? If it’s not otherwise stated, you can usually assume that data is transferred least-significant bit (lsb) first.

Synchronization bits

The synchronization bits are two or three special bits transferred with each chunk of data. They are the start bit and the stop bit(s). True to their name, these bits mark the beginning and end of a packet. There’s always only one start bit, but the number of stop bits is configurable to either one or two (though it’s commonly left at one).

The start bit is always indicated by an idle data line going from 1 to 0, while the stop bit(s) will transition back to the idle state by holding the line at 1.

Parity bits

Parity is a form of very simple, low-level error checking. It comes in two flavors: odd or even. To produce the parity bit, all 5-9 bits of the data byte are added up, and the evenness of the sum decides whether the bit is set or not. For example, assuming parity is set to even and was being added to a data byte like 0b01011101, which has an odd number of 1’s (5), the parity bit would be set to 1. Conversely, if the parity mode was set to odd, the parity bit would be 0.

Parity is optional, and not very widely used. It can be helpful for transmitting across noisy mediums, but it’ll also slow down your data transfer a bit and requires both sender and receiver to implement error-handling (usually, received data that fails must be re-sent).

9600 8N1 (an example)

9600 8N1 - 9600 baud, 8 data bits, no parity, and 1 stop bit - is one of the more commonly used serial protocols. So, what would a packet or two of 9600 8N1 data look like? Let’s have an example!

A device transmitting the ASCII characters ‘O’ and ‘K’ would have to create two packets of data. The ASCII value of O(that’s uppercase) is 79, which breaks down into an 8-bit binary value of 01001111, while K’s binary value is01001011. All that’s left is appending sync bits.

It isn’t specifically stated, but it’s assumed that data is transferred least-significant bit first. Notice how each of the two bytes is sent as it reads from right-to-left.

3

Since we’re transferring at 9600 bps, the time spent holding each of those bits high or low is 1/(9600 bps) or 104 µs per bit.

For every byte of data transmitted, there are actually 10 bits being sent: a start bit, 8 data bits, and a stop bit. So, at 9600 bps, we’re actually sending 9600 bits per second or 960 (9600/10) bytes per second.

Now that you know how to construct serial packets, we can move on to the hardware section. There we’ll see how those 1’s and 0’s and the baud rate are implemented at a signal level!

Wiring and Hardware

A serial bus consists of just two wires - one for sending data and another for receiving. As such, serial devices should have two serial pins: the receiver, RX, and the transmitter, TX.

4

It’s important to note that those RX and TX labels are with respect to the device itself. So the RX from one device should go to the TX of the other, and vice-versa. It’s weird if you’re used to hooking up VCC to VCC, GND to GND, MOSI to MOSI, etc., but it makes sense if you think about it. The transmitter should be talking to the receiver, not to another transmitter.

A serial interface where both devices may send and receive data is either full-duplex or half-duplex. Full-duplex means both devices can send and receive simultaneously. Half-duplex communication means serial devices must take turns sending and receiving.

Some serial busses might get away with just a single connection between a sending and receiving device. For example, our Serial Enabled LCDs are all ears and don’t really have any data to relay back to the controlling device. This is what’s known as simplex serial communication. All you need is a single wire from the master device’s TX to the listener’s RX line.

Hardware Implementation

We’ve covered asynchronous serial from a conceptual side. We know which wires we need. But how is serial communication actually implemented at a signal level? In a variety ways, actually. There are all sorts of standards for serial signaling. Let’s look at a couple of the more popular hardware implementations of serial: logic-level (TTL) and RS-232.

When microcontrollers and other low-level ICs communicate serially they usually do so at a TTL (transistor-transistor logic) level. TTL serial signals exist between a microcontroller’s voltage supply range - usually 0V to 3.3V or 5V. A signal at the VCC level (3.3V, 5V, etc.) indicates either an idle line, a bit of value 1, or a stop bit. A 0V (GND) signal represents either a start bit or a data bit of value 0.

5

RS-232, which can be found on some of the more ancient computers and peripherals, is like TTL serial flipped on its head. RS-232 signals usually range between -13V and 13V, though the spec allows for anything from +/- 3V to +/- 25V. On these signals a low voltage (-5V, -13V, etc.) indicates either the idle line, a stop bit, or a data bit of value 1. A high RS-232 signal means either a start bit, or a 0-value data bit. That’s kind of the opposite of TTL serial.

6

Between the two serial signal standards, TTL is much easier to implement into embedded circuits. However the low voltage levels are more susceptible to losses across long transmission lines. RS-232, or more complex standards like RS-485, are better suited to long range serial transmissions.

When you’re connecting two serial devices together, it’s important to make sure their signal voltages match up. You can’t directly interface a TTL serial device with an RS-232 bus. You’ll have to shift those signals!

Continuing on, we’ll explore the tool microcontrollers use to convert their data on a parallel bus to and from a serial interface. UARTs!

UARTs

The final piece to this serial puzzle is finding something to both create the serial packets and control those physical hardware lines. Enter the UART.

A universal asynchronous receiver/transmitter (UART) is a block of circuitry responsible for implementing serial communication. Essentially, the UART acts as an intermediary between parallel and serial interfaces. On one end of the UART is a bus of eight-or-so data lines (plus some control pins), on the other is the two serial wires - RX and TX.

7

            Super-simplified UART interface. Parallel on one end, serial on the other.

UARTs do exist as stand-alone ICs, but they’re more commonly found inside microcontrollers. You’ll have to check your microcontroller’s datasheet to see if it has any UARTs. Some have none, some have one, some have many. For example, the Arduino Uno - based on the “old faithful” ATmega328 - has just a single UART, while the Arduino Mega - built on an ATmega2560 - has a whopping four UARTs.

As the R and T in the acronym dictate, UARTs are responsible for both sending and receiving serial data. On the transmit side, a UART must create the data packet - appending sync and parity bits - and send that packet out the TX line with precise timing (according to the set baud rate). On the receive end, the UART has to sample the RX line at rates according to the expected baud rate, pick out the sync bits, and spit out the data.

8

            Internal UART block diagram (courtesy of the Exar ST16C550 datasheet)

More advanced UARTs may throw their received data into a buffer, where it can stay until the microcontroller comes to get it. UARTs will usually release their buffered data on a first-in-first-out (FIFO) basis. Buffers can be as small as a few bits, or as large as thousands of bytes.

Software UARTs

If a microcontroller doesn’t have a UART (or doesn’t have enough), the serial interface can be bit-banged - directly controlled by the processor. This is the approach Arduino libraries like SoftwareSerial take. Bit-banging is processor-intensive, and not usually as precise as a UART, but it works in a pinch!

Common Pitfalls

That’s about all there is to serial communication. I’d like to leave you with a few common mistakes that are easy for an engineer of any experience level to make:

RX-to-TX, TX-to-RX

Seems simple enough, but it’s a mistake I know I’ve made more than a few times. As much as you want their labels to match up, always make sure to cross the RX and TX lines between serial devices.

10

            FTDI Basic programming a Pro Mini. Note RX and TX’s crossed!

Baud Rate Mismatch

Baud rates are like the languages of serial communication. If two devices aren’t speaking at the same speed, data can be either misinterpreted, or completely missed. If all the receiving device sees on its receive line is garbage, check to make sure the baud rates match up.

9

            Data transmitted at 9600 bps, but received at 19200 bps. Baud mismatch = garbage.

Bus Contention

Serial communication is designed to allow just two devices to communicate across one serial bus. If more than one device is trying to transmit on the same serial line you could run into bus-contention. Dun dun dun….

For example, if you’re connecting a GPS module up to your Arduino, you may just wire that module’s TX line up the Arduino’s RX line. But that Arduino RX pin is already wired up to the TX pin of the USB-to-serial converter, which is used whenever you program the Arduino or use the Serial Monitor. This sets up the potential situation where both the GPS module and FTDI chip are trying to transmit on the same line at the same time.

11

            Two transmitters sending to a single receiver sets up the possibility for bus contention.

Two devices trying to transmit data at the same time, on the same line, is bad! At “best” neither of the devices will get to send their data. At worst, both device’s transmit lines go poof (though that’s rare, and usually protected against).

It can be safe to connect multiple receiving devices to a single transmitting device. Not really up to spec and probably frowned upon by a hardened engineer, but it’ll work. For example, if you’re connecting a serial LCD up to an Arduino, the easiest approach may be to connect the LCD module’s RX line to the Arduino’s TX line. The Arduino’s TX is already connected to the USB programmer’s RX line, but that still leaves just one device in control of the transmission line.

12

Distributing a TX line like this can still be dangerous from a firmware perspective, because you can’t pick and choose which device hears what transmission. The LCD will end up receiving data not meant for it, which could command it to go into an unknown state.

In general - one serial bus, two serial devices!

Installing an Arduino Bootloader

Overview

Do you have a bricked Arduino that won’t accept code anymore? Or, maybe you wrote your own firmware and would like to upload it to your Arduino? Or, maybe you just want to learn more about the inner-workings of Arduino, AVR, and microcontrollers in general. Well, you’re in luck! This tutorial will teach you what a bootloader is, why you would need to install/reinstall it, and go over the process of doing so.

AVR Programmers Connected to Arduinos

Suggested Reading

You may want to check out these tutorials before continuing down the bootloader path.

What is a Bootloader?

Atmel AVRs are great little ICs, but they can be a bit tricky to program. You need a special programmer and some fancy .hex files, and its not very beginner friendly. The Arduino has largely done away with these issues. They've put a .hex file on their AVR chips that allows you to program the board over the serial port, meaning all you need to program your Arduino is a USB cable.

The bootloader is basically a .hex file that runs when you turn on the board. It is very similar to the BIOS that runs on your PC. It does two things. First, it looks around to see if the computer is trying to program it. If it is, it grabs the program from the computer and uploads it into the ICs memory (in a specific location so as not to overwrite the bootloader). That is why when you try to upload code, the Arduino IDE resets the chip. This basically turns the IC off and back on again so the bootloader can start running again. If the computer isn't trying to upload code, it tells the chip to run the code that's already stored in memory. Once it locates and runs your program, the Arduino continuously loops through the program and does so as long as the board has power.

Why Install a Bootloader

If you are building your own Arduino, or need to replace the IC, you will need to install the bootloader. You may also have a bad bootloader (although this is very rare) and need to reinstall the bootloader. There are also cases where you've put your board in a weird setting and reinstalling the bootloader and getting it back to factory settings is the easiest way to fix it. We've seen boards where people have turned off the serial port meaning that there is no way to upload code to the board, while there may be other ways to fix this, reinstalling the bootloader is probably the quickest and easiest. Like I said, having a bad bootloader is actually very very rare. If you have a new board that isn't accepting code, 99.9% of the time its not the bootloader. For the other 1% of the time it is, this guide will help you fix that problem.

Selecting a Programmer

We are going to talk about two different types of programmers you can use to install or reinstall bootloaders.

Option 1: Dedicated Programmers

For a quick easy programmer we recommend looking into the AVR Pocket Programmer (Windows only).

a

Or, you can use the official Atmel AVR MKII programmer (Now discontinued) or the Atmel JTAG ICE3 programmer.

b

                                AVR MKII

c

                                 JTAG ICE3

The AVR Pocket Programmer or most cheaper options will work just fine for most applications, but they may have problems with some boards, specifically ones with lots of memory like the ATMega2560 based boards.

Option 2: Using the Arduino as a Programmer

The other option is grabbing an Arduino Uno (or Duemilanove). If you go into the Arduino IDE you will see an example sketch called ‘Arduino as ISP.’ If you upload this code to your Arduino, it will basically act as an AVR programmer. This isn’t really recommended for production of boards, or boards with lots of memory, but, in a pinch, it works pretty well. Also as of this writing the code only works on ATmega328 boards. Maybe one day it will work on the Leonardo or Due, but not yet.

Connecting the Programmer

In-Circuit Serial Programming (ICSP)

It’s very uncommon to program ICs before they are soldered onto a PCB. Instead, most microcontrollers have what’s called an in-system programming (ISP) header. Particularly, some IC manufacturers, such as Atmel and Microchip, have a specialized ISP method for programming their ICs. This is referred to as in-circuit serial programming (ICSP) Most Arduino and Arduino compatible boards will have a 2x3 pin ICSP header on them. Some may even have more than one depending on how many ICs live on the PCB. It breaks out three of the SPI pins (MISO, MOSI, SCK), and power, ground, and reset. These are the pins you’ll need to connect your programmer to in order to reflash the firmware on your board.

d

Here we have the Arduino Uno R3. It has two ICSP headers: one for the ATmega16U2 and one for the ATmega328. To reflash the bootloader on this board, you would use just the ICSP header for the ATmega328.

On some smaller boards you may not see this connector, but the pins should be broken out elsewhere. Whether you’re using an SMD IC or a DIP IC, the ISP pins should be accessible in one form or another. Some boards might only have test points for the ISP header. If this is the case, you may want to consider getting an ISP Pogo Adapter. This kit allows you to temporarily make a good connection with test test points in order to reprogram your IC.

f

ISP Pogo Adapter Kit Fully Assembled. You can connect any of the programmers we mentioned in the previous section to this board.

If you are having trouble finding the ICSP pins on your particular Arduino board, you can consult this website for detailed pinouts of most Arduino related ICs and then some.

Once you have located the six ICSP pins on your board, it’s time to hook up your programmer to the board. You can use a programming cable to connect the two, or, if you don’t have a cable, you can just use some male-to-female jumper wires.

Connecting the Pocket AVR Programmer to Target

If you are using a programmer such as the pocket AVR programmer, your setup should look something like the connection below with the AVR programming cable's arrow (◄) connected to MISO. If you look really closely at the molding of the 2x3 connector, you should be able to notice the arrow (◄) pointing to pin 1 relative to the position of a standard ICSP header.

Top View of the Pocket AVR Programmer Connected to a Target AVR Arduino Uno with Pinouts

Heads up! There is a subtle difference in the orientation of the 2x5 to 2x3 AVR programming cable compared to other 2x3 cables that are attached to official Atmel programmers. As shown in the image below with MISO highlighted by a white dot, the pocket AVR programmer's cable has MISO connected closer toward the inside of the cable. The AVR MKII's cable has MISO connected closer toward the outside of the cable.

Pocket AVR Programmer and Atmel AVR MKII Connected to RedBoards

You also might notice that there is not a cable USB cable connected to one of the RedBoards. Since the pocket AVR programmer can provide 5V power to the target AVR with the switch flipped to the Power Target position, a USB cable is not needed for the RedBoard. However, the official Atmel AVR MKII is not able to provide power to the target board. Thus, a cable is required to connect to the target AVR.

The same goes for newer Atmel programmers. The image below shows the Atmel JTAG ICE3 connected to a RedBoard. As you can see, the position of the AVR cable is connected to the RedBoard similar to the image with the AVR MKII. Since the programmer is not able to provide power to the target, you would need an additional cable connected to the target AVR.

Atmel JTAG ICE3 Connected to RedBoard
 

Connecting the Arduino as ISP to Target

Or, if you're using the Arduino as your programmer, it should look the image below. Make sure to power the Arduino as ISP by connecting it to your computer.

Fritzing Diagram of Arduino as ISP Connected to Target Arduino

Hookup Table

Here's a table to help clarify which connections go where. Depending on the Arduino, you may have access to the ICSP pins only on the 2x3 ICSP header. Make sure to refer to the board layout for more information on the Arduino's SPI connections.

AVR Programmer Arduino as ISP 2x3 ICSP Header ATmega328 ATmega2560 ATmega32U4
5V Vcc/5V Pin 2 Vcc Vcc Vcc
GND GND Pin 6 GND GND GND
MOSI MOSI/D11 Pin 4 D11 D51 D16
MISO MISO/D12 Pin 1 D12 D50 D14
SCK SCK/D13 Pin 3 D13 D52 D15
Reset D10 Pin 5 Reset Reset Reset

Uploading Code - Easy Way

The easy way to upload the bootloader involves using the Arduino IDE.

Upload Arduino as ISP

Grab a known good RedBoard or Arduino Uno. Open your Arduino IDE. In your menu, select File > Examples > 11.ArduinoISP > ArduinoISP to open up the Arduino as ISP sketch

Arduino as ISP Sketch

Select the COM port for your Arduino as ISP. The COM port may be different depending on how it enumerated on your computer.

Select COM Port

Upload the code to your Arduino to turn it into a AVRISP.

Upload Code

Burning a Bootloader to Your Target

Leave the Arduino as ISP (i.e. your programmer) connected to your computer. If you have not already, connect your target Arduino. Then select the board definition for your target Arduino under Tools > Board.

Board Selection for Target

Select the programmer that you are using under Tools > Programmer. In this case, our programmer is an Arduino as ISP so select ArduinoISP. You will also need to select the COM port that the Arduino as ISP is connected to if you have not selected the COM port already.

Programmer

Finally, select Burn Bootloader. This will take the board you selected in the Arduino IDE and look up the associated bootloader in the board.txt file. Then, it will find the bootloader in the Arduino IDE's program folder (specifically "...\Arduino\hardware\arduino\avr\bootloaders") and install it. This only works if the board is installed correctly in the IDE and you have the correct bootloader.

Burn Bootloader

If for some reason you want to use a bootloader that isn't installed in the Arduino IDE, visit the next section. However, it's probably easier to just install the bootloader from the Arduino IDE. For those who are curious about settings such as fuse bits, have no fear. Arduino takes care of all the messy details for you when you burn bootloaders through it.

Uploading Code - Hard Way

The hard way is for those people who want to use the command line. This method may be more preferable if you are modifying and recompiling and don't want to have to keep updating the IDE, but otherwise it's pretty unnecessary. Again, you will need to get the programmer and hook everything up. In this example, we are using avrdude on Windows.

There are three steps to this process:

  • Set Fuse Bits (i.e. Low, High, and Extended)
  • Flash .hex File
  • Set Lock Bits

The first step involves setting the fusebits. Fusebits are the part of the AVR chip that determine things like whether you are using an external crystal or whether you want brown out detection. The commands listed below are specifically for the Arduino Uno using an ATMega328, they will probably work on some other similar boards such as the Duemilanove, but make sure you know what you are doing before playing with fusebits. All the required fuse bits are listed in the boards.txt file for different boards. Again, if you have a boards.txt file installed then just use the Easy Way. The second step is actually uploading the program. The final step is setting the lock bits.


Note: These fusebits will not work on a 3.3V/8MHz board. If you are using a different microcontroller, you will also need adjust the partno parameter.


Pocket AVR Programmer

Fuse Bits

If you are using the AVR Pocket Programmer to program your target Arduino Uno, type the following commands in the command line to set the fuse bits.

avrdude -b 19200 -c usbtiny -p m328p -v -e -U efuse:w:0x05:m -U hfuse:w:0xD6:m -U lfuse:w:0xFF:m

Hex File and Lock Bits

Once the fuse bits are set, we can flash a compiled .hex file to the target board and set the lock bits. Enter the following in a command line. Make sure that you are in same directory as your .hex file and adjust the ...hexfilename.hex that you are using to flash for your target. To flash the Arduino Uno Bootloader, head over to the Arduino program folder. On a Windows OS, it will look similar to this path ...\arduino-1.8.5\hardware\arduino\avr\bootloaders\optiboot. There area few files in the folder but the one we are interested in is the optiboot_atmega328.hex file.

avrdude -b 19200 -c usbtiny -p m328p -v -e -U flash:w:hexfilename.hex -U lock:w:0x0F:m

Arduino as ISP

Fuse Bits

If you are using the Arduino as ISP to program your target Arduino Uno, type the following commands in the command line to set the fuse bits.

avrdude -P comport -b 19200 -c avrisp -p m328p -v -e -U efuse:w:0x05:m -U hfuse:w:0xD6:m -U lfuse:w:0xFF:m

Hex File and Lock Bits

Once the fuse bits are set, we can flash a compiled .hex file to the target board and set the lock bits. Enter the following in a command line. Make sure that you are in same directory as your .hex file and adjust the ...hexfilename.hex that you are using to flash for your target. To flash the Arduino Uno Bootloader, head over to the Arduino program folder. On a Windows OS, it will look similar to this path ...\arduino-1.8.5\hardware\arduino\avr\bootloaders\optiboot. There area few files in the folder but the one we are interested in is the optiboot_atmega328.hex file.

avrdude -P comport -b 19200 -c avrisp -p m328p -v -e -U flash:w:hexfilename.hex -U lock:w:0x0F:m

One last bit of info. As we stated earlier, a bootloader is essintially a .hex file. Thus, you can use this method to upload and code you wish to your ICs.

Resources and Going Further

For more info on AVRs, bootloaders, and flashing firmware to other boards, check out these other great tutorials.

 

创元素-广州美术学院实验艺术系课程电子与机械互动课件公开

course 1 for the first week

course 2 for the first week

course 1 for the second week

course 2 for the second week

course 3 for the second week

继电器基础知识与Arduino控制

继电器(Relay),也称电驿,是一种电子控制器件,它具有控制系统(又称输入回路)和被控制系统(又称输出回路),通常应用于自动控制电路中,它实际上是用较小的电流去控制较大电流的一种“自动开关”。故在电路中起着自动调节、安全保护、转换电路等作用。[来自维基百科]

继电器按输入信号性质分为:电压继电器、电流继电器、时间继电器、温度继电器、速度继电器、压力继电器;按工作原理分为:电磁式继电器、感应式继电器、电动式继电器、电子式继电器、热继电器、光继电器。我们一般使用Arduino控制的是小型直流电磁式继电器。

继电器分类

 

时间继电器:时间继电器用来延迟接触操作,有通电后延迟接触者和断电后延迟断开者(或两者兼有)的型号。

电磁继电器:依据输入线圈的电流性质,分为直流继电器和交流继电器。直流继电器与交流继电器在控制方式上并无区别,但是在铁心结构上有区别。交流继电器,因电流产生交变磁场,在磁感应强度过零时,触点会断开,产生振动与噪音,因此在铁心上增加短路环,延迟铁心磁场变化,可以防止触点振动。

热敏干簧继电器:是一种利用热敏磁性材料检测和控制温度的新型热敏开关。它由感温磁环、恒磁环、干簧管、导热安装片、塑料衬底及其他一些附件组成。热敏干簧继电器不用线圈励磁,而由恒磁环产生的磁力驱动开关动作。恒磁环能否向干簧管提供磁力是由感温磁环的温控特性决定的。

固态继电器(solid state relay,SSR):是利用一颗发光二极管(LED)等发光元件与一颗光晶体管等光接收元件作成之光耦合器,触发硅控整流器(SCR)或双向硅控整流器(TRIAC),因此可以接受低压(DC或AC)信号输入,而驱动高压之输出,具隔离输出入及控制高功率输出之效果。优点是开关速度快、工作频率高、使用寿命长、噪声低和工作可靠,用于防爆场所,也有许多的不利的地方,例如:当闭合的时候,高的电阻(发热),增加电噪音。当断开的时候,低的电阻,反向漏电流(通常 µA 范围)。可使用于取代常规电磁式继电器,广泛用于数位程控装置。固态继电器按负载电源类型可分为交流型和直流型。按开关型式可分为常开型和常闭型。按隔离型式可分为混合型、变压器隔离型和光电隔离型,以光电隔离型为最多。

磁簧继电器:是以线圈产生磁场将磁簧管作动之继电器,为一种线圈传感装置。因此磁簧继电器之特征、小型尺寸、轻量、反应速度快、短跳动时间等特性。当整块铁磁金属或者其它导磁物质与之靠近的时候,发生动作,开通或者闭合电路。由永久磁铁和干簧管组成。永久磁铁、干簧管固定在一个不导磁也不带有磁性的支架上。以永久磁铁的南北极的连线为轴线,这个轴线应该与干簧管的轴线重合或者基本重合。由远及近的调整永久磁铁与干簧管之间的距离,当干簧管刚好发生动作(对于常开的干簧管,变为闭合;对于常闭的干簧管,变为断开)时,将磁铁的位置固定下来。这时,当有整块导磁材料,例如铁板同时靠近磁铁和干簧管时,干簧管会再次发生动作,恢复到没有磁场作用时的状态;当该铁板离开时,干簧管即发生相反方向的动作。 磁簧继电器结构坚固,触点为密封状态,耐用性高,可以作为机械设备的位置限制开关,也可以用以探测铁制门、窗等是否在指定位置。

光继电器:光继电器为AC/DC并用的半导体继电器,指发光器件和受光器件一体化的器件。输入侧和输出侧电气性绝缘,但信号可以通过光信号传输。其特点为寿命为半永久性、微小电流驱动信号、高阻抗绝缘耐压、超小型、光传输、无接点等。主要应用于量测设备、通信设备、保全设备、医疗设备等。

继电器的工作原理:当线圈通电以后,铁芯被磁化产生足够大的电磁力,吸动衔铁并带动簧片,使动触点和静触点闭合或分开,即原来闭合的触点断开、原来断开的触点闭合。当线圈断电后,电磁吸力消失,衔铁返回原来位置,触点又恢复到原来闭合或分开的状态。

继电器工作原理动图

 

继电器工作原理

 

在选用小型直流电磁式继电器时,我们需要注意以下几个问题:

  • 线圈直流电阻;
  • 额定工作电压或额定工作电流;
  • 吸合电压或电流;
  • 释放电压或电流;
  • 触点负载(指继电器触电在切换时能够承受的电压和电流值)

选用继电器时,一般控制电路的电源电压可作为选用的依据。控制电路应能给继电器提供足够的工作电流,否则继电器吸合是不稳定的。考虑上述因素之后,再考虑继电器的体积问题。

一般通过Arduino控制继电器是通过输出高低电平来控制继电器内部衔铁的开闭,从而达到控制大电流高电压电路的目的。

比如有一次做一个项目需要用到24V堵转电流为3A 的大功率减速电机,我原来使用大功率的L298P电机控制模块来对电机进行PWM调速控制,但是由于电机的堵转电流太大,以至于模块出了问题,最终不得不通过继电器来控制电机的通断以及转向。

或许有小伙伴会疑惑要怎么使用继电器来控制转向,我下面来说一下,我的做法是使用两个继电器来构成一个类似于H桥结构的电路,通过控制两个继电器的通断可以使得电机两端分别接电源正极和负极。

PS:有一个需要注意的是,在两个继电器状态变换之前,需要使用delay()函数进行延时50ms左右,否则会造成电源短路!!

使用继电器时,我们可以选择使用单独一个单路或者双路的继电器元件,或者使用现成的继电器模块,某宝上有售。

下图是单独的继电器:

单个双路继电器

下图是常见的继电器模块:

一路继电器模块如果需要控制220V市电则需要使用带有光耦保护的继电器模块(图中是四路的,也可以选购一路或者两路的):

多路带光耦继电器模块

 

如何使用Arduino控制继电器?

在拿到一个继电器的时候,我们可以测试相关的参数:

1,使用数字万用表来测试继电器的引脚:用数字万用表的电阻档,测量常闭触点与动点电阻,其阻值应为0;而常开触点与动点的阻值就为无穷大。由此可以区别出哪个是常闭触点,哪个是常开触点。

2,测量吸合电压和吸合电流:找来可调稳压电源和电流表,给继电器输入一组电压,且在供电回路中串入电流表进行监测。慢慢调高电源电压,听到继电器吸合声时,记下该吸合电压和吸合电流。为求准确,可以试多几次而求平均值。

3,测量释放电压和释放电流:也是像上述那样连接测试,当继电器发生吸合后,再逐渐降低供电电压,当听到继电器再次发生释放声音时,记下此时的电压和电流,亦可尝试多几次而取得平均的释放电压和释放电流。一般情况下,继电器的释放电压约在吸合电压的10~50%,如果释放电压太小(小于1/10的吸合电压),则不能正常使用了,这样会对电路的稳定性造成威胁,工作不可靠。

以下是具体的接线方法:

1,使用单个继电器元件来控制外电路。

继电器连接图

 

具体的代码很简单,就是使用digitalWrite()函数来控制具体数字端口的高低电平来使得继电器通或断。这里就不给出了。

2,使用继电器模块:

relayArduino

 

继电器模块就需要查询相关说明,要看是低电平触发还是高电平触发的继电器模块。就对应的也是使用digitalWrite()函数来控制对应的pin(图中是D10口)的高低电平就可以控制外电路的通断了。具体的代码很简单,这里也不给出。

参考:维基百科

《电子工程师必备:元器件应用宝典》 胡松 胡斌著 人民邮电出版社