9 Replies - 2999 Views - Last Post: 09 October 2012 - 01:15 PM Rate Topic: -----

#1 awinters  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 03-October 12

Detecting voltage change on serial port

Posted 03 October 2012 - 10:17 AM

I need to detect the falling edge of 5 volts going to ground from a USB to Serial.
Is there a way to do this without using some sort of micro board between the laptop and the device?
I see there is PinChanged event, but I don't know how to use it. Which pin is recommended on the serial end? I don't want to send anything back into my device.

Thanks
AW
Is This A Good Question/Topic? 0
  • +

Replies To: Detecting voltage change on serial port

#2 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5524
  • View blog
  • Posts: 11,834
  • Joined: 02-June 10

Re: Detecting voltage change on serial port

Posted 03 October 2012 - 01:01 PM

Serial ports don't measure the exact voltage. SO you won't detect if it is 5v or 12 volts. If that is your need: stop. You need an analog to digital converter and will have to read actual data telling you the voltage.

Otherwise, yes the PinChanged event is what you are looking for.
Its well documented on MSDN.
http://msdn.microsof...pinchanged.aspx

THink of it just like CheckedChange on a checkbox. The event is raised when voltage either appears (leading edge) or drops (trailing edge). Both are a change in condition on that pin. You subscribe to the event just as if it were a checkbox.checkedchanged event.

Different pins have different purposes Pin 6 is DTS for example.

Give it a try. Do some experiments. Read about the serial port and what the pins are. Throw together some code in an attempt to learn. If you need some help once you've given it a go, come back to this thread and update us/me on what you've done and what you've written and what specific issue you're having.
Was This Post Helpful? 0
  • +
  • -

#3 awinters  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 03-October 12

Re: Detecting voltage change on serial port

Posted 03 October 2012 - 01:11 PM

I was hoping you would reply. I saw a post of yours from 2010 (?).
I just don't want to fry my laptop, or the $400k device.
I'm not looking for a precise measure of voltage. The line is pretty solid when its high, but when it drops to ground, it drops NOW.
Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5524
  • View blog
  • Posts: 11,834
  • Joined: 02-June 10

Re: Detecting voltage change on serial port

Posted 03 October 2012 - 01:22 PM

The serial port standard says a serial port should accept up to 24vdc. I've used USB<->Serial adapters with voltages as high as 30vdc over very long lines which became about 12vdc by the time it hit the PC.

I've noticed that the adapters make a nice safty valve for voltage overages: I'd rather fry a $9 external adapter than a true 9pin on the motherboard.

Remember that 'pretty solid' is not 'solid'. If you have a drop of even a millisecond you will get a pin-changed event. Its common to need to code in some 'debounce' or 'noise' filtering. You qualify the change by requiring it to remain changed for at least... 50 milliseconds lets say.

You should fry the device if it is supplying the voltage, since nothing should be going back to it.
Was This Post Helpful? 0
  • +
  • -

#5 awinters  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 03-October 12

Re: Detecting voltage change on serial port

Posted 04 October 2012 - 11:35 AM

The below is my code. The port does open (and close), but no response when I attach / remove a 9v battery to Pin 9.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using System.Timers;

namespace Calculate_Shutter_Delay
{

    public partial class Form1 : Form
    {
        Stopwatch timer_for_shutter_delay = new Stopwatch();
        private SerialPort port; // use private field for SerialPort
        public Form1()
        {
            InitializeComponent();
            port = new SerialPort("COM8", 19200, Parity.None, 8, StopBits.One); // instantiates field
            port.PinChanged += new SerialPinChangedEventHandler(port_PinChanged); // New event trigger for communications
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (label2.Text == "CLOSED")
            {
                serialPort1.Open();
                if (serialPort1.IsOpen)
                {
                    label2.Text = "OPEN";
                    button1.Text = "Close Serial Port";
                    button2.Enabled = true;
                    return;
                }
            }

            if (label2.Text == "OPEN")
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();
                    label2.Text = "CLOSED";
                    button1.Text = "Open Serial Port";
                    button2.Enabled = false;
                    return;
                }
            }
        }

        private void port_PinChanged(object sender, SerialPinChangedEventArgs e)
        {
            string info = string.Empty;
            switch (e.EventType)
            {
                case SerialPinChange.Ring:
                    timer_for_shutter_delay.Stop();
                    info = "Pin 9";
                    break;
                default:
                    timer_for_shutter_delay.Stop();
                    info = "Other Pins";
                    break;
                    }

            this.Invoke(new MethodInvoker(delegate()
            {
                this.label4.Text = info;
                label6.Text =  Convert.ToString(timer_for_shutter_delay.ElapsedMilliseconds);
                timer_for_shutter_delay.Reset();
                Thread.Sleep(5000); // sleep for 5 seconds
                this.label4.Text = "";

            }));
    }

        private void button2_Click(object sender, EventArgs e)
        {
            timer_for_shutter_delay.Start();
        }

    }
}


Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5524
  • View blog
  • Posts: 11,834
  • Joined: 02-June 10

Re: Detecting voltage change on serial port

Posted 04 October 2012 - 01:28 PM

Funny how the one pin you experimented with is one that is kind of out of the ordinary. Ring detect is odd about what it recognizes as a 'ring' - its a hold over from the telephone modem era.

Give it a go with CTS (pin 8) or DTR (pin 6) - These behave more as expected and I use these all the time reliably.

Take special note of tips 2 and 4 below: Your code would benefit.


Some of my common tips (some may apply more than others to your specific style):
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.

  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)

  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like index, timeOut, row, column and so on. You should avoid 'T' for the timer. Amongst other things 'T' is commonly used throughout C# for Type and this will lead to problems. There are naming guidelines you should follow so your code confirms to industry standards. It makes life much easier on everyone around you, including those of us here to help. If you start using the standards from the beginning you don't have to retrain yourself later.
    You might want to look at some of the naming guidelines. Its a lot easier to start with good habits than to break bad habits later and re-learn.



  • Try to avoid having work actually take place in GUI control event handlers. It is better to have the GUI handler call other methods so those methods can be reused and make the code more readable. This is also how you can send parameters rather than use excessive global variables. Get in this habit even if you are using WinForms because WPF works a lot under the idea of "commands" and this will get you working towards that. Think of each gester, control click, menu option etc. as a command to do something such as a command to SAVE. It doesn't matter where the command comes from, all sources should point at the same target to do the actual saving.
    Spoiler


  • Don't replace lines of code that don't work. Instead comment them out and put your new attemps below that. This will keep you from re-trying the same ideas over and over. Also, when you come back to us saying "I've tried this 100 different ways and still can't get it", we can actually see what you tried. So often a failed attempt is very very close and just needs a little nudge in the right direction. So if we can say "See what you did in attempt 3... blah blah" it helps a lot

    Spoiler

    If you are using Visual Studio you can select a block of lines and hit control+k control+c (Kode Comment) to comment it out. control+k control+u (Kode Uncomment) to uncomment a selected block.


Also - you do realize that electricity requires a ground, right?
Just applying voltage to a pin without the ground from the battery going to the ground of the serial port isn't going to work.
Was This Post Helpful? 2
  • +
  • -

#7 awinters  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 03-October 12

Re: Detecting voltage change on serial port

Posted 04 October 2012 - 02:10 PM

I have ground from the battery tied to pin 5.
This does work, however I'm getting a lock-up.
I'm going to remove the thread.sleep and try again.

tlhIn`toq;

It works ! HELLS YEAH !!!
Thank you very much for your time and input.

AW
Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5524
  • View blog
  • Posts: 11,834
  • Joined: 02-June 10

Re: Detecting voltage change on serial port

Posted 04 October 2012 - 02:19 PM

Thread.sleep is evil and should be avoided 99% of the time.
THe entire thread sleeps, that means no events, no gui updates, no windows messaging, NOTHING - so you won't see the transition with the pin changes again.
it is NOT
thread.PauseButContinueToPayAttentionToWindowsMessages();
Was This Post Helpful? 1
  • +
  • -

#9 awinters  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 03-October 12

Re: Detecting voltage change on serial port

Posted 09 October 2012 - 12:51 PM

tlhIn`toq;

I have an interest in controlling 5 volts (on / off) from my USB port. Is using a USB to TTL converter or cable a good way to do this? I would like to be able to control the +5 / -5 in c#.

Thanks
AW
Was This Post Helpful? 0
  • +
  • -

#10 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5524
  • View blog
  • Posts: 11,834
  • Joined: 02-June 10

Re: Detecting voltage change on serial port

Posted 09 October 2012 - 01:15 PM

THere are a lot of project kits out there for this sort of think that would probably be safer on your hardware and give you more control.

I've used a couple that let you have a dozen in and out ports. So you can lots of different feeds in, and lots of feeds out. THis way you can program such that "if input 9 gets a signal, turn on output 4"

The board has its own power supply so you aren't drawing from the limited availability off the motherboard causing the USB bus to close down.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1