Solved

Accessing Serial Port (C#)

Posted on 2009-05-14
16
1,332 Views
Last Modified: 2013-12-17
I am just beginning tinkering with serial ports and I have run across a strange problem. In the very beginning of my project I attempt to simply open the serial port, so I can begin listening to it. Here is the code:

 private SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);

        private void Form1_Load(object sender, EventArgs e)
        {
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            port.Open();
        }

This throws an excpetion on the "port.Open()" line that says:

The given port name does not start with COM/com or does not resolve to a valid serial port.
Parameter name: portName

I am running Windows Vista 32bit, and I have one hardware comport which is set to COM1. I have verified this through the device manager as well as through the following code:

foreach (string port in SerialPort.GetPortNames())
{
     MessageBox.Show(port);
}

This method spits back only one string, and thats "COM1" without the quotes. I have also deleted all of my printers to ensure they were not causing an issue, but I still get the above exception. Anyone have any ideas what is causing this?
0
Comment
Question by:Pretzel_Jesus
  • 7
  • 6
  • 2
  • +1
16 Comments
 
LVL 9

Expert Comment

by:Gorkem Yuksel
ID: 24387854
Have you tried to use COM1: (add the semi-colon at the end)

Cheers,

G.
0
 
LVL 10

Expert Comment

by:smegghead
ID: 24390605
Are you sure there isn't a space before the COM1, or maybe you've got C0M1 (i.e. with a 0).

You shouldn't need the colon at the end. You could always try it in lower case, but I'm 99% sure that shouldn't make a difference.

Can you open the com port from the command window ?? i.e. just typing..
>mode com1
or
>copy con: com1:

and just see if the port is actually accessible.
0
 
LVL 10

Expert Comment

by:smegghead
ID: 24390634
Actually.. try putting the port=new serialport(... etc) on the line inside the form_load event. Just to ensure that it's not being changed elsewhere.. or if you can 'break' execution, look at the content of the 'port' variable.
0
 

Author Comment

by:Pretzel_Jesus
ID: 24390775
Actually it turns out deleting my printers wasnt enough. I needed to reboot my computer which was suprising. At any rate what would the trick be to monitor data coming out of a serial port to a printer? For instance if I put a generic text only printer on COM1 how can I monitor data being sent through com1?
0
 
LVL 10

Expert Comment

by:smegghead
ID: 24390950
I don't think that you can do this from c#, but you can get software which does this http://www.virtualserialport.com/products/serialmonitor/

0
 

Author Comment

by:Pretzel_Jesus
ID: 24390964
I have seen other software that does this as well. They physically monitor a hardware com port and sniff all plain text data leaving the port (going to a printer). However the apps I know of are written in C++. You sure there is no way to do this in C#?
0
 
LVL 10

Expert Comment

by:smegghead
ID: 24391028
no, I'm not 100% sure, but I can't see an obvious way of doing this.. there isn't an option to open the port with shared access or anything.

You might be able to do this with windows APIs, but it's probably a lot of work.
0
 
LVL 1

Expert Comment

by:VegasCid
ID: 24400435
Hi,

Here you have a real code working in real envioroment.

I hope this help you

Best Regards
using System.IO.Ports;

...        

//private SerialPort portCOM = new          SerialPort("COM1",9600,Parity.None,8,StopBits.Two);

        private SerialPort portCOM = new SerialPort("COM1", 9600);

        

        string car2;

        int car;
 

        public Form1()

        {

            InitializeComponent();

        }
 

        private void Form1_Load(object sender, EventArgs e)

        {         

            txtInfo.AppendText(portCOM.IsOpen.ToString());

        }
 
 

private void btnOpen_Click(object sender, EventArgs e)

        {

            if (!portCOM.IsOpen)

            {

                portCOM.Open();

                txtInfo.Text = "Conexion open\n";

                

                portCOM.DiscardInBuffer(); // when open clean buffer

            } //if

        }
 

        private void btnClose_Click(object sender, EventArgs e)

        {

            if (portCOM.IsOpen)

            {

                portCOM.Close();

                txtInfo.Text = "Conexion closed\n";

            } //if

        }
 

        private void btnWriteandRead_Click(object sender, EventArgs e)

        {

            if (portCOM.IsOpen)

            {

                portCOM.Write("1");

                //Read response

car = portCOM.ReadChar();

                show(car);

            } //if

        }
 

private void btnReadAny_Click(object sender, EventArgs e)

        {

            if (portCOM.IsOpen)

            {

                car2 = portCOM.ReadExisting();

                txtInfo.Text = car2;

            } //if

        }
 

private void show(int car)

        {

//Transform ascii to real number

            car = car - 48;
 

            switch (car)

            {

                case 0:

                    txtInfo.Text = "0";

                    break;

                case 1:

                    txtInfo.Text = "Marcha atras velocidad 1";

                    break;

                case 2:

                    txtInfo.Text = "Marcha atras velocidad 2";

                    break;

                case 3:

                    txtInfo.Text = "Marcha atras velocidad 3";

                    break;

                case 4:

                    txtInfo.Text = "Marcha delante velocidad 1";

                    break;

                case 5:

                    txtInfo.Text = "Marcha delante velocidad 2";

                    break;

                case 6:

                    txtInfo.Text = "Marcha delante velocidad 3";

                    break;

                case 7:

                    txtInfo.Text = "PARADO";

                    break;

                default:

                    txtInfo.Text = car.ToString();

                    break;

            } //switch

        }

Open in new window

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Expert Comment

by:VegasCid
ID: 24400504
I forget this:

Try to access first to the serial port with hyperterminal.

Microsoft have removed this app in Vista but you can use to know the correct conexion options with any app showed in this blog entry or use Windows XP

http://msmvps.com/blogs/richardwu/archive/2007/06/15/hyperterminal-for-vista.aspx
0
 

Author Comment

by:Pretzel_Jesus
ID: 24528374
It turns out the exception is thrown because the com port is in use. I need to sniff data coming over the com port when a generic / text only printer exists on it. Is there any way to monitor the port while another device resides on it?
0
 
LVL 10

Expert Comment

by:smegghead
ID: 24528454
I think that as I suggested above, you have to either use 3rd party software to do this, or spend days trying to do this wth windows API.
0
 

Author Comment

by:Pretzel_Jesus
ID: 24528464
I need to develop my own software for this particular instance. So I need to get this working in the fashion I detailed above.
0
 
LVL 10

Expert Comment

by:smegghead
ID: 24542301
I don't necessarily object, but the original question, which I spent time answering, was just relating to opeing a serial port, there was no mention of monitoring the communication of the port.

Can the points just be reduced and awarded, otherwise the input from the 'experts' seems pointless.

More was added to the question after it was asked, then stated that 'there was no workable solution'. But the initial question WAS answered.

Anyway, I don't really care, it makes no difference to me, but it might put other people off helping you in the future if you delete questions.
0
 

Author Comment

by:Pretzel_Jesus
ID: 24542319
If its possible to award partial points I will not object. I dont want this appearing as a solution for others to search through however, as no working solution was provided.
0
 
LVL 10

Accepted Solution

by:
smegghead earned 500 total points
ID: 24542386
Solutions were provided to your initial question.

And links were provided to your subsequent questions about monitoring.
I don't mind you deleting this question, but if your reasons for wanting to delete is so that other people don't waste their time reading this question, there is actually some valid input from the experts which suggest various things to try. It turned out that one of your printers had the port locked..
but this was nothing to do with 'port monitoring'.

0
 

Author Closing Comment

by:Pretzel_Jesus
ID: 31581573
I will just award the points and be done with it. I solved my own problem to the initial question (port was in use).
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now