2017-05-31 135 views
-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"); 
    } 
} 
} 
+0

我看着彼得Duniho的問題,並不能肯定我的怎麼是重複的。你能指出我的問題可能是重複的,所以我可以更新我的文章? –

回答

0

你必須在Main功能定義myport,所以它是局部的功能。嘗試宣告它的方法外,在類級別,以便它可以訪問所有的方法:

class Program 
{ 
    private static SerialPort myPort; 

    static void Main(string[] args) 
    { 
     var timer = new Timer { Interval = 5000, Enabled = true }; 
     timer.Elapsed += OnTimedEvent; 

     myPort = new SerialPort { BaudRate = 9600, PortName = "COM4" }; 
     myPort.Open(); 

     if (myPort.IsOpen) 
     { 
      myPort.WriteLine("You are are now connected to GDC-IoT Number 1"); 
      myPort.WriteLine("ALETS - Actionable Law Enforcment Technology Software"); 
     } 

     // Listen to serial port 
     while (true) 
     { 
      Console.WriteLine(myPort.ReadLine()); 
     } 
    } 

    public static void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 
     if (myPort == null) 
     { 
      Console.WriteLine("Port has not yet been assigned"); 
     } 
     else if (!myPort.IsOpen) 
     { 
      Console.WriteLine("Port is not open"); 
     } 
     else 
     { 
      Console.WriteLine("Sending ping..."); 
      myPort.WriteLine("PING"); 
     } 
    } 
} 
+0

Rufus你搖滾!謝謝..我無法弄清楚如何讓所有變量都可以訪問它,但是工作起來!非常感激! –

相關問題