【问题标题】:How to send ctrl+z to serial port using c#如何使用 c# 将 ctrl+z 发送到串口
【发布时间】:2016-07-18 23:28:20
【问题描述】:

我尝试了以下方法: (这个“whatever”是在向端口发送 AT+STGR=3,1 后要求输入的 4 位密码)

1. this.port.WriteLine("whatever\0x1A");

2. this.port.WriteLine("whatever"+ char.ConvertFromUtf32(26));

3. this.port.WriteLine("whatever\u0001");

4. this.port.WriteLine("whatever"+(char)26);

5. this.port.WriteLine("whatever");
   SendKeys.Send("^(z)");

6. this.port.WriteLine("whatever");
   this.port.Write(new byte[] { 0x1A }, 0, 1);

7. this.port.WriteLine("whatever");
   this.port.Write(new byte[] { 0x26}, 0, 1);

它们都不起作用,但是当使用 putty 并输入代码后跟 ctrl+z 键时,一切正常,所以谁能告诉我 putty 是如何将这个 ctrl+z 发送到串行端口的?或者如果可能的话在c#中解决这个问题? 每次我尝试上面给出的 c# 代码时,调制解调器的回复是:

+CME ERROR: 100

串口初始化:

            port.PortName = "COM3";
            port.BaudRate = 115200;
            port.DataBits = 8;
            port.StopBits = StopBits.One;
            port.Parity = Parity.None;
            port.ReadTimeout = 300;
            port.WriteTimeout = 300;
            port.Encoding = Encoding.GetEncoding("iso-8859-1");
            port.DataReceived += new SerialDataReceivedEventHandler(this.port_DataReceived);
            port.Open();
            port.DtrEnable = true;
            port.RtsEnable = true; 

【问题讨论】:

  • 在这里阅读回复/回答stackoverflow.com/questions/4862684/…
  • @MethodMan 我已经尝试过 (char)26,它应该发送相当于发送 ctrl+z 的 ascii。但正如我提到的,它没有成功。或者你认为这不是发送它的方式?如果有,请写出正确的发送方式吗?
  • 使用写入字节 0x26。
  • @jdweng 能否请您写下代码作为答案?
  • 试试这个:this.port.Write(new byte[] { 0x1A }, 0, 1);

标签: c# serial-port gsm


【解决方案1】:

为 ctrl 代码找到一个像 this 这样的 ASCII 映射。看起来对于 ctrl Z 你需要一个 ASCII 0x26。我会将其定义为

char CtrlZ = (char)26;
char CR = (char)13;

serialport1.WriteLine(string.Format("whatever{0}{1}",CtrlZ, CR));

【讨论】:

  • 我遇到了类似的问题,这个解决方案解决了我的问题。这应该设置为正确答案。
  • 链接已失效。 :(
  • 只要谷歌“ASCII Map”并去图像,你会找到一堆。
【解决方案2】:

试试"whatever\u001A""whatever" Sleep "\u001A"

同时检查您通过连接发送/接收的整个命令/响应序列。

这是一个示例,可根据您的具体情况进行调整。

//TODO initialize the serialConnection and open it
//TODO specific commands...
serialConnection.WriteLine("AT+CPIN=\"1234\""); // replace according to your real situation
var response = serialConnection.ReadExisting();
Console.WriteLine("pin resp: " + response);
Thread.Sleep(200);
//TODO other specific commands?
serialConnection.Write("whatever");
//Thread.Sleep(200); uncomment this if it helps
serialConnection.Write(new byte[]{26}, 0, 1); // or Write("\u001A")
response = serialConnection.ReadExisting();
Console.WriteLine("ctrl-z resp: {0}", response);
//closing stuff, etc...

【讨论】:

  • 问题是这个调制解调器不保存输入缓冲区。因此,无法准确确认调制解调器如何接收输入。它可以工作到我发送 AT+STGR=3,1 以获取“>”,我应该在其中输入引脚并按 ctrl+z 确认。我将尝试在 pin 和 ctrl+Z 之间添加一个线程睡眠并让您知道。但是,我认为这很难解决任何问题。
  • 这里我也建议在 pin 后输入 return (WriteLine)(然后 sleep 和 Ctrl+z)
  • 您可能还需要在 AT+STGR=3,1 之后和 pin 之前返回 \r
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-03
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
  • 2011-04-28
相关资源
最近更新 更多