我正在尝试将一串 AT 命令发送到 USB 加密狗。我已经成功写入串口。但我没有成功地回读。基本上我想要做的是将让我们说 AT 到加密狗并在 Richtextbox 中接收 OK。接下来是将信息从另一台设备发送到加密狗并在富文本框中读取。
下面是我正在使用的代码:
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
SerialPort sp = null; //<---- serial port at form level
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// initialise port in form loadmyport.PortName = "COM3";
sp = new SerialPort();
sp.PortName = "COM8";
sp.BaudRate = 115200;
sp.Parity = Parity.None;
sp.DataBits = 8;
sp.StopBits = StopBits.One;
sp.NewLine = System.Environment.NewLine;
sp.ReadTimeout = 2000;
sp.WriteTimeout = 2000;
sp.DtrEnable = false;
sp.RtsEnable = false;
sp.WriteBufferSize = 4096;
sp.ReadBufferSize = 4096;
sp.Handshake = Handshake.None;
sp.Encoding = System.Text.Encoding.ASCII;
// also set up baud rate etc here.
// attach event handler to capture data received
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
}
private void button1_Click(object sender, EventArgs e)
{
connect.Enabled = false;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (!sp.IsOpen)
{
sp.Open();
}
// send data to port
sp.Write("ATXXX,XXXXXXX\r\n");
disconnect.Enabled = true;
}
catch (Exception)
{
// report exception to user
Console.WriteLine(e.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
connect.Enabled = true;
try
{
// open port if not already open
// Note: exception occurs if Open when already open.
if (!sp.IsOpen)
{
sp.Open();
}
// send data to port
sp.Write("atXX,0\r\n");
}
catch (Exception)
{
Console.WriteLine(e.ToString());
}
finally
{
disconnect.Enabled = false;
}
}
public void OnApplicationExit(object sender, EventArgs e)
{
sp.Close();
}
}
}