C#在任务后从2个串行ports读取数据



我有一个GPS-跟踪器和一个RFID阅读器。将RFID卡放在DER RFID阅读器上后,我想阅读最后的GPS位置。

在我的代码中,我将永久性地获得GPS坐标。我有两个连续剧" gpsport"one_answers" rfidport"。我不知道以这种方式中断了两个eventhandler。您可以解决问题还是任何想法?

这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        SerialPort gpsPort = new SerialPort("COM5");
        gpsPort.BaudRate = 9600;
        gpsPort.Parity = Parity.None;
        gpsPort.StopBits = StopBits.One;
        gpsPort.DataBits = 8;
        gpsPort.Handshake = Handshake.None;
        gpsPort.RtsEnable = true;
        gpsPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        gpsPort.Open();
        SerialPort rfidPort = new SerialPort("COM4");
        rfidPort.BaudRate = 9600;
        rfidPort.Parity = Parity.None;
        rfidPort.StopBits = StopBits.One;
        rfidPort.DataBits = 8;
        rfidPort.Handshake = Handshake.None;
        rfidPort.RtsEnable = true;
        rfidPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler2);
        rfidPort.Open();
        Console.ReadKey();            
    }
     public static void  DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        if (indata.Contains("GPRMC"))
        {
            string[] sentence = indata.Split(',');
            string latitude = sentence[3].Substring(0, 2) + "°";
            latitude = latitude + sentence[3].Substring(2);
            latitude = latitude + sentence[4];
            string longitude = sentence[5].Substring(2, 1) + "°";
            longitude = longitude + sentence[5].Substring(3);
            longitude = longitude + sentence[6];
            Console.Write("Latitude:" + latitude + Environment.NewLine + "Longitude:" + longitude + Environment.NewLine + Environment.NewLine);
        }            
    }
     public static void DataReceivedHandler2(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.Write(indata + Environment.NewLine);       
    }
}

使 string indata在firs dataReceived事件范围之外成为静态变量。

class Program
{
    private static string indata_GPS = "";
....
}

现在您应该从GPS中阅读此变量:

public static void  DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    indata_GPS = sp.ReadExisting();

第二次DataReceived事件从RFID设备发射后,您只需从indata_GPS读取值即可。这样,您将获得GPS

的最新值
public static void DataReceivedHandler2(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    Console.Write("RFID: " + indata + Environment.NewLine);
    Console.Write("GPS latest Data: " + indata_GPS  + Environment.NewLine);
}

我不知道有多中断两个eventhandler

无需打断任何东西;)

相关内容

  • 没有找到相关文章

最新更新