Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How do I read data from USB Virtual COM in C#?

How do I read data from USB Virtual COM in C#?

Scheduled Pinned Locked Moved C#
questioncsharpcomhelp
13 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    naouf10
    wrote on last edited by
    #1

    I searched for a solution on the internet but no luck. I am using windows form with Serial Port control and richTextBox. I am trying to read the phone number from caller ID device (CTI comet caller ID) which decodes the Caller's telephone number from the telephone line and presenting it on a virtual COM5 Port of my PC because the Caller ID is a COM device. The caller ID is connected to my PC via USB to COM Adapter because my PC doesn't have physical COM ports. Also the USB to COM Adapter driver is installed well .Note that the telephone line supports the caller ID feature. When the phone rings the phone number should show up in richTextBox, I tried the following code but nothing happens (phone number did not appear) Am I missing something?. My question: How can I read data from virtual COM5 port in C#? Please help me to modify this code to make it work. Thank you

    public partial class Form1 : Form
    {
    public SerialPort mySerialPort = new SerialPort("COM5");

    public Form1()
    {
        InitializeComponent();
    
        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataR);
        mySerialPort.Open();
     }
    
    public void DataR(object sender, SerialDataReceivedEventArgs e)
    
    {
    
        if (richTextBox1.InvokeRequired)
         {
             richTextBox1.Invoke(new SerialDataReceivedEventHandler(DataR), sender, e);
         }
    
         else
         {
    
            richTextBox1.AppendText(mySerialPort.ReadExisting()); //recieve data in real time.
    
          }
      }
    
    
    private void serialPort1\_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
    
    }
    

    }

    OriginalGriffO L L 3 Replies Last reply
    0
    • N naouf10

      I searched for a solution on the internet but no luck. I am using windows form with Serial Port control and richTextBox. I am trying to read the phone number from caller ID device (CTI comet caller ID) which decodes the Caller's telephone number from the telephone line and presenting it on a virtual COM5 Port of my PC because the Caller ID is a COM device. The caller ID is connected to my PC via USB to COM Adapter because my PC doesn't have physical COM ports. Also the USB to COM Adapter driver is installed well .Note that the telephone line supports the caller ID feature. When the phone rings the phone number should show up in richTextBox, I tried the following code but nothing happens (phone number did not appear) Am I missing something?. My question: How can I read data from virtual COM5 port in C#? Please help me to modify this code to make it work. Thank you

      public partial class Form1 : Form
      {
      public SerialPort mySerialPort = new SerialPort("COM5");

      public Form1()
      {
          InitializeComponent();
      
          mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataR);
          mySerialPort.Open();
       }
      
      public void DataR(object sender, SerialDataReceivedEventArgs e)
      
      {
      
          if (richTextBox1.InvokeRequired)
           {
               richTextBox1.Invoke(new SerialDataReceivedEventHandler(DataR), sender, e);
           }
      
           else
           {
      
              richTextBox1.AppendText(mySerialPort.ReadExisting()); //recieve data in real time.
      
            }
        }
      
      
      private void serialPort1\_DataReceived(object sender, SerialDataReceivedEventArgs e)
      {
      
      }
      

      }

      OriginalGriffO Online
      OriginalGriffO Online
      OriginalGriff
      wrote on last edited by
      #2

      Start by making sure that you can communicate with the device at all, by using Hyperterminal or similar. Until you have established that you have the right port, speed, pbc, parity, stop bits, and that any flow control is working fine, you are just guessing with "home brewed" code. So when it doesn't work, it could quite literally be anything causing it.

      Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      N 1 Reply Last reply
      0
      • N naouf10

        I searched for a solution on the internet but no luck. I am using windows form with Serial Port control and richTextBox. I am trying to read the phone number from caller ID device (CTI comet caller ID) which decodes the Caller's telephone number from the telephone line and presenting it on a virtual COM5 Port of my PC because the Caller ID is a COM device. The caller ID is connected to my PC via USB to COM Adapter because my PC doesn't have physical COM ports. Also the USB to COM Adapter driver is installed well .Note that the telephone line supports the caller ID feature. When the phone rings the phone number should show up in richTextBox, I tried the following code but nothing happens (phone number did not appear) Am I missing something?. My question: How can I read data from virtual COM5 port in C#? Please help me to modify this code to make it work. Thank you

        public partial class Form1 : Form
        {
        public SerialPort mySerialPort = new SerialPort("COM5");

        public Form1()
        {
            InitializeComponent();
        
            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataR);
            mySerialPort.Open();
         }
        
        public void DataR(object sender, SerialDataReceivedEventArgs e)
        
        {
        
            if (richTextBox1.InvokeRequired)
             {
                 richTextBox1.Invoke(new SerialDataReceivedEventHandler(DataR), sender, e);
             }
        
             else
             {
        
                richTextBox1.AppendText(mySerialPort.ReadExisting()); //recieve data in real time.
        
              }
          }
        
        
        private void serialPort1\_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
        
        }
        

        }

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #3

        How do you know that you're not receiving data and that the "display" part is the problem? Read your port into a string and check the contents before trying to display something that may or may not be there. (That's why you don't chain methods so early on in development).

        N 1 Reply Last reply
        0
        • L Lost User

          How do you know that you're not receiving data and that the "display" part is the problem? Read your port into a string and check the contents before trying to display something that may or may not be there. (That's why you don't chain methods so early on in development).

          N Offline
          N Offline
          naouf10
          wrote on last edited by
          #4

          @

          Gerry Schmitz

          . I tried to read the port into a string but the string still empty, I debugged the program and I noticed that the DataReceived event did not got fired. Does it mean the port did not receive any data ? plseae help

          OriginalGriffO L 2 Replies Last reply
          0
          • OriginalGriffO OriginalGriff

            Start by making sure that you can communicate with the device at all, by using Hyperterminal or similar. Until you have established that you have the right port, speed, pbc, parity, stop bits, and that any flow control is working fine, you are just guessing with "home brewed" code. So when it doesn't work, it could quite literally be anything causing it.

            Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

            N Offline
            N Offline
            naouf10
            wrote on last edited by
            #5

            @ OriginalGriff . I will try your idea and see what happens, I will let you know . thank you

            1 Reply Last reply
            0
            • N naouf10

              @

              Gerry Schmitz

              . I tried to read the port into a string but the string still empty, I debugged the program and I noticed that the DataReceived event did not got fired. Does it mean the port did not receive any data ? plseae help

              OriginalGriffO Online
              OriginalGriffO Online
              OriginalGriff
              wrote on last edited by
              #6

              naouf10 wrote:

              Does it mean the port did not receive any data ?

              Yes... Exactly that...

              Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

              N 1 Reply Last reply
              0
              • N naouf10

                @

                Gerry Schmitz

                . I tried to read the port into a string but the string still empty, I debugged the program and I noticed that the DataReceived event did not got fired. Does it mean the port did not receive any data ? plseae help

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #7

                I've "heard" the DataReceived event doesn't always work (so I avoid it). You first need to confirm that your SerialPort (class) settings match what's in Control Panel AND match what the device expects. Also insure your "timeout" settings are high enough. When you believe there is data on the serial port, you can do a .BytesToRead() call on the serial port to see if there is data waiting. You should "sleep" some amount of time before trying. If you never have any "bytes to read" > 0, then you're still not configured / hooked-up properly. (You should build a dialog (button) so that you can read / query the port on demand for testing. You cannot restart a program and serial port and expect data to persist).

                N 1 Reply Last reply
                0
                • OriginalGriffO OriginalGriff

                  naouf10 wrote:

                  Does it mean the port did not receive any data ?

                  Yes... Exactly that...

                  Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

                  N Offline
                  N Offline
                  naouf10
                  wrote on last edited by
                  #8

                  @ OriginalGriff. I tested the caller Id in different PC (PC2) which has EPOS and this EPOS could display the phone number so it means the port receives data when phone rings therefor I tested my C# code in PC2 and still my app didn't receive data from COM port although EPOS can read data from same port. any idea?

                  1 Reply Last reply
                  0
                  • L Lost User

                    I've "heard" the DataReceived event doesn't always work (so I avoid it). You first need to confirm that your SerialPort (class) settings match what's in Control Panel AND match what the device expects. Also insure your "timeout" settings are high enough. When you believe there is data on the serial port, you can do a .BytesToRead() call on the serial port to see if there is data waiting. You should "sleep" some amount of time before trying. If you never have any "bytes to read" > 0, then you're still not configured / hooked-up properly. (You should build a dialog (button) so that you can read / query the port on demand for testing. You cannot restart a program and serial port and expect data to persist).

                    N Offline
                    N Offline
                    naouf10
                    wrote on last edited by
                    #9

                    @ Gerry Schmitz . Thank you for your good information. yes both the SerialPort (class) and the Caller ID have the same settings. maybe your ideas will work but I have to modify my code first. Can you please tell me how to do the following in my code: -

                    .BytesToRead() call

                    - how to sleep before trying? - how to insure my "timeout" settings are high enough. I don't have TimeOut in my code. Please help me so I can modify my code. Thank you

                    L 1 Reply Last reply
                    0
                    • N naouf10

                      @ Gerry Schmitz . Thank you for your good information. yes both the SerialPort (class) and the Caller ID have the same settings. maybe your ideas will work but I have to modify my code first. Can you please tell me how to do the following in my code: -

                      .BytesToRead() call

                      - how to sleep before trying? - how to insure my "timeout" settings are high enough. I don't have TimeOut in my code. Please help me so I can modify my code. Thank you

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #10
                              int bytesToRead = 0;
                      
                              for ( int i = 0; i < 5; i++ ) {
                                 bytesToRead = \_serialPort.BytesToRead;
                      
                                 if ( bytesToRead > 0 ) {
                                    break;
                                 }
                      
                                 Thread.Sleep( 50 );
                      
                      
                              }  // end for.
                      

                      Setting timeouts is trial-and-error; you just need to insure they are "long enough". I've been in situations where the timeouts needed varying from 250ms up to 5000ms; depending on the environment (i.e. network). Another thing: Serial devices don't typically just "send"; they respond to requests. i.e. You send data to the device; it responds ... even if it is just with an error. If there is no "command" that you can send to the device and for which you can expect a response (like "current status"), then you are missing something (like RTFM).

                      1 Reply Last reply
                      0
                      • N naouf10

                        I searched for a solution on the internet but no luck. I am using windows form with Serial Port control and richTextBox. I am trying to read the phone number from caller ID device (CTI comet caller ID) which decodes the Caller's telephone number from the telephone line and presenting it on a virtual COM5 Port of my PC because the Caller ID is a COM device. The caller ID is connected to my PC via USB to COM Adapter because my PC doesn't have physical COM ports. Also the USB to COM Adapter driver is installed well .Note that the telephone line supports the caller ID feature. When the phone rings the phone number should show up in richTextBox, I tried the following code but nothing happens (phone number did not appear) Am I missing something?. My question: How can I read data from virtual COM5 port in C#? Please help me to modify this code to make it work. Thank you

                        public partial class Form1 : Form
                        {
                        public SerialPort mySerialPort = new SerialPort("COM5");

                        public Form1()
                        {
                            InitializeComponent();
                        
                            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataR);
                            mySerialPort.Open();
                         }
                        
                        public void DataR(object sender, SerialDataReceivedEventArgs e)
                        
                        {
                        
                            if (richTextBox1.InvokeRequired)
                             {
                                 richTextBox1.Invoke(new SerialDataReceivedEventHandler(DataR), sender, e);
                             }
                        
                             else
                             {
                        
                                richTextBox1.AppendText(mySerialPort.ReadExisting()); //recieve data in real time.
                        
                              }
                          }
                        
                        
                        private void serialPort1\_DataReceived(object sender, SerialDataReceivedEventArgs e)
                        {
                        
                        }
                        

                        }

                        L Offline
                        L Offline
                        Luc Pattyn
                        wrote on last edited by
                        #11

                        Hi, serial input on a Windows PC (or on any device for that matter) tends to be tricky, here are some pointers: 1. The code you have shown does NOT read any data, your DataReceived handler is empty. 2. I/O operations occur in "real time", making it hard to observe them correctly; typical debug operations (single-stepping and the like) don't work, the world doesn't stop when you stop typing the keyboard. My solution to this is: use logging. A simple Console.WriteLine() or a File.WriteLine() could do, prefixing a time stamp always proves useful. I tend to also log to a listbox, with auto-scroll, and obviously with the appropriate Invoke stuff built-in so it works from any thread that happens to call it. And no, you don't need a logging package for this, all the logging infrastructure requires is about 10 lines of code. 3. Advice on all software development: don't build your entire app, then test and watch it fail. Develop one basic operation at a time, get it to work properly, then proceed. Hence, do not touch WinForms Controls before you must. 4. Tricky bits part 1: AFAIK there is no decent description as to when an I/O event is called; for DataReceived it does not mean: "when my data is in" (the computer does not know what you consider "your data"), and we can only hope and observe it does not mean for each and every byte. What typically happens is the operating system collects incoming bytes, and signals an input operation when it has a reasonable amount of data (say 5 bytes), which probably is half a message in your application domain, so you get an event for half a message; and then the remaining bytes possibly aren't enough to cause a second signal, so you don't get them at all. (Exception is when you read a text string and tell the driver what constitutes an end-of-message, by default that could be a CARRIAGE RETURN, a LINEFEED or both). Conclusion: you most often are better off not using those events, as they often do not connect well to your application. Yes they work, but not the way you would dream they work. 5. Advice on I/O: for simple things (and also when starting complex things), first use operations you perform explicitly AND synchronously (i.e. actual Read, ReadLine and the like, without events), avoid asynchronous stuff (such as the DataReceived operation). 6. Tricky bits part 2: how does one synchronize the external device and the code that reads data? the start of transmission is no good, reading a message often makes sense only when the entire message is available. I see

                        N A 2 Replies Last reply
                        0
                        • L Luc Pattyn

                          Hi, serial input on a Windows PC (or on any device for that matter) tends to be tricky, here are some pointers: 1. The code you have shown does NOT read any data, your DataReceived handler is empty. 2. I/O operations occur in "real time", making it hard to observe them correctly; typical debug operations (single-stepping and the like) don't work, the world doesn't stop when you stop typing the keyboard. My solution to this is: use logging. A simple Console.WriteLine() or a File.WriteLine() could do, prefixing a time stamp always proves useful. I tend to also log to a listbox, with auto-scroll, and obviously with the appropriate Invoke stuff built-in so it works from any thread that happens to call it. And no, you don't need a logging package for this, all the logging infrastructure requires is about 10 lines of code. 3. Advice on all software development: don't build your entire app, then test and watch it fail. Develop one basic operation at a time, get it to work properly, then proceed. Hence, do not touch WinForms Controls before you must. 4. Tricky bits part 1: AFAIK there is no decent description as to when an I/O event is called; for DataReceived it does not mean: "when my data is in" (the computer does not know what you consider "your data"), and we can only hope and observe it does not mean for each and every byte. What typically happens is the operating system collects incoming bytes, and signals an input operation when it has a reasonable amount of data (say 5 bytes), which probably is half a message in your application domain, so you get an event for half a message; and then the remaining bytes possibly aren't enough to cause a second signal, so you don't get them at all. (Exception is when you read a text string and tell the driver what constitutes an end-of-message, by default that could be a CARRIAGE RETURN, a LINEFEED or both). Conclusion: you most often are better off not using those events, as they often do not connect well to your application. Yes they work, but not the way you would dream they work. 5. Advice on I/O: for simple things (and also when starting complex things), first use operations you perform explicitly AND synchronously (i.e. actual Read, ReadLine and the like, without events), avoid asynchronous stuff (such as the DataReceived operation). 6. Tricky bits part 2: how does one synchronize the external device and the code that reads data? the start of transmission is no good, reading a message often makes sense only when the entire message is available. I see

                          N Offline
                          N Offline
                          naouf10
                          wrote on last edited by
                          #12

                          Thank you alot, I will consider what you have said.

                          1 Reply Last reply
                          0
                          • L Luc Pattyn

                            Hi, serial input on a Windows PC (or on any device for that matter) tends to be tricky, here are some pointers: 1. The code you have shown does NOT read any data, your DataReceived handler is empty. 2. I/O operations occur in "real time", making it hard to observe them correctly; typical debug operations (single-stepping and the like) don't work, the world doesn't stop when you stop typing the keyboard. My solution to this is: use logging. A simple Console.WriteLine() or a File.WriteLine() could do, prefixing a time stamp always proves useful. I tend to also log to a listbox, with auto-scroll, and obviously with the appropriate Invoke stuff built-in so it works from any thread that happens to call it. And no, you don't need a logging package for this, all the logging infrastructure requires is about 10 lines of code. 3. Advice on all software development: don't build your entire app, then test and watch it fail. Develop one basic operation at a time, get it to work properly, then proceed. Hence, do not touch WinForms Controls before you must. 4. Tricky bits part 1: AFAIK there is no decent description as to when an I/O event is called; for DataReceived it does not mean: "when my data is in" (the computer does not know what you consider "your data"), and we can only hope and observe it does not mean for each and every byte. What typically happens is the operating system collects incoming bytes, and signals an input operation when it has a reasonable amount of data (say 5 bytes), which probably is half a message in your application domain, so you get an event for half a message; and then the remaining bytes possibly aren't enough to cause a second signal, so you don't get them at all. (Exception is when you read a text string and tell the driver what constitutes an end-of-message, by default that could be a CARRIAGE RETURN, a LINEFEED or both). Conclusion: you most often are better off not using those events, as they often do not connect well to your application. Yes they work, but not the way you would dream they work. 5. Advice on I/O: for simple things (and also when starting complex things), first use operations you perform explicitly AND synchronously (i.e. actual Read, ReadLine and the like, without events), avoid asynchronous stuff (such as the DataReceived operation). 6. Tricky bits part 2: how does one synchronize the external device and the code that reads data? the start of transmission is no good, reading a message often makes sense only when the entire message is available. I see

                            A Offline
                            A Offline
                            Agent__007
                            wrote on last edited by
                            #13

                            Excellent post! :thumbsup:

                            You have just been Sharapova'd.

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups