在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类非常基于this example