When I press a button, this button performs a tast once it was pressed and even I release button, it should keep performing the task. But when I release the button, it does not perform the task.
I assign a task to a button. And when I press this button and even if I release the button, I want the button to keep doing its task.
Here is a part of my code:
if (!input(button3)){
buton3_state=1;
} else buton3_state=0,buton3_lock=0;
if (buton3_state==1 && buton3_lock==0)
{
output_low(horn),horn_state=0;
buton3_lock=1;
}
if((input1_state==1 ||input2_state==1 ||input3_state==1 ||input4_state==1 ||input5_state==1 ||input6_state==1)&&(buton3_state==0))
{
horn_state=1;
}
if(horn_state==1){output_high(horn);}
CodePudding user response:
You probably want something like this:
int task = 0; // indicates if task should run
for (;;) // loop forever
{
if (!input(button3))
{
// button is pressed
task = 1;
// task is set to 1 and it stays 1 even if the button is released
}
if (task)
{
// do task...
}
}
CodePudding user response:
I guess you execute your code in a loop like "while" and your input function returns "1" when "button3 = 1". So according to this assumption. When you press the button task will work well but if you release the button in next iteration of loop your program flow will enter the else block. Simple create a global variable out of the loop "state = 0" and make "or" within "if" block after assign "1" in the "if" statement. This ways if you press one time to the button even if you release the button, your code will run continuously because the state is 1 in the first iteration. According to your limited information I understand this.
int state = 0
...
while(...)
{
if (!input(button3) || state) {
buton3_state=1;
state = 1;
}
else {
buton3_state=0;
buton3_lock=0;
}
}