Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
11 years, 1 month ago.
What is wrong with my "if" statement?
#include "mbed.h" DigitalIn button(p21); DigitalIn Initials(p22); DigitalOut myled(LED1); int main() { if (button(1)) { myled = 1; wait(0.9); myled = 0; wait(0.3); myled = 1; wait(0.9); myled = 0; wait(0.3); myled = 1; wait(0.9); myled = 0; wait(0.9); myled = 1; wait(0.9); myled = 0; wait(0.3); myled = 1; wait(0.3); myled = 0; wait(0.3); myled = 1; wait(0.9); myled = 0; } }
Edited by 0xc0170: please use code highlight syntax.
Question relating to:
1 Answer
11 years, 1 month ago.
Hi,
you could have copied the error it shows,which is descriptive. To read a value from button, use : if (button == 1), or if (button.read() == 1)
Regards,
0xc0170
For the truly lazy you could also do: if (button) { ... }
Why this works: button on it's own is the same as button.read() due to the way digital in has been defined, that is why Martin's two options above do exactly the same thing. In c false is represented by 0, any non 0 value is considered to be true. So if (button) has exactly the same meaning as if (button.read() != 0). Since button is either going to be 0 or 1 testing for not equal to 0 is the same as testing for equal to 1.
posted by 27 Aug 2014