Hi Everyone,
I am new to Arduino Program and have a question around an if statement. I want to toggle a variable from 1 to 0 and print the results. However, when i upload the sketch it only prints out 1's. Anyone have any thoughts?
int flag = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
if (flag = 0){
Serial.println(flag);
flag = 1;
}
if (flag = 1){
Serial.println(flag);
flag = 0;
}
}
Also there are much other post's on this forum and other forum's, so for this couple of question i'd rather to search first before posting a question. Well you have kinda got all the information you've got now.
What also is been usefull for me and other programmer's as well are the fundamentals of the language c++.
There's an android app called soloLearn in the play store. that support's multiple languages, maybe dig into that app a bit further. i don't know if this app can be found on the ios store as well.
If you have a variable that will only contain 0 or 1 you should probably declare it as 'bool' or 'boolean' so the compiler can enforce that restriction for you.
It appears you are toggling between 0 and 1. You can do that with the '!' operator which does boolean inverse.
boolean flag = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println(flag);
flag = !flag;
}
One interesting effect of how you wrote (or intended to write) your sketch:
void loop()
{
// At this point, 'flag' is always 0
if (flag == 0)
{
Serial.println(flag);
flag = 1;
}
// At this point, 'flag' is always 1
if (flag == 1)
{
Serial.println(flag);
flag = 0;
}
// At this point, 'flag' is always 0
}