我有GPS跟踪器和RFID阅读器。 我想把RFID卡放在RFID读卡器上后,我想看看最后的GPS位置。
在我的代码中,我获得了GPS-coordinantes的永久性。我有两个SerialPorts “gpsPort”和“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);
}
}
答案 0 :(得分:0)
使string indata
成为第一个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
无需中断任何事情;)