3

在 C# 中将单个字节写入 .NET 4.0 中的串行端口会导致

用户代码未处理 InvalidOperationException

每次向 SerialPort 发送一个字节。

如何将单个字节写入串行端口?

    //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);
    }

配置:

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

要写入的字节:

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

WriteByte功能是:

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
        }

NetCommManager 类非常基于这个例子

4

1 回答 1

6

你忘Open()了:http comPort: //msdn.microsoft.com/en-us/library/ms143551.aspx

于 2012-07-27T04:57:13.283 回答