该程序旨在打开两个 COM 端口并每隔 1 秒将数据从一个端口发送到另一个端口。用户输入哪个端口发送和哪个端口接收。我遇到的问题是 ElapsedEventHandler() 接受了具有两个默认参数的 OnTimedEvent() 函数。我希望 OnTimedEvent() 函数向发送端口写入一些内容并在接收端口上读取它,然后将其显示到控制台。显然我的代码不会像现在这样工作,因为端口和消息不在 OnTimedEvent() 的范围内。我该怎么做才能使该功能按我想要的方式工作?提前致谢。
using System;
using System.IO.Ports;
using System.Timers;
public class serial_test1
{
public static void Main(string[] args)
{
string sender;
string recver;
string buff_out;
string message;
SerialPort send_port;
SerialPort recv_port;
if (args.Length == 1)
{
sender = "UART";
recver = "USB";
message = args[0];
}
else if (args.Length == 2)
{
sender = args[0];
message = args[1];
if (sender == "USB")
{
recver = "UART";
}
else
{
recver = "USB";
}
}
else
{
sender = "UART";
recver = "USB";
message = "TEST MESSAGE";
}
int baud = 115200;
int data_bits = 8;
Parity parity = Parity.None;
StopBits stop_bits = StopBits.One;
buff_out = message;
SerialPort UARTport = new SerialPort("COM1", baud, parity, data_bits, stop_bits);
SerialPort USBport = new SerialPort("COM7", baud, parity, data_bits, stop_bits);
UARTport.Open();
USBport.Open();
if (sender == "USB")
{
send_port = USBport;
recv_port = UARTport;
}
if (sender == "UART")
{
send_port = UARTport;
recv_port = USBport;
}
string header = "from " + sender + " port to " + recver + " port";
Console.WriteLine(header);
Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 1 second.
aTimer.Interval = 1000;
aTimer.Enabled = true;
UARTport.Close();
USBport.Close();
Console.ReadLine();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string buff_in;
send_port.WriteLine(buff_out);
buff_in = recv_port.ReadLine();
Console.WriteLine(buff_in);
}
}