# Counting 2ms long pulses on several input pins

• posted

I have a 5 microswitches

connected to some inputs of a microcontroller. The switches are normally closed and put the level to low. When they are open, the level is high thanks to pull-up resistors.

I have to count the pulses generated from the microswitches. They are managed by a rotating cam (en.wikipedia.org/wiki/Cam) that push/release continuously the switches.

The rotation speed could change. When it is slow, the complete pulse width could be up to 15-20ms, where the last part (about 3-5ms) is composed by many bouncing oscillations. When the rotation is fast, the complete pulse width is about 1-2ms and the boucing oscillations takes about 2-3ms.

What is the best approach/algorithm to debounce and detect/count pulses on all the lines, without stressing the microcontroller too much?

My approach is to sample each input lines every 1ms in the ISR of a timr. Usually it is at low level. When I see the first 1, I increase the counter and change to HIGH status. Now I have to see two consecutives 0 to go back to LOW status.

Do you have better ideas?

• posted

Not clear how the pulse rate relates to the pulse width. Does the contact bounce between both poles? If not... Tie one end high, one end low and run the moving contact thru a resistor to a cap on a high-Z input. States will be stable...unless the contact is allowed to bounce between both fixed contacts. Adding some hysteresis will let you make the cap smaller if timing is an issue.

Bottom line is that you're running mechanical switches too fast. Magnets and reeds might have lower mass/higher rates. Or magnets and hall swtiches.

• posted

So, there is a ~10X range of speeds? Are you *sure* you are seeing

1ms pulse "ideal" widths? Can you alter the shapes (dwell) of each cam?

What do you consider "too much"?

Do you care *when* you recognize the switch as closed vs. open? I.e., is the cam "timed" to some critical part of a mechanism so the instant the cam closes corresponds to the mechanism being in a "significant" position/orientation?

For example, if a SINGLE pulse looks like:

+-+ +-+ +---------+ | | | | | | | | | | | |

-----+ +-+ +-+ +---------

A B C D E

Do you care if you "report" the pulse at time:

- A (at the leading edge of the pulse, before any bounces)

- B (some time after the leading edge but possibly in the bounce period)

- C (after the bouncing has stopped)

- D (at the trailing edge of the pulse)

- E (some time after the trailing edge)

[Note I am only illustrating bounce on the leading edge in this description. And, representing this as a *logical* signal which may differ from the voltage levels you "see" on a particular pin]

What are the mechanical "phase" relationships between the cams? E.g., presumably the cams have some *fixed* (?) relationship(s) to each other. So, cam 5 might never be "on" while cam 2 is "on", etc.

Will any of these such cam relationships ever *change*?

• posted

I would hope reasonable processors support edge triggered interrupts on those input pins. You shouldn't have to poll every millisecond or anything like that. You may have to check the status of all the inputs on each such interrupt, in case there are multiple transitions at the same time.

• posted

Quite probably. However it's difficult to be sure because you've been very clear on what you think you _need_ to do but haven't told us anything about what you _want_ to do. There's often a big difference between false perceptions of the former and the reality of the latter. If you explain the problem itself as opposed to the problems imposed by the solution there is probably a better method.

Without that insight we are flying blind to a certain extent, but a few things cross my mind. What kind of speeds are we talking about here? 1ms pulses quite easily takes us into tens of thousands of RPM. Most machine shops will have problems making bearings for that kind of use, yet alone eccentric cams.

Whatever you are doing, microswitches are certainly _not_ the answer since the one thing we do know is that is is MCU interfaced. On a good day you might be able to get away with reed switches but in all probability you are looking at some form of optical detection. That could well end up cheaper and easier than microswitches would have been even if they would have worked.

```--
Andrew Smallshaw
andrews@sdf.lonestar.org```
• posted

Polling at ~1kHz frequency may not be so bad, and gives you automatic debouncing.

Simple method: read all switches (possibly in single read from IO port), and put the state in a bitmap. Compare with bitmap from last time, and every switch that went from 0->1 is considered pushed at that time.

Of course, without know more about the problem, I can't guarantee that this is a suitable solution.

• posted

I'd be leary of tying 5 "noisey" signals to interrupts -- unless there is something that limits the bandwidth of that "noise".

Otherwise, an interrupt based solution can leave you playing games like conditionally *disabling* selective IRQ's for certain periods of time to prevent the processor from being swamped by "nonproductive" IRQ's.

Polling at a high enough frequency AND PASSING THE SAMPLED DATA to a lower priority "task" to do the actual debouncing is probably best if the latency between ISR and "handler" can be tolerated. This keeps the ISR really slick -- read "I/O port", push to circular buffer, return. (yeah, you have to detect buffer overruns but that's trivial)

Hard to say anything for sure without knowing the bandwidth of that "bounce" and the repetition rate of each "cam signal". Nor the consequences of missing a contact closure, whether the edge is really significant (what happens at startup if a switch is closed? do you immediately report it as such? or, do you wait to see it open before you report it as closing, again, etc. recall there is a *mechanism* associated with the switches...)

• posted

Only if there is no bounce! Consider seeing a switch go from 0 to 1 to 0 to 1 to 0 to 1 (thereafter). Is this *one* or *three* switch closures?

Agreed. What the switches signify (to the application) bears a good deal on how they are "interpreted".

• posted

The idea is that the polling routine is slow enough that the bouncing has stopped before the next poll, and that every 0->1 transition should count as a real closure.

Of course, the OP has to determine whether there is a suitable polling frequency that satisfies all the requirements.

• posted

Doesn't matter, as long as they are new bounces, and not bounces associated with previous closure.

The assumptions are that: 1) polling frequency is low enough that bouncing stops within a period. 2) polling frequency is high enough that you don't miss anything of importance.

• posted

Well the bouncing might have started an instant before the next poll...

FWIW, typing "debouncing" into a search engine finds lots of articles about debouncing in software.

• posted

There is insufficient information here to determine:-

1. Is the use of mechanical switches adequate to the task being undertaken.
2. The best de-bounce method (in either hardare or software) that should be employed.
3. Whether polling or edge triggered inturrupts are the best strategy.

So Pozz, a simple test on which you should then report the results here. Mount one of the switches as intended and strap it into a circuit configuration that will resemble the input circuit you are using. Attach a scope across the points where the input would be taken and set the trigger to capture the resultant input. Rotate the cam-shaft over the full range of rates you expect it to operate at and report the results in the form of shoing us the scope traces (on a link) or tabulated as figures relating how long the contacts bounce for at what speed.

Of course, once you have done this you may discover your own answer to your problem. Either ay I think the other responders and myself will be interested in your findings.

```--
********************************************************************
Paul E. Bennett IEng MIET..... ```
• posted

Not enough info on reprtion frequency and max latency for each input amongst many other factors.

Whether even an simple MAX6817 would do all the work and one interupt pin to micro..... up to complex hardware filtering, or simple filtering and software.

Whether counters for each are needed etc. etc...

Most likely all solutions will be h/w and s/w even. minimal h/w pull up resitor and software.

Also any relationship between the switches/cams, as to are we measuring the pulse characteristics for each cam in isolation, or related to other cams.

The cams could for example be paper feed related in a printer and time differences could detect paper jam/empty/page ejected.

```--
Paul Carpenter          | paul@pcserviceselectronics.co.uk
PC Services ```
• posted

This seems like a bug waiting to manifest. A "contact's" dynamic characteristics can vary a lot over the life of a product (esp with very low voltage switching). Or, over operating conditions (do the dynamics of the mechanism change as the cams actuate more often or with shorter dwell times)

Scanning contact closures is NOT where you are going to come up with those HUGE SAVINGS that are going to make/brake your product or implementation. Invest the little extra code and state to do the job reliably and you can reuse the algorithm far more often and reliably than if you try to be "too clever".

WRT "buttons":

Most "people" tend to think "a switch is a switch". E.g., the marketing guy figures you can sell a waterproof version of the EXISTING product just by substituting a few components. So, he comes along and replaces an Hg-wetted, magnetically actuated reed switch with a membrane switch and wonders why things don't work anymore.

Things like button bounce are *very* prominent in the user experience. If the user has to deliberately focus on HOW he presses a button, your product draws unnecessary attention to itself.

We have a clothes dryer (or, maybe its the washer, I can't recall which) that requires you to *hold* the power button engaged. It is noticeable (because the mating appliance doesn't exhibit this behavior). So, instead of just pushing the button and moving on to the next step in configuring the product for use, I have to deliberately pause and

*focus* on "turning the power on".

I have a (cheap) flashlight that has a single button that controls multiple functions (press once for X, twice for Y, three times for Z, etc.). Over time, it has developed significant bounce. So, I have to be very careful and deliberate each time I turn it on/off, etc.

Similarly, I have a "ball cap" with LEDs in the bill (*almost* a toy -- though it does have use in some hands-free uses). It is the penultimate example of a multifunction button (each button press cycles the LED controller through different patterns, etc.)!

But, the manufacturer encased the button in a rubber boot (presumably to make it water-resistant? wear the hat in the rain??). So, it is much harder to press than you would expect. Couple this with the fact that the various light patterns include complex blinking patterns (which are not obvious without *watching* the lights for a second or two to identify which sequence is in play), and the choice of a single button control ("UI") makes the experience (UX) tedious

[E.g., you're never completely sure you have returned the controller to the "full off" condition -- or, if you have just selected a slow blink pattern!]

• posted

A terrible variant of that is my car's remote control.

Click it and if it *changed* to open or locked, the lights flash and you know its state.

But if the lights don't flash you don't know whether - you are too far away - a door wasn't shut properly - it in the desired state

So, unless you see the lights flash, you have to try the other state then re-try the state you want. Argh.

Apart from that, the Mazda 2 has been remarkably reliable, touchwood.

• posted

How would this bug occur ? If the switch stays in 0 for at least one polling period, bounces for less than a period, and stays in 1 for at least one period, my simple algorithm will capture this reliably.

Of course if the switch bounce time exceeds the period of interest you want to capture (say you want to capture 1000 useful events per second, and the switch bounces for 5 ms), no algorithm is going to save you. You'll need a better switch.

• posted

IMO, this makes for a bad user experience. You don't want to have to *think* about trivial little actions like this.

E.g., when we lift our *ringing* cordless phone off the cradle, it automatically answers. But, if the answering machine has already engaged, you must press the TALK button to be connected to the caller.

So, you lift the handset -- and *hope*! "Hello?" Wait a while to see if the other party is there. If not, they are undoubtedly speaking to the answering machine and *you* just spoke to "dead air". Quickly press the talk button and reannounce yourself -- interrupting the caller in the middle of leaving a message, etc.

Of course, it could be *worse*! Imagine if the TALK button served as the "on hook" (hangup) button, as well! You'd

*always* be leary of pressing it for fear you *are* connected to the caller and pressing that button would hang up the phone!

:<

But, this other behavior rises to a level where you are aware enough about it that it persists in your impressions of the vehicle! I'm sure Mazda would rather your comments have been *unconditional* praise (regardless of how "trivial" this other issue might be considered).

My old TV was a delight! *But*, the MUTE function on the remote did not operate independently of the other functions. E.g., if you muted the volume and then changed channels, the mute was canceled. I.e., if you wanted to mute the TV and channel surf without sound (e.g., maybe you or someone else in the room is talking on the phone), you had to drive the volume all the way down to '0' -- where it would persist as you changed channels.

So, in practice, you hit MUTE, changed channels, cursed because the mute was released and instinctively hit MUTE again. Paused as you recalled the "decrease volume" trick. Cursed again because pressing Volume Down automatically un-MUTEs the set (again). Wait for the volume to get down to '0'. *THEN*, start flipping through channels.

Again, the conditional endorsement of the product: "a delight BUT..."

Sort of like climbing Everest and then planting the flag *in* your big toe! Sure, you remember the satisfaction of the accomplishment. But, you also remember (and recount to others!) the hole you poked through your toe at the time! :-/ (which becomes the part of the story that folks MOST remember)

• posted

Hi Arlet,

[Grrrr.... I always want to type "Arlett"! No doubt a c> >

It happens when the switches characteristics -- or conditions under which it operates -- change over time. E.g., "bounces for MORE than a period". Alternatively, "stays in 0 for LESS than one polling period".

Or, the switch is replaced by a mechanism with different characteristics entirely (my "a switch is a switch" comment).

Or, the code is lifted and reused in some other (inappropriate) project.

Chances are, the limitations of your debounce algorithm (along with most other algorithms in your design) aren't spelled out in simple terms in a place where someone wanting to modify the hardware/software/specification can quickly review them for the downside consequences of any proposed changes.

This leads to those annoying pointy-head conversations where you have to tell your boss/client that this "simple" change is going to take a week to implement/test: "Huh? Why can't we just use this different switch?? Why can't we just change the cam dwell to 7 degrees from 10?? etc."

Then, as their frustration mounts, trying to reassure them that there was a *reason* you "crippled" (in their eyes) the algorithm in this way. So, they should, in a perverse sense, be HAPPY that it will take a week! (otherwise, it would imply you were using an inappropriate algorithm).

[I'm sure we've *all* been through those sorts of "discussions"]
• posted

Instead of 'crippled', I'd use the term 'simplified'. It's a 3 line piece of code, driven by a constant timer, with only 1 parameter: the timer interval. It's hard to imagine any modification would require a week.

In fact, a more complicated algorithm is more likely to be misunderstood and messed up later.

• posted

Which is why I set Pozz the task of scoping the input in a real-world testing configuration so that he would see hat bounce factor he might have to deal with. I like simple solutions but only if they will work properly in the situation. As Pozz didn't mention the rate of cam-shaft rotation or the dwell angle of each of his 5 cams, then we are all in the dark as to the real requirements. I am prepared to wait for Pozz's results.

```--
********************************************************************
Paul E. Bennett IEng MIET..... ```

ElectronDepot website is not affiliated with any of the manufacturers or service providers discussed here. All logos and trade names are the property of their respective owners.