gpt4 book ai didi

c# - 串行端口 : Send in Bytes or Characters?

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:18 24 4
gpt4 key购买 nike

<分区>

我正在使用串行端口应用程序发送带有 Unicode 控制字符的命令,但没有成功。当我在 super 终端或 Putty 中发送相同的命令时,通信有效,所以我很好奇这两个程序是否写出字节数组或 Unicode 字符甚至字符串。如果我模仿他们所做的,我可能会成功......我还注意到我从 Visual Studio 的工具箱中取出的串行端口属性被列为使用我在代码中编写的不同 COM 端口,这就是为什么我没有得到回应还是我的代码覆盖了它?在进行环回测试时,我也得到了带有控制字符的正确命令的输出,所以我无法弄清楚我做错了什么。这是 .NET 2.0 Framework 仅供引用

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace SimpleSerial
{
public partial class Form1 : Form
{
string RxString;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 9600;
serialPort1.Parity = Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
serialPort1.Handshake = Handshake.None;
serialPort1.ReadTimeout = 500;
serialPort1.WriteTimeout = 500;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
const char STX = '\u0002';
const char ETX = '\u0003';
readonly string pull_shelf_104 = string.Format("{0}01P00104##{1}" , STX, ETX);
private byte[] WrapString(string pull_shelf_104)
{
return System.Text.Encoding.ASCII.GetBytes(pull_shelf_104);
}
private void linkLabel_HC1_100_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (serialPort1.IsOpen)
{
byte[] data = WrapString(pull_shelf_104);
serialPort1.Write(data, 0, data.Length);
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void DisplayText(object sender, EventArgs e)
{
textBox1.AppendText(RxString);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
}
}
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com