How to detect an electrical switch closing ?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: How to detect an electrical switch closing ?

  1. #1
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    3,762

    How to detect an electrical switch closing ?

    Hi,

    I'm working on a a program for monitoring a conveyor belt. At random intervals an electrical switch will be tripped (closed) and reopened a short while later.
    This switch is hardwired into the conveyor belt and I have no control over it. It's just a dumb type electrical switch that's either closed (current can pass through) or open (no current can pass). The switch is just there, there's nothing hooked up to it (yet). It closes when something is on the conveyor belt under a camera.

    I need to detect the closing of the switch and then take a picture of what's on the conveyor belt via a the camera (no problem, I have that sorted). The picture is stored and then analysed in a background thread (got that sorted also).
    The data will typically come in bursts of several "clicks" over a few seconds followed by seconds/minutes/hours of no action.
    Pictures are analysed in background since there may not be enough time to fully process them between "clicks" as they happen (typically an image takes between 2 to 15 seconds to process).


    The problem I have now... I somehow need to hook up this on/off switch to the pc, and write code to detect the switch presses.

    I'm not that into hardware, but from old memory (well ancient actually, talking DOS era here). I seem to remember that you could just attach a switch between two pins of the RS232 and read out the com port status somehow to detect the open/closed state of the switch.

    Anyone know if this is indeed possible... and how ? which pins on the RS232 do I need, what would I need to write in code to do this (the program runs in Windows)?
    Ideal would be that tripping the switch would result in a message/interrupt/or other "wake up" type thing to happen in the program, although if need be continuous polling is possible as well (but less ideal because of used CPU time, and the possibility of not detecting a down/up of the switch if it happens fast enough).

    Alternate solutions are welcome too. It doesn't have to be RS232. Printerport, Ethernet, USB... I can even solder some wires on the motherboard if really really necessary. Just looking for something easy/cheap that will work.

    I can't change the actual switch, it's built into the conveyor belt and can't be substitured for another type switch.

  2. #2
    Join Date
    Nov 2006
    Posts
    1,611

    Re: How to detect an electrical switch closing ?

    I tried to answer this post 4 times today, but kept getting stopped by one mishap or another, though nothing technical.

    The serial port DTR signal is probably of use to you. It's "Data Terminal Ready", and is used to tell if the device (presumed most often to be a 'dumb terminal' or serial printer, perhaps external modem) is on (or online).

    This is pin 20 of the large format RS232 - I THINK it's pin 9 of the 9 pin connector, but google for the pinout to be sure.

    If memory serves (and this goes back 15 years), DSR is pin 6. It was common to short pin 6 to 20 so the DTR signal was turned on, for devices that didn't really warrant a return status of that kind, and to reduce the number of wires needed. This would be your route - simply wire your switch between these two - and they're commonly used in lengths of 50 ft or so.

    This won't give you a means to respond to an interrupt (or message) - unless I've forgotten something about it, and that's certainly possible. A message from the serial port (or interrupt) comes when data is available.

    You could also consider using a keyboard as a controller. Let's say the PC has USB and a PS2 port. If you can find an old keyboard, perhaps with busted keys but that otherwise works - you could use a keyboard of the 'opposite' interface as your spare for user control (that is, the keyboard the user uses to control the computer), while using the spare keyboard's parts as a switch sensor. What you would do is take the tiny PC board inside the keyboard out, along with it's cord. You would note the membrane or other connection which normally feeds keystrokes to the controller - observe where that membrane connects to the control board, and use a voltmeter to find the supply power (probably 5 volts, but I'm guessing). This is a low current supply so it won't drive long wires. Now, the keyboard is a matrix that crosses one or more other lines - with experiment you could learn how to complete a connection to 'mimic' the keypress of particular keys. I've done this before, long, long ago - and each board is different, so it's just a minor trial and error. There's no voltage or current to be worried about (though use standard precautions for poking around electronics).

    When you find a suitable combination that works to provide a keystroke for a generally unused key (say F12), you can wire that for actuation from your switch.

    Note, however, that mechanical switches are noisy devices. Typically a piece of metal slides over another to complete contact, and this generates an unstable level of resistance over time - if you 'listened' to it, it would sound like a noisy volume control on a cheap radio.

    This means that it may provide 'bounce' using this approach. The bounce would mean you'd receive dozens or hundreds of keystroke messages in a very short time, which software would simply resolve into a single event - say over a boundary of 1 second, or the average duration of a contact event on the switch.

    What you'll want to consider, however, is that this isn't likely to 'enjoy' a long wire. That would invite noise from radio interference to potentially become part of a sensing problem (false switch firing as a result of some radio transmission nearby). You may solve this with a simple solid state relay - supply your switch with, say, 5 volts (or whatever the relay requires) - so that when the switch is activated, it triggers the relay at some distance. The relay would be very close to the keyboard control board. The "other side" of the relay would act as a key contact on THAT circuit, and the keyboard controller would only "see" a short wire.

    You could also use a mouse - an old one - and wire your switch in place of one of it's buttons, along the same lines as the keyboard substitution.

    This approach gives you a message in Windows - a trivial programming problem that doesn't require polling.

    Those are cheap - of you want better, let me know.
    Last edited by JVene; April 30th, 2009 at 08:24 PM.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

  3. #3
    Join Date
    Jan 2002
    Location
    Houston, TX
    Posts
    1,421

    Re: How to detect an electrical switch closing ?

    Actually, I think you mean the DSR (Data Set Ready) signal.

    DTR indicates that the terminal is ready, but in this case your PC with your software running IS the terminal, and the external device will be the Data Set.

    Connecting DSR and DTR allowed the terminal to act as if the data set was always ready since the DTR (output) was then connected to the DSR (input).

    Good luck.
    Be sure to rate those who help!
    -------------------------------------------------------------
    Karl - WK5M
    PP-ASEL-IA (N43CS)
    PGP Key: 0xDB02E193
    PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193

  4. #4
    Join Date
    Nov 2006
    Posts
    1,611

    Re: How to detect an electrical switch closing ?

    but in this case your PC with your software running IS the terminal
    This was always a source of confusion, since the PC can be used as either depending on the software it's using. From a hardware perspective this switch scenario isn't going to provide data, but neither is the PC.

    One of the ways we used to determine what was DCE vs DTE (whether the device is a terminal supplying data or a communications device consuming data) was which pin is the transmit, pin 2 or 3, or which was supplying the terminal ready voltage. In this case, the PC is supplying itself through a switch, and I don't think that's really covered by the standard - still, we're talking about the same pins - If pin 20 is 'sensing' and pin 6 is 'supplying', and the software is checking the DTR status, that's the software's view of things. If DTR is supplying and DSR is 'sensing', then the software will be looking at DSR. I seem to recall that on the PC, and in the software that looks at this, DTR is 'sensed' and DSR is 'set' - indicating DSR is supplying the voltage....this would be important from the software's viewpoint, but I don't think this switch is concerned with which way electricity is flowing, though certainly the software will have to account for which signal is the 'sense' - and I'm reaching back 15 years and not looking up a reference (I'm on a laptop with a slow / flaky wifi right now).

    I forgot to point out, too, that in order to reduce switch noise it may be side to place a 0.1 uf capacitor between the signal and ground, and to use shielded low capacity cable.
    Last edited by JVene; May 1st, 2009 at 09:42 AM.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

  5. #5
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    3,762

    Re: How to detect an electrical switch closing ?

    I can't use mouse of keyboard since both will be in normal operation at the time. Someone is at the pc using normal programs while the conveyor belt monitoring program runs in the background.

    The switch is at about 2meters from the PC.


    assuming the DTR/DSR type scenario... How would one test for a depressed switch in windows (XP/Vista) ?

  6. #6
    John E is offline Elite Member Power Poster
    Join Date
    Apr 2001
    Location
    Manchester, England
    Posts
    4,235

    Re: How to detect an electrical switch closing ?

    I must admit, modifying the keyboard would have been my preferred option but then, I'm quite handy with a soldering iron! However, if that's impossible try this company. They seem to sell a range of ready made devices to interface switches to a PC.
    "A problem well stated is a problem half solved. - Charles F. Kettering

  7. #7
    Join Date
    Nov 2006
    Posts
    1,611

    Re: How to detect an electrical switch closing ?

    John E has a good point, but......

    You can use a keyboard and still use the PC.

    That was my point about using both a PS/2 and a USB keyboard. Windows will allow both keyboards to provide input at the same time (typical on laptops, for example) - I've done that on my desktop many times.

    The trick would be to choose a key for the switch that isn't a normal part of your application's use.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

  8. #8
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    3,762

    Re: How to detect an electrical switch closing ?

    Mkay, just got back from a meeting with the prospective customer(s) and the other people on the dev team...

    Looks like RS232 is out of the question as the controller PC's don't have an RS232 port. It kinda didn't occur to me that new PC's these days no longer have one of these anymore...

    So... Looking for alternatives...

    Keyboard is out as well because that would mean no clicks are being sent to the controller app while the user is not logged in. Or when the security desktop (login/gina/UAC) is active.
    For the same reasons mouse is not feasible either.

    Ideally something that can be waited on with WaitForSingleObject(), although I'll settle for a polling system as well if need be.


    Note that I do need to be able to read/poll for "whatever" even if the controller app does not have focus or the security desktop is active. (this is looking a LOT more complicated than I'd anticipated).

  9. #9
    Join Date
    Nov 2006
    Posts
    1,611

    Re: How to detect an electrical switch closing ?

    I had no idea this was for a client, or I wouldn't have gone THAT cheap and rigged.

    Ok, how cheap is cheap?

    I have two ideas. Midi or audio.

    I've done both. This depends a little on your comfort with simple electronics.

    A few years ago I contracted for an artist on an "installation". This required that I be able to sense the approach of a person to a lighted column. The closer they got, the brighter the column had to be. The details are beyond the scope of this post, but basically what I did was to create a circuit that produced a tone from an oscillator, where each column had it's own frequency. The audio in sampled these frequencies and used DFT to figure out the amplitude of each signal. You could do something similar but much simpler.

    There are circuits you can google for simple oscillators. You can make one out of a 555 timer, or a "Twin T" tuned circuit with a few caps, resistors and a cheap operational amplifier (Like the TL08x available at Radio Shack, if they still have their parts department). TL07x is fine, too - this isn't critical, any audio op-amp will do. Simply get it to generate an audio tone around 1Khz (500 to 3000 hz would do). Connect it's output through that switch. With the switch open, no audio. Switch closed, audio comes through. Have the audio line in sample that, and respond to the tone's presence. You could simply average amplitude, or you could check the incoming signal with a DFT algorithm for a particular frequency and respond at some arbitrary amplitude of that frequency (this latter would filter out noise digitally).

    It also occurred to me that you COULD send audio out of the output jack, then route that through the switch, and sample the input for the signal (so you don't have to make an oscillator).

    Audio sampling has a slight delay, and a small constant drain on CPU resources, but on anything this side of a 700Mhz, it's nominal. You might turn off sampling while you process images.

    It's also good form to consider an input buffer op-amp at the audio card, just so you're not exposing the PC to a long incoming audio cable. Shielded cable is a good idea here. Parts are probably under $20 (not counting cable). You'll need power - there are ways to power op-amps from single polarity power supplies (like from the PC), but most circuits are drawn out for bi-polar supplies.

    The only "gotcha" here is the reliability of mini-audio plugs. Especially in less climate controller locations, (like warehouses for example?) the contacts tend to get dirty over time, turning signal into static. This is why DFT is better than simple audio amplitude. Failure would mean "no longer taking pictures" instead of "always taking pictures".

    This can be mitigated somewhat, depending on your access to the PC's internals. You could choose a gold plated contact, or you could solder in a 'jumper' to a more reliable audio connector, like an XLR 3 PIN.

    It's important to note, too, that you're target is NOT the microphone input - that's very sensitive. What you want is the "line" input - usually 1V p-p. It's much less sensitive to noise from poor contact, but not immune. Actually, nothing is immune to contact noise, you simply can overcome it with robust physical connections and lower sensitivity ( otherwise known has higher voltages - something in the 2 to 5 volt range ). You do NOT supply 2 to 5 volts to an audio in - in fact, you don't supply DC. Therefore, you want to pass the output THROUGH a capacitor (something between 1uf and 10uf) in order to stop any DC getting in (even from offset due to power supply configuration of the op-amp). Don't let me scare you, this is 'bright high school kid' level electronics (at least, I had learned this stuff long before I left high school, and I know a few that did, too). You don't find that many studying audio/linear electronics these days, but in my day we built our own mixers, power amps and stacks of speaker cabinets for parties.


    Another idea is midi. Midi is commonly associated with musical instruments, but it's applicable to all kinds of control/sense situations. There's an array of midi sensor devices, most based on sensing switches. There are midi interface 'boxes' for USB if the PC doesn't have a joystick/midi input. This approach is probably going to cost upwards of $50, because even a midi cable is around $25. There are also lots of midi circuits on the web, including a device called "Midi-Man" which is sold to people making "installation art" or stage work, where they must either sense input TO midi, or provide output to control something that needs a control voltage to operate. If you found a busted, small, cheap midi keyboard ( I happen to have one that's smaller than a PC keyboard, looks like a toy ) - you'd have 95% of what you need. The keys are switches on the cheap ones (something more complex on better keyboards which sense pressure).

    In this approach, your application would monitor midi input (much less duty that audio monitoring above). There's a demo midi monitor in most of the Visual Studio versions that show how this is done.

    Oh, back on the second keyboard idea - I'm only 50/50 on this point, but I think you CAN deploy an OS hook on the keyboard and catch any keystroke no matter what has focus - check into that, too.
    Last edited by JVene; May 4th, 2009 at 04:50 PM.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

  10. #10
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    3,762

    Re: How to detect an electrical switch closing ?

    Quote Originally Posted by JVene View Post
    I had no idea this was for a client, or I wouldn't have gone THAT cheap and rigged.
    Mkay... I must have missed the big hype in between the iphone, youtube and twitter and people are installing some time of conveyor belt with controller apps in their kitchen now

    Quote Originally Posted by JVene View Post
    Ok, how cheap is cheap?
    As cheap as possible. Although "simple" is maybe more the key word here.
    The issue is that these are laptops that get plugged into a docking station at the counter when the operator is opening the counter (and taken out when they're leaving). When they leave the conveyor belt stops as well so no new clicks will be arriving. A laptop can't be undocked when it still has images to be processed in the queue (the docking station has a software controlled locking mechanism to prevent that).

    Any solution means that I also need to be able to disconnect the switch. But there's enough ways to do that even if "ugly" or "klunky". a 2.5mm mono jack male/female woule be possible, although not really the most elegant.



    I have two ideas. audio.
    I actually already explored that option. But it doesn't work because of the delay in sampling/buffering the data. Unless I'm missing something crucial about reading sound data. Any data you're samplng can arrive up to half a second later than it actually happened. In that amount of time the conveyor belt will have moved too far.

    The specs require handling of up to 10 clicks per second with a delay of 70ms between clicks as minimum. And the signal to the camera to take a picture needs to be sent no more than 10ms after the actual click has happened.

    if I use the keyboard or mouse as simulation. I'm well within the specs. With sound I couldn't get it to work.


    Another idea is midi.
    Hmm forgot about that one... Worth exploring

    I'm pretty sure the laptops don't come with midi. And I can't really rely on finding enough busted midi keyboards 50$ for a midi connection+25$ for cable could be proibitive though... Will see what I can find on the local hardware shops.

  11. #11
    Join Date
    Nov 2006
    Posts
    1,611

    Re: How to detect an electrical switch closing ?

    Mkay... I must have missed the big hype in between the iphone, youtube and twitter and people are installing some time of conveyor belt with controller apps in their kitchen now
    Cute....I thought you might be an in-house tech, where the owner/boss was fine with 'rigged' solutions. Approaching a client as a consultant brings any proposition into a slightly higher domain, I would think - but under $50 is quite cheap, so rigged may have to do.

    The tightest audio delay can be arranged by shortening the sample, but I don't think you could get anything in those ranges.

    A Midi USB dongle is the 'cleanest' solution, but probably more expensive than your target.

    Most laptops have some kind of parallel port, which might also be used, but it's tricky. That port is a very old design, and polling it has a tendency to affect the OS (ever used a parallel port connected scanner?) by momentary hanging - plus, at your speed intervals, I don't think even serial port polling would be a great idea. It could work, I know, but the polling speed would approach enough drain - any OS service, like Anti-Virus, that momentarily hogs a single CPU might cause a 'skip' in service.

    Midi has a small delay, too - related to it's sample rate. It's like a 31.5 kbps interface, meaning you get around 3K bytes per second or so. Probably very much in your timing range.


    Back to cheap, though - I think you should read MSDN (through google perhaps) on SetWindowsHookEx, specifically with WH_KEYBOARD_LL (low level keyboard hook). This could re-interest you in the USB keyboard option. A cheap, broken USB keyboard should be within reach, quite possibly for free. The hook allows you to intercept and filter for a particular keystroke not commonly used on the keyboard without regard for what application has focus. I would have to experiment to verify the hook is active in all situations you describe. You could package the hook as a service which posts a message to your app (or any number of mechanisms), making the hardware solution cheap and simple.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

  12. #12
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    3,762

    Re: How to detect an electrical switch closing ?

    Quote Originally Posted by JVene View Post
    Cute....I thought you might be an in-house tech, where the owner/boss was fine with 'rigged' solutions. Approaching a client as a consultant brings any proposition into a slightly higher domain, I would think - but under $50 is quite cheap, so rigged may have to do.
    Hmm... right you are. didn't consider that.


    A Midi USB dongle is the 'cleanest' solution, but probably more expensive than your target.
    I can find USB midi "stuff" from as low as 12 Euro's to as much as 150 Euro. I'm not entirely sure what those 12 Euro thingies actually do are are capable off. I will need to talk to some techies about what they're about. Looks like I know what to do tomorrow...

    Most laptops have some kind of parallel port
    Apparently. Some smart people at laptops-r-us and even desktops-r-us decided that they'd stop doing that also and just assume everyone uses network printers or printers with USB.
    Looks you're as much out of the times as I am


    Back to cheap, though - I think you should read MSDN (through google perhaps) on SetWindowsHookEx, specifically with WH_KEYBOARD_LL (low level keyboard hook).
    Yep. know all about that. Been using windows hooks for keyboard, mouse, messages, ... both global and thread local for years. Problem with the keyboard and mouse ones (even the _LL ones) is that smart people (honestly) at Microsoft decided it would be a bad idea if you could log keys typed at the login and UAC screens.

    Other than that... it'd mean trying to find a button that they would never be pressing themselves, and the customer has made it clear they use ALL buttons on the keyboard.

  13. #13
    Join Date
    Nov 2006
    Posts
    1,611

    Re: How to detect an electrical switch closing ?

    I was about to suggest X10, but most of those interfaced to a serial port.

    If you had bluetooth developer's parts, you might manage a 'bluetooth remote control' of some kind, assuming the laptops had bluetooth.

    It's starting to look more like midi as I think about it.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

  14. #14
    John E is offline Elite Member Power Poster
    Join Date
    Apr 2001
    Location
    Manchester, England
    Posts
    4,235

    Re: How to detect an electrical switch closing ?

    Did you take a look at the company that I suggested? They sell several interfaces for taking up to a dozen switch inputs and delivering the output to USB. If you could find a suitable USB router to go with it, you should be most of way there. In fact, this seems to be something they specialise in, so they might be able to find you something, even if it isn't part of their standard range.
    "A problem well stated is a problem half solved. - Charles F. Kettering

  15. #15
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    3,762

    Resolved Re: How to detect an electrical switch closing ?

    Issue solved

    Talking to a "genious" in electronics, he pointed me to the following www.arduino.cc.

    A small bit of electronics which while overkill for what I was asking for (controlling the input of a button), actually turns out to be ideal for this project as we can now manage multiple inputs and even control multiple outputs, so we can ALSO without much added costs (just the cables) do stuff like turning the belt off and on, turning the camera on and off. And other interesting stuff.

    We also struck a deal with a semi-local shop selling these to make us special versions of the arduino with only the connectors we need. Bringing the cost per unit down to about 15Euro ex vat for 50 of these.


    In short... If you need any type of interface TO or FROM external non-PC aware electronics. Check this out, it may be the perfect solution for your problem too.

    The arduino is a small "computer" of it's own and can do some impressive stuff while not even connected to a pc, but you can use it as a generic type interface to electronics as well. Slightly overkill. but at 15Euro per unit... you can hardly call the cost much of an issue
    Last edited by OReubens; May 7th, 2009 at 02:36 PM.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center