C# 串口写字节

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11680730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:48:46  来源:igfitidea点击:

C# Serial Port Write Byte

c#serial-portbytesend

提问by DogEatDog

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

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

InvalidOperationException was unhandled by user code

用户代码未处理 InvalidOperationException

Every time a byte is sent to the SerialPort.

每次向 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 WriteBytefunction is:

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
        }

The NetCommManager class is very much based on this example

NetCommManager 类很大程度上基于此示例

采纳答案by Jeff E