0

i need to make somekind of "on-off" button with my project. when the button not pressed, it supposed to print

stopped

if pressed

started

the problem is, when im not pressin it, it keep printin 'stopped', same when i keep pushin the button. i want it to only print the data once. more detail, what i need is, the button hold the stay in 'STARTED' position until i press it again.

here is my code

{ 
  int main (void)
  int TestM4;

  while(1)
  {
    if (!(PORTJ_IN&PIN1_bm)) //test m4
     {
         testM4 = 1;
         printf("%d\n", testM4);
     }
     else
     {
         testM4 = 0;
         printf("%d\n", testM4);
     }
  • 2
    `While(1)` without `break`! – Saurav Sahu Nov 15 '16 at 04:17
  • Clearly write what is the value of "PORTJ_IN" and "PIN1_bm" when (1)Button is already ON (2)Button is already OFF (3)When you pressed the button and changing state from ON to OFF (4)When you pressed the button and changing state from OFF to ON. – MayurK Nov 15 '16 at 15:17

2 Answers2

0
while(1)

This runs the while loop continuously.

So, it checks the buttons, prints out the statements, and then goes back straightaway to check them again.

To run it only once, remove the while loop altogether, but then the program will end pretty quickly.

Perhaps, look at ways to pause the program.

Community
  • 1
  • 1
Bijay Gurung
  • 1,094
  • 8
  • 12
0

I don't know all the code, so while(1) could be good or bad code, but you can test as a flag to change it and print once only.

while(1)
{
    if (!(PORTJ_IN&PIN1_bm)) //test m4
    {
         if(testM4 != 1) // status as button up
         {
             testM4 = 1;
             printf("%d\n", testM4);
         }
    }
    else
    {
         if(testM4 != 0)
         {
             testM4 = 0;
             printf("%d\n", testM4);
         }
    }
}
cpatricio
  • 457
  • 1
  • 5
  • 11
  • im sorry sir, its not like what i want. ive tried it. but what i wanted to do is more like, if i press the button then release it (because the button cant locked down, i dunno whats the type of the button) its 'ON' when i press it again its gonna be 'OFF' – Muki Wahyu Jati Nov 15 '16 at 05:59