The code below, without the if statement, count’s up from 1 to infinite and shows this in the console as intended.
If I add the if statement, I get what’s shown in the screenshot below. Why does this happen?
#include <Arduino_MKRIoTCarrier.h>
MKRIoTCarrier carrier;
int a;
int r,g,b;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without blocking if none is found
delay(1500);
carrier.begin();
carrier.display.setRotation(0);
a =1;
}
void loop()
{
// put your main code here, to run repeatedly:
Serial.println(a);
a =a + 1;
if (a = 10)
{
carrier.leds.setPixelColor(0, 255, 0, 0);
carrier.leds.show();
}
}
>Solution :
In c++, comparison is ==
, so you need to write if (a == 10)
. When you write, a = 10
, that’s an assignment: a
will have the value of 10
and the evaluation value is also 10
(to be precise, reference to a
which is 10
), thus in if()
it evaluates to true
.