2015-03-13 89 views
2

我正在为Uno编写我的第一个代码,并且遇到了使用库的问题。我创建了两个GPSLocation类(loc1和loc2)的实例来存储两个位置的lat和lon。当我给它们赋值时,立即调用它们,两个实例保持相同的值,这些值是我设置值的最后一个对象。我一直在看这个小时,看不到我做错了什么。两个返回相同值的Arduino类实例

我的代码如下。任何帮助都会很棒。

Test.ino

void setup() { 

    Serial.begin(115200); 
} 

void loop() { 

    GpsLocation loc1; 
    loc1.setLat(-12.3456); 
    loc1.setLon(34.4567); 
    GpsLocation loc2; 
    loc2.setLat(-78.9123); 
    loc2.setLon(187.6325); 
    delay(1000); 
    Serial.print("Loc1: "); 
    Serial.print(loc1.getLat(), 4); 
    Serial.print(", "); 
    Serial.print(loc1.getLon(), 4); 
    Serial.print("\n"); 
    Serial.print("Loc2: "); 
    Serial.print(loc2.getLat(), 4); 
    Serial.print(", "); 
    Serial.print(loc2.getLon(), 4); 
    Serial.print("\n"); 
} 

GPSLocation.h

#ifndef GpsLocation_h 
#define GpsLocation_h 

#include "Arduino.h" 

class GpsLocation 
{ 
    public: 
    GpsLocation(); 
    void setLat(float lat); 
    void setLon(float lon); 
    float getLat(); 
    float getLon(); 
}; 

#endif 

GPSLocation.cpp

#include "Arduino.h" 
#include "GpsLocation.h" 

float latitude = 0.0; 
float longitude = 0.0; 

GpsLocation::GpsLocation(){} 

void GpsLocation::setLat(float lat) 
{ 
    latitude = lat; 
} 

void GpsLocation::setLon(float lon) 
{ 
    longitude = lon; 
} 

float GpsLocation::getLat() 
{ 
    return latitude; 
} 

float GpsLocation::getLon() 
{ 
    return longitude; 
} 

这是WHA t串行监视器返回

Loc1: -78.9123, 187.6325 
Loc2: -78.9123, 187.6325 
+4

制作'GpsLocation'的'latitude'和'longitude'成员。 – user657267 2015-03-13 07:01:13

+2

是的,看起来像你的经度和纬度被定义为全局变量 - 它们没有在GPSLocation类中定义 - 因此只有它们的一个副本存在。 – ThisHandleNotInUse 2015-03-13 07:09:14

回答

0

我更新了我的GPSLocation类,如下解决了我的问题。多谢你们。

GPSLocation.h

#ifndef GpsLocation_h 
#define GpsLocation_h 

#include "Arduino.h" 

class GpsLocation 
{ 
    public: 
    float latitude; 
    float longitude; 
}; 

#endif 

GPSLocation.cpp

#include "Arduino.h" 
#include "GpsLocation.h" 

设置和越来越Test.ino如下

loc1.latitude = -12.3456; 
Serial.print(loc1.latitude, 4); 
+0

你应该接受你的回答,表明你的问题已经解决。 – Erik 2015-05-01 22:10:16

0

初始代码的问题在于,您已将变量定义为全局变量(在全局范围内),并且这两个实例都可以访问这些变量,因此从任何实例应用到它们的最后一个值都会影响并可供所有实例访问。

一般情况下,你应该避免使用全局变量,因为它被认为是不好的做法。

通过使变量非静态类成员,实际上你让他们你的情况下的“零件”。这样,每个Arduino实例在某种意义上都有自己的变量副本,您可以分别应用值。

UPDATE:为了维护封装,也更好地声明变量为私有,并通过setter和getter方法适用于他们的访问。关于wiki的更多概念请看看。

相关问题