‘=' is not the same as '==’.
A single equals sign is used to assign a value:
float y = 20.4; Serial.println(y); // this will give you 20.4 |
A two equals is a comparator
if (test == true) { Serial.println("true"); } |
You probably already know this, but it’s a very easy typo to make and it can be frustrating to spot in your code once it happens. One way to avoid the problem is to always use this shorthand version below, and stop using '==' altogether.
if (test) { Serial.println("true"); } if (!test) { Serial.println("false"); } |
A float can store values with a decimal point, and integers can store only whole numbers. What you might not realise, is that integer maths works a little different to floating point maths. On the Arduino, if you divide an integer by an integer, the result is always rounded to give an integer result.
int x = 2; float y = 9 / x; // the compiler only sees integers here, so it does integer math! Serial.println(y); // this will give you 4.00! |
One way to fix the above example is to show explicitly that 9 should be handled as a float.
float y = (float)9 / x; |
Or like this
float y = 9.0 / x; |