Rocky Masthead Image

Contact Sensors and where to use them

Probably the simplest sensors of all to use are the so-called "force" or contact sensors.

These sensors work by detecting movement against one or more mechanical elements (such as a switch lever or button), and that is used to close electrical contacts, which then inform the processor that the sensor has been activated.

Contact sensors can be used in some robots as the primary means of detecting a collision with something and routing power to different motors to effect a change of direction. However, more complex robots typically use contact sensors as a failsafe - if other sensors are unable to detect an obstacle, the contact sensor can usually be relied on to detect it.

The simplest contact sensors are single-axis pushbuttons. While they're available in a wide range of types, they tend to be fairly difficult to mount and use. While they generally have a good contact area, their range of movement is quite limited, and the amount of force needed to actuate them reliably varies enormously from switch to switch. Good quality switches can also be extremely expensive!

Many robot builders start out using these types of pushbuttons, but quickly realise their limitations and general unreliability. But there are much more useable alternatives!

The most common contact sensor type used in robotics uses a mechanical lever to move a spring-loaded copper paddle between two contact points. These types of sensors are called "microswitches" (or "snap action switches") because they're generally very quick to change over, and they're very small. However, there's small and then there's really small - some microswitches are less than a few millimetres on a side, smaller than a child's fingernail - what you might call a "micro microswitch"! But even the smallest microswitch is able to be mounted fairly easily on a robot's exterior.

Standard Microswitch Roller Microswitch Lever Microswitch Whisker Microswitch Kit
Some typical microswitches, shown approximately actual size.

Mechanical switches, by their nature, are 2-state devices. That is, they stay in one position (or "state") until something happens to them, then they fairly quickly switch to another state. Once the robot is moved away from whatever activated the switch, they reset themselves automatically, ready for another "bump". This is why they're also called "bump" sensors.

Microswitches are available in 2- or 3-terminal varieties. The 2-terminal switch is either normally open (NO), and activation closes the connection, or they're normally closed (NC) and activation breaks the connection between the terminals. 3-terminal switches have a common (COM) terminal, and one NO and NC terminal. Activation of the switch results in the contact changing over, so the NC terminal is opened, and the NO terminal is connected to the COM.

You can use a 3-terminal switch in place of a 2-terminal (assuming the size and mounting is the same), but if all 3 terminals are wired to a circuit, obviously a 2-terminal switch won't work instead.

Switches Ain't Perfect!

Most people (myself included at one time) assume that these 'digital' switches just work the way you expect, and there's nothing special needed to get them working right away. However, wiring contact switches still needs some care, whether you're using the switch as an input to a microprocessor or using it as a power switch inline with your motor(s).

There are two issues that most people aren't aware of that can affect the reliability of switchess. These are :

  1. Electrical noise or interference, and
  2. Contact bounce.

Both of these problems can be avoided altogether, or at least minimised, by  some attention to wiring and to how, exactly, you connect the switch.

The RIGHT way to wire up a switch.

You'd think that, with such a simple mechanical contact to work with, you can just grab some wire, solder 'em to your switch, and connect it, right? Unfortunately, it's not always that simple!

Even for the simplest robot, there are a couple of rules you need to know about that will give you perfect results when using microswitches, every time.

The No. 1 rule is : keep your wiring as short as possible! This will drastically reduce the amount of unwanted electrical noise in your circuit. Even if you're just wiring your switch directly to your motor, short wires will lose less power and give you more reliability. In the case where you're wiring to your motors, use the heaviest wiring you can manage to solder reliably. Your batteries will last longer, and your robot will work better, than using long strands of thin 'hookup wire'. Plus, it's much easier to keep neat, and that means it's easier to fix if anything should go wrong.

And that bring us to rule No. 2 : keep your wiring as neat as possible! For sure, while you're breadboarding and thrashing your prototype, it doesn't matter too much about neatness - after all, what's one more little wire? But as your design gets more sophisticated, you'll find that neat wiring will repay your efforts many times over when it comes to troubleshooting or repairs - and it will, sooner or later! (That should probably be the third rule - you will always end up repairing or rewiring your robot, sooner or later...)

If, like most robot designers, you're using a processor of some kind, the thickness of the wiring isn't critical at all, but you should still try to keep the wiring as short and simple in layout as possible.

If your wires need to go some distance from your switch to your board connection, make sure you don't run the wiring too close to any power leads or other high-current connections (like motor leads, for example). If it's at all possible, try to run your signal/switch wires across the line of your power and motor leads. Electricians do this every day, and for exactly the same reasons. So it won't hurt to be a little bit thoughtful when it comes to laying out your wiring loom (a wiring "loom" is what you call all the 'spaghetti' wiring when it's neatened up). If it helps avoid some problems, that's better than fixing it later on, right?

What about "contact bounce"? Is it likely to affect my robot?

That's an excellent question, and I'm going to spend a bit of time on this one. It's the most common area for trouble out of all the sensors and their possible problems, and most people just get it wrong. Then they wonder why their robot doesn't stop jerking when a switch is activated, or why switch presses seem to be ignored by the processor, and so on. It's actually pretty simple to fix, and there are a few ways of going about it. Let's look at why this is.

Most contact switches are spring-loaded to some degree. This makes them much more reliable to operate, so that once the switch starts to move, it completes the move, rather than 'getting stuck' halfway!

The problem here is actually invisible to us. All mechanical switches seem to operate as digital devices - we press a light switch, for example, and the light comes on. It doesn't flicker into life (well, it might if it's a fluorescent light, but not an incandescent bulb), it just switches on. At least, it seems to just turn on in one go to our eyes and brains.

But in fact, every switch ever made tends to "bounce" a little as the contact inside is 'made' (connected) and 'broken'. That's why it's called "contact bounce", and that's why we're talking about this here. You and I can't see this, and it varies from switch to switch, but they all do it, and while we can't see it, a computer chip sure can!

The "bouncing" can happen once, twice, or up to twenty or thirty times. Each 'bounce' can last from less than a millionth of a second, to over a tenth of a second, and every value in between. Some switches are designed to be less susceptible to bounce, while the cheaper the switch, the more likely it is to bounce. That's just the way things are, unfortunately.

Can I make things worse?

The easiest way for you to make the problem worse is to use cheap switches to begin with. Now, no manufacturer likes to talk about contact bounce, it's just too icky, so it has to come down to manufacturer reliability and cost.

Now, we're not talking about a huge difference in cost, here. I've bought microswitches off the internet that cost me exactly $0.87 each (that's 87 cents). These microswitches were made in China. (Please don't think I'm "China bashing" here, this is just an example from the real world, OK?) Now, I also bought the same variety of microswitch (same size, same mounting holes, same operating pressure, same contact life, as identical as I could find them) from a famous US switch manufacturer, and they cost me $1.72 each. (For four switches, that's not a huge price difference. I guess if you were buying 100,000 switches, it might be different, but not to your typical robot maker. After all, where would you mount 100,000 microswitches? The 'bot would look like a porcupine!)

The point is, I actually measured both sets of switches, for 200 operations each, under the same identical conditions - same connecting wires, same place on the bench, everything. I used a digital oscilloscope (CRO) to sample the outputs of the switches.

The contact bounce I actually measured on the C&K switches occurred less often than on the cheap switches, and it didn't last for as many bounces, on average, as the cheaper switches (6 bounces average, vs. 13 bounces average). I couldn't tell the difference in terms of how long each bounce was, it just looked random in the spreadsheet. For such a small sample, I can't draw too many conclusions, but the results were repeatable.

Not only that, but the more expensive switches were much, much better to use - the operating pressure was more constant, the switchover occurred with a much more solid action (a nice, solid 'tick' each time), and even the little levers wiggled around less as I tried to operate them by hand. (I could even tell this although I'd marked the identical switches only on one side so I could only tell afterward who made it). In fact, 2 of the cheaper switch levers actually fell out during the test. That's NOT what you want happening on your robot!

The long and short of it is - buy good quality switches and components. They may be more expensive to begin with, but you'll save yourself time and effort in the long run. Even if your robot won't be operated by NASA, you'd like it to last more than one or two bumps!

How NOT to wire up a switch to a microprocessor

Now that you're aware of what contact bounce is, and you understand that it's important to keep your wiring short and neat, here's the reason for all that talk...

A microprocessor can react to very short signals on its inputs. At the same time, those signals have to meet certain conditions in order to be "accepted" by the input circuitry.

NOTE: The inputs must be within the processor's voltage range! One sure way of killing a CPU is to wire your switch up to 12 volts, then connect that right to your 5V (or 3.3V) microprocessor and turn the power on. POOF! You let the magic smoke out and the CPU is a silicon drink coaster!

OK, so you've wired your switch to the same supply as your CPU, you've kept your wires short and neat, now what?

The most reliable way of using a switch is to have it "open" by default, and then when it's actuated, it closes the connection. Typically, you connect the N.O. (normally open) connection to a "pullup" resistor, which is connected to your power line, and you connect the COM (common) connection to ground or 0 volts. Something like this :

Simplest switch circuit connection

Now, most modern microprocessors have pullups available internally, so this seems to be a very simple way of connecting a bump sensor or other switch. But now that we know what we know about bounce and noise, you can guess that this type of connection will result in really unstable operation. The switch will work just fine - but with the bouncing and noise, the processor is going to see all sorts of activity each time the switch is pressed - so you won't get the behaviour you expect.

You should note that this kind of switch is just fine if you switch it on or off while the power's off - the processor will then be able to read a very stable high or low voltage at any time. This type of connection is often used for configuration switches. This allows you to tell the processor to act differently depending on what voltage level it sees during the startup phase. DIP switches are very commonly used for this purpose, as they pack 4 or 8 tiny little switches in a very small space, and they're easy to wire up with one resistor each!

Let's add a capacitor!

Since the problem is the voltage "jumping" up and down when the switch is opened or closed, a capacitor is often used to 'fix' this problem.

A capacitor stores charge - so each time the contact bounces, the capacitor charges up (or discharges) a little bit more, leading to a much smoother 'ramp' of voltage change. Here's a typical 'debounce' circuit using a capacitor :

A slightly more complicated debounce circuit

There's nothing wrong with this, right? (You know what the answer's going to be, don't you?)

There is still a problem with this circuit, although it doesn't show up on all processors. The problem is that while the capacitor is ramping up or down, the voltage slowly (from a microprocessor's point of view!) goes from a low voltage level, to an "undefined" level, and then up into the high voltage level - or vice-versa. While the voltage is in "no man's land" somewhere between high and low, the processor is likely to make up it's own values - and because the capacitor has slowed things down a bit, the voltage stays in the DMZ range for longer, so the processor may think it has dozens (or hundreds!) of switch changes, and then you get truly bizarre behaviour!

When you use any device - a remote control, for example - and you notice that sometimes the "UP" button actually changes the channel or volume DOWN (and vice-versa), then you know you've got a slowly changing input causing havoc. Many published electronic circuits suffer from these sorts of problems, especially where cost or complexity or size is an issue.

So how can we fix this?

Well, remember I said earlier that the problem doesn't show up on all processors? That's because many microprocessors have a particular input mode on their digital inputs called a "Schmitt Trigger". A Schmitt Trigger uses hysteresis to "speed up" slowly rising signals. So while the input of a schmitt trigger can be a very slowly rising voltage, the output is always one clean high-to-low or low-to-high transition!

OK, then how can we get this effect if our CPU doesn't have schmitt trigger (also just called ST) inputs? Simple - we add a ST buffer or inverter between the capacitor and the CPU. Like this :

The simplest guaranteed debouncer circuit

The funny little symbol inside the inverter symbol (the triangle representing IC1) means that it has ST input circuitry. So now, with just 3 simple components, we have a safe, reliable, clean debounced switch input. Of course, using an inverter means that when the switch is closed, instead of the CPU seeing a "Low" voltage signal, it will see a High signal, and vice-versa, but that's dead simple to fix in code.

And you can always use an ST buffer instead of an inverter - that will produce the same voltage level on the output as it sees on the input. But ST buffers can be quite difficult to obtain these days. Since many were designed by using 2 inverters in series, it's cheaper for manufacturers to put just one inverter per pin rather than doubling up. It saves them money. And makes our jobs harder, but that's not important to them.

OK. Surely that's it for debouncers? Well, no. For ultra-reliable debouncing, where you have to take into account the lifetime of the switch, you don't want the switch just shorting out the capacitor. The capacitor can store quite a lot of energy - which can burn and scorch the switch contacts very quickly indeed! So if you want your switches to last as long as possible, you can use the following circuit to completely eliminate contact burn and capacitor stress. Here's the circuit :

The bulletproof, long-life debounce circuit.

The first thing you'll notice is there's a diode in the circuit. That helps the capacitor to charge up quickly when the switch is opened after being closed.

The second thing you'll notice is R2. This resistor prevents the capacitor from dumping its charge into the switch contacts and burning or pitting them. The two extra components won't significantly affect the timing of the circuit when it's in use, so you don't have to recalculate all your values.

How big should the capacitor and resistor be?

That's an excellent question. Typically, most switches bounce for a maximum of 5-20 mS (milliseconds, or 5-20 thousandths of a second). So you want your resistor/capacitor combination to keep charging for at least that long, but for no longer than 100 milliseconds.

If you take too long to charge the capacitor, or to discharge it, then short switch changes won't have time to trigger the CPU.

100mS (one-tenth of a second) would be the longest you'd need for a switch that could be actuated and then released quickly (say, by a reed switch operated by a magnet connected to a driveshaft). However, a contact or bump sensor would probably stay operated for up to a second or more, so the values wouldn't need to be so critical. In fact, you can use the values in the schematics above as a starting point!

Because of the different needs, you may have to experiment a bit. There is a magic formula that will help you, and it's really simple.

You need to control the time taken to charge the capacitor, or to discharge it. Well, there is a formula for resistor/capacitor circuits (also called RC circuits) that calculates that very thing. The formula is :

Tc = C * R

Where Tc is in seconds, C is in farads, and R is in ohms. So, for example, let's take a 10µF (microfarad, one millionth of a Farad) capacitor, and let's say we want to debounce for 10mS, a very typical time for most switches. We can rearrange the formula very easily to give us the resistance we need :

R = Tc/C

Now, 10µF is 10 millionths of a farad, which is 10 x 10-6 F, which is 1 x 10-5 F, which is written as 0.000001, and our time is 10 milliseconds, or 10/1000ths of a second, which is written as 0.010. So, putting in these values, we have :

R = Tc/C

  =  0.01 / 0.000001

 =  10000, or 10,000 ohms, or 10k

Don't worry, you'll get used to dealing with all those zeroes... eventually.

So for our 10mS delay, using our 10µF capacitor, all we need for R1 and R2 is 10k. Simple, huh? You can plug any values in to that equation, and get exactly the value you want. Just remember to convert your capacitance to farads, your time to seconds, and your resistance to ohms, and you're laughing.

By the way, if you need to calculate your capacitance, the formula becomes :

C = Tc/R

So there you have it - the full guff on what contact bounce is, why it's important, and what you can do about it.

Solid-state Debouncing

Both Maxim and Motorola make excellent solid-state debouncing ICs. These offer excellent overvoltage protection, up to 25V for the Maxim parts, and ESD protection so you can't zap 'em to death either.

Unfortunately, the Motorola MC14490 (also available through On Semiconductor) is quite expensive, at around $10 a pop! The Maxim MAX6816 (single switch), MAX6817 (dual switch), and MAX6818 (8-switch) debouncers are around a tenth the price, and the octal debouncer is slightly less than half the price of the Motorola chip!

Now let's get back to discussing the switches and how you can best use them in your design!

How can I best use microswitches?

Probably the first thing you'll need to do in order to make practical use of contact switches is to increase their 'range'. It's pretty trivial to attach wires or plastic parts (LEGO parts work really well here!) to the actuation lever of most microswitches. This increases the distance that a contact can be sensed at, and is the single easiest way to improve the protection for your robot.

There are a couple of gotchas with this method, however, which I'd like to discuss here. I had to learn the hard way, so hopefully you don't need to!

Levers, Levers everywhere!

First, the principle of levers can catch you out sometimes, especially with longer switch contact extensions or "feelers". The problem is that as the lever gets longer, it has to move further in order to actuate the change-over switch mechanism. For really long (more than about 10cm) feelers, a typical microswitch needs the end of the feeler to move as much as 5cm (about 2 inches) or more before the switch will operate! And the longer the feeler is, the further it needs to move to get the switch to operate. Who would've thought?

One way to avoid this is to use a small stub to "pre-press" (also called "preconditioning") the switch, so only a very small feeler movement is needed to complete the switching action. Unfortunately, this tends to stress the spring metal mechanism inside the switch, leading after some time to extremely unreliable operation!

Another option is to arrange a set of smaller levers to operate the switch mechanism. Unfortunately, this can sometimes be difficult to put into practice, as you'll start to have to deal with very small levers and precise positioning. Unless you design this very carefully indeed, you'll find that overcoming friction (especially if you use plastic or wooden parts) is your biggest problem, and may lead to unreliable operation.

The Plane! The Plane!

The second gotcha is a bit more subtle, so it can catch you unawares. I know it took me a while to figure it out!

The microswitch (and most other mechanical switching devices, like rockers and even pushbuttons) works best in one plane. In other words, the movement of the switch will only happen if the contact force moves the switch lever in the direction it was designed to move. Normally, you'd mount microswitches horizontally, so that the lever will press 'in' as a wall or other object is contacted. But what if the object isn't perfectly vertical? Or worse, what if it isn't perfectly flat?

What happens then is that trigonometry takes over. This means that if the point of contact doesn't move in the same plane as the switch mechanism, only a percentage of the contact force will be used to operate the switch. In the extreme case, where a switch is mounted horizontally on either side of the front and rear of the robot, a sloping contact (for example, the edge of a wheelchair ramp, or a stair bannister riser, or even a chair leg) will force the feeler out of the horizontal entirely. That means that the feeler is "feeling" the obstacle just fine, but it's not able to move the switch lever to tell the robot that something's there!

You might think I'm just making this up, but you'd be surprised at just how good most robots are at not running into things "properly"!

The easy solution to this type of problem is to use a "wrap-around" horizontal bar or bumper to operate your switch. That way, no matter what direction or angle the obstacle is at, it will eventually be forced to press against the switch lever horizontally.

However, one newer option is to use a digital joystick (generally available for a few dollars each) and mount it horizontally (so the "joystick" part is parallel to the floor and directly in front or behind the robot). If you then attach your feeler to the centre of the joystick, like a long "handle", you'll be able to detect movement in any of 3 axes! Unfortunately, joystick switches tend to have very small movement extremes, so you do have to be careful with your selection of your whisker or feeler.

Too sensitive to move?

The last issue with feelers and contact switches also has a lot to do with their size.

Obviously, the longer the feeler, the sooner you can detect an object in contact with the feeler. But there comes a point where longer feelers start to work against the robot's maneuverability.

If you consider a small robot entering a small space (say, a closet or dead-end corridor or hallway), then if the robot's feelers are too long, the robot may not be able to get out of the small space! This is because each time it moves, one or more feelers will be activated, at the front or back.

This leads to an endless loop of backwards,forwards,backwards,forwards movements as the robot attempts to move away from the contact point. In this case, every movement will result in a contact, which means the poor robot just flattens its batteries trying to move out!

As you can see in this diagram, the robot's sensors give it quite
a long sensing distance - but they're too long to allow it to turn around without either getting stuck (which is bad!) or without repeatedly being triggered by the walls as it backs and turns.
In this diagram, the robot's sensors are a more reasonable size, so it's able to easily back up and execute a U-turn without any problems.

Not all robot designs suffer from this problem, of course. Round or octagonal robots generally don't have many problems of this type. In addition, round bodies are able to navigate through smaller spaces than square robots - even if they're the exact same dimensions!

This also has much to do with the steering method chosen for the robot. Rotational steering (also called omnidirectional steering) won't avoid this problem on a rectangular robot, but it will make maneuvering in tight spaces easier than, say, a robot with car-type (or "Ackerman") steering.

As a side note, you'll notice how many of the design decisions in other areas of the robot's design can impact in more than one way - for example, body shape on steering and so on.

Variable contact sensors

Newer contact sensors are coming to market all the time. Most recently, variable resistance contact sensors are starting to appear. These are generally very cheap and easy to use. Their output changes in proportion to the force applied to them - a light force results in a small change in resistance (or capacitance, for capacitance touch sensors), while a large force results in a large change in value.

With both types of contact sensor, a relatively large force is required to activate them. Compared with some cleverer alternatives (see below for "Cat's Whisker" sensors), the force may be large enough for the robot to damage whatever it is that's pressing against the sensor. If this is a brick wall, it may damage the robot! If it's mum's favourite vase, it may damage you...

So the obvious choice is either to use a long contact sensor to give your robot as much time as possible to react. Unfortunately, as we've seen, this approach can make your robot sensitive and difficult to use in small spaces like corridors and hallways. So you do need to find a good compromise between being able to stop your robot before hitting something, and having your robot work in as many environments as possible.

This naturally leads us on to other sensor technologies - such as ultrasonics, IR (Infrared), and magnetics. Use the links at the left to investigate these alternatives.

A Lighter Touch

One alternative to using direct mechanical sensors such as switches and contact pads is to amplify the effects of the contact and use the amplified signal itself. This sounds complicated (and it is slightly more complex than switches), but it's not as hard to do as you might think. Let's look into it now.

One approach to consider is to use the so-called piezoelectric effect to sense a point of contact. Put simply, you attach a fairly stiff wire or plastic shaft (something flexible but not too flimsy) to a common piezoelectric transducer, such as the little piezo beeper-type devices. You don't have to break one of those to get the piezo material - these days, most robotics stores stock some kind of simple and cheap "bare" piezo elements for exactly this sort of thing. You can even buy ready-to-use kits with all the bits soldered on and ready to go.

A typical piezoelectric vibration sensor

A typical piezoelectric vibration sensor, ready to be plugged in!

This approach works because when a piezoelectric material is vibrated, even very slightly it generates electrical signals. (The opposite effect - vibrating the crystal by applying voltage to it - is how these devices work as speakers!) Depending on how 'violent' the vibration is, a small piezo transducer can easily generate over a hundred volts! Of course, this is at incredibly tiny (micro-amp or pico-amp) current levels, so it won't kill you - but you can feel it if you're (un)lucky enough!

By attaching a long, slender rod or wire to the piezo element, you're using the lever principle to both extend the range of the robot's sensors, and also minimises the flexing of the piezo disc or pad, which will also make it last longer. The rod or wire doesn't have to move much at all - the lightest tap against a wall (or even a fabric like a curtain) will generate enough piezo electrical signal to easily be amplified and sent to the robot's processor.

Of course, this approach won't work with simple relay/motor/switch type robots, as the signals generated are very small in comparison to what's needed to switch a relay or turn a motor. The signals also don't generally last very long. But there's no reason the amplified signal couldn't be used to turn on a simple transistor, which turns on a relay, which drives the wheels directly. So this is a pretty flexible (pardon the pun) method of detecting touch contact with the world. And it's far less likely to result in your robot gouging a hole in the hallway!

So there you have it. Hard and soft contact sensors can be your first or last line of defense for your robot, and with some ingenuity, you can make your robot as sensitive as you like!

N.B. Please check out the Hardware Suppliers' page, and look for Sparkfun and Robot Shop links. Both these online suppliers have some great microswitch and piezo sensors available. For the more technical minded, be aware that all the big US stores (Mouser, Digikey, etc) stock literally thousands of types of these devices, generally at much lower prices than the hobbyist stores. However, you do need to know what you're doing when ordering from them, as they generally have a minimum order value for shipping, and some parts can't be returned, even if they're unused.

At this build revision (1.7.7), Rocky uses four horizontal bumper switches, with integrated circuit debouncing via a Maxim 6816 device per switch input.

Eventually, these contact bumpers will be upgraded to Cat's Whisker (piezoelectric contact) sensing, real estate permitting.