Pages: [1]   Go Down
Author Topic: Strange Variable Problem  (Read 368 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 3
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello,

I'm developing some software for an unmannned autonomous vehicle, and I've run into a very strange problem -- I have a float variable called "heading", and for testing purposes, I ended up with code like this:

Serial.println("---------TESTING");
if (heading == heading) {
    Serial.println("Success");
}
Serial.println("TESTING---------");



The strange thing is, even though the first and last lines do print, the "Success" line doesn't! I initially wrote this code because the "heading" variable wasn't storing the proper value, and sort of out of desperation I just figured I would make sure that the variable itself was ok. Not sure where my logic was on that one, but it was late : P

Anyway, what would be a reason that a variable would not register as equal to itself?
Logged

Grenoble/Lyon - France
Offline Offline
Sr. Member
****
Karma: 0
Posts: 363
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Can it be because it's undefined ?
Logged


0
Offline Offline
Newbie
*
Karma: 0
Posts: 3
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Good thought, but it's defined as a global variable:

float heading;

..earlier in the file (and given a value, albeit in a slightly complicated way, just before the test).
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 3
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Erg, sorry about the trouble...it was one of those really annoying hard-to-spot programming mistakes.

Thanks though!
Logged

Las Vegas, NV
Offline Offline
God Member
*****
Karma: 0
Posts: 507
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

In general you can run into problems when you try to test for equality using floats, although it is strange that a float would not register the same as itself.  Try changing the code to see if it's close to itself:

if (heading > heading - 0.0001 && heading < heading + 0.0001)
  serial.println("success");

I've used 0.0001 in my example, but you should choose something that's three or four orders of magnitude smaller than whatever is currently in "heading".

- Ben
Logged


New Zealand
Offline Offline
God Member
*****
Karma: 0
Posts: 999
Arduino pebbles
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
it was one of those really annoying hard-to-spot programming mistakes.
Which was? smiley

--Phil.
Logged

Pages: [1]   Go Up
Jump to: