3

Writing a single byte to the serial port in .NET 4.0 in C# causes a

InvalidOperationException was unhandled by user code

Every time a byte is sent to the SerialPort.

How do I write a single byte to the serial port?

    //Serial Init
    //Full fledged constuctor
    public NetCommManager(String portName, TransmissionType trans, String baud, String parity, String stopBits, String dataBits)
    {
        nc_baudRate = baud;
        nc_parity = parity;
        nc_stopBits = stopBits;
        nc_dataBits = dataBits;
        nc_portName = portName;
        nc_transType = trans;

        //now add an event handler
        comPort.DataReceived += new SerialDataReceivedEventHandler(netComm_DataReceived);
    }

Config:

       _commManger = new NetCommManager(commPortNumber,                        
       NetCommManager.TransmissionType.Text, "19200", "None", "One", "8");

The Byte to be written:

_commManager.WriteByte(Convert.ToByte( 0x7B));

And WriteByte function is:

public void WriteByte(byte data)
        {
            //change data to array
            //byte[] dataArray = new byte[1];
            var dataArray = new byte[] {data};
            //dataArray[0] = data;
            comPort.Write(dataArray, 0, 1);   // <-- Exception is thrown here
        }

The NetCommManager class is very much based on this example

3
  • 2
    You are missing portion of the code that creates comPort object... and have several commented out lines for some reason. Commented Jul 27, 2012 at 2:43
  • The commented lines are other attempts to get it working in a different form Commented Jul 27, 2012 at 2:55
  • 1
    +1 for good effort. Note that you still missing comPort = new... portion :). Somehow Jeff E managed to figure it (+1 to the answer obviously). On commented out code - consider if it shows significantly different variant of code. I don't think it is case here - so I'd simply remove it. Commented Jul 27, 2012 at 17:23

1 Answer 1

6

You forgot to Open() the comPort: http://msdn.microsoft.com/en-us/library/ms143551.aspx

Sign up to request clarification or add additional context in comments.

1 Comment

This was correct. Some how the port was being closed before the Write was occurring. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.