C# Serial Port Write Byte

25,870

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

Share:
25,870
DogEatDog
Author by

DogEatDog

Lots of information that I don't want to provide In One Fell Swoop ✓ I will: Elixir, Ruby (off the rails), Rails, JavaScript ✓ I might: Python, Rust, C#, C/C++, ✓ I can: Java, Perl, Objective-C

Updated on February 06, 2020

Comments

  • DogEatDog
    DogEatDog over 4 years

    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