C# 使用定时器向串行端口C发送数据#

C# 使用定时器向串行端口C发送数据#,c#,timer,C#,Timer,我想听一首曲子,但每十分钟就给那首曲子发一个“PING”字。我可以毫无问题地听,但我不知道如何让计时器在同一个开放端口上发送。如果我尝试调用计时器事件并将代码写入com端口,则会出现错误:“名称“myport”在当前上下文中不存在。”我知道为什么会出现错误,但我不确定如何格式化代码以使用计时器使用打开的同一个组件 代码如下: using System; using System.IO.Ports; using System.Timers; namespace ConsoleApplicatio

我想听一首曲子,但每十分钟就给那首曲子发一个“PING”字。我可以毫无问题地听,但我不知道如何让计时器在同一个开放端口上发送。如果我尝试调用计时器事件并将代码写入com端口,则会出现错误:“名称“myport”在当前上下文中不存在。”我知道为什么会出现错误,但我不确定如何格式化代码以使用计时器使用打开的同一个组件

代码如下:

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");
    }
}
}

您在
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");
        }
    }
}

鲁弗斯,你真厉害!谢谢..我不知道如何让所有变量都可以访问它,但这是可行的!非常感谢!我看了彼得·杜尼霍(Peter Duniho)的问题,不确定我的问题是如何重复的。你能给我指出一个可能是重复的问题,这样我就可以更新我的帖子了吗?