该程序旨在打开两个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);
}
}
答案 0 :(得分:2)
我建议使用System.Threading.Timer
代替,您可以将状态对象传递到传递给TimerCallback
的构造函数中。