Accessing Serial Port (C#)

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?
Pretzel_JesusAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
smeggheadConnect With a Mentor Commented:
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
 
Gorkem YukselCommented:
Have you tried to use COM1: (add the semi-colon at the end)

Cheers,

G.
0
 
smeggheadCommented:
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
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
smeggheadCommented:
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
 
Pretzel_JesusAuthor Commented:
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
 
smeggheadCommented:
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
 
Pretzel_JesusAuthor Commented:
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
 
smeggheadCommented:
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
 
VegasCidCommented:
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
 
VegasCidCommented:
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
 
Pretzel_JesusAuthor Commented:
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
 
smeggheadCommented:
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
 
Pretzel_JesusAuthor Commented:
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
 
smeggheadCommented:
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
 
Pretzel_JesusAuthor Commented:
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
 
Pretzel_JesusAuthor Commented:
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
All Courses

From novice to tech pro — start learning today.