将数据请求作为C#中的字符串发送到通信端口

时间:2010-03-03 22:30:58

标签: c# communication

我需要将一个写入方法作为C#中的字符串发送到一个com端口。它应该被包含在stx和etx之间。

e.g。 serialPort1.write(“02TY000D03”) - 其中02和03是stx和etx。

有人可以提供一个快速示例,因为我认为上面的代码不正确吗?

非常感谢

达伦。

2 个答案:

答案 0 :(得分:5)

您需要使用转义码;

serialPort1.Write("\x02TY000D\x03");

答案 1 :(得分:4)

以下是我从here获取的示例:

// This is a new namespace in .NET 2.0
// that contains the SerialPort class 
using System.IO.Ports; 

private static void SendSampleData() { 
    // Instantiate the communications
    // port with some basic settings 
    SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One); 

    // Open the port for 
    communications port.Open(); 

    // Write a string 
    port.Write("Hello World"); 

    // Write a set of bytes 
    port.Write(new byte[] {0x0A, 0xE2, 0xFF}, 0, 3); 

    // Close the port 
    port.Close();
}

因此,您最好使用Write而不是write,注意大写W.如果02和03是字节值,则必须使用\x转义值,即\x03;