-1
我想收聽comport,但每隔十分鐘將單詞「PING」發送到該端口。我可以聽,沒有問題,但我無法弄清楚如何讓定時器在同一個開放端口上發送。如果我嘗試調用計時器事件並將代碼寫入com端口,則會出現錯誤:'名稱'myport'在當前上下文中不存在。'我知道爲什麼我得到錯誤,但我不知道如何格式化代碼以使用計時器來使用打開的同一個comport。使用定時器將數據發送到串行端口C#
下面是代碼:
using System;
using System.IO.Ports;
using System.Timers;
namespace ConsoleApplication1
{
class Program
{
//public static void Main()
static void Main(string[] args)
{
Timer aTimer = new Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
{
SerialPort myport = new SerialPort(); //Setting up the Serial
Port
myport.BaudRate = 9600;
myport.PortName = "COM4";
myport.Open();
if (myport.IsOpen)
{
myport.WriteLine(" Your are Now Connected to
GDC-IoT Number 1");
myport.WriteLine(" ALETS - Actionable Law Enforcment
Technology Software");
}
while (true)
{
string data_rx = myport.ReadLine(); // Read Serial Data
Console.WriteLine(data_rx);
}
}
}
public static void OnTimedEvent(object source,
ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
myport.WriteLine("PING");
}
}
}
我看着彼得Duniho的問題,並不能肯定我的怎麼是重複的。你能指出我的問題可能是重複的,所以我可以更新我的文章? –