Dear all, im new to arduino and got confuse while writing coding, let say if i want to convert FOR loop into IF statement, how do i do that? because i want to add push button and every time i hit the button, the value of x and y will increase in same way when using the FOR loop. here the coding:
The state change detection tutorial may be what you need. The button can be wired to ground instead of Vcc, then you don't need the external resistor. Set the button pin to pinMode(INPUT_PULLUP) in setup() and adjust the logic in the sketch to sense an active LOW switch (LOW when pressed).
The for statement is a looping statement. The if statement is not. You can replace a for statement with some other statements including the use of an if statement but why would you want to except perhaps to solve a riddle or a homework problem?
One of the responses that I can see discusses resistors and buttons, but the post that I see has neither. Perhaps the post has been changed by editing? That would be discourteous.
If you want to elimnate the for loops then let the loop() function do what its name suggests
int x = 0;
int y = 0;
void setup()
{
Serial.begin(115200);
}
void loop()
{
x++;
if (x == 5)
{
x = 0;
y++;
if (y == 5)
{
y = 0;
}
}
//put code here to read inputs if required
Serial.print("x : ");
Serial.print(x);
Serial.print("\t\t");
Serial.print("y : ");
Serial.println(y);
delay(200); //added to help understand the output
}
Dear all, thank you for your suggestion, for UKHeliBob, your are the real MVP, i want to put a button so when i pressed the button, the value will increases for x value first until it make loop and then x=0, make y+1 afterward and keep increasing in that order until it meet the conditions given. Thanks everyone
i want to put a button so when i pressed the button, the value will increases for x value first until it make loop and then x=0, make y+1 afterward and keep increasing in that order until it meet the conditions given
Read the input each time through loop() and when the button becomes pressed add one to x and when x reaches the top limit set it back to zero and increment y. When y reaches the top limit set it back to zero. If the button is not pressed then don't do anything and keep going round loop() until it becomes pressed.
The whole of the required logic is in my example program