0

The Atmega16 PORTC is used for push button, and renamed as so

#define LEFT_S       PINC&(1<<2)
#define RIGHT_S      PINC&(1<<3)
#define UP_S         PINC&(1<<4)
#define DOWN_S       PINC&(1<<5)
#define OK_S         PINC&(1<<6)

And am trying to put it in loops like

while (OK_S);

or

if (UP_S);

What is the consideration?

while (OK_S) or if (UP_S) is not working in functions.

But by taking the key value to a variable via a function, then I can check it.
When I use a function ch = Key_pressed(); while(ch==1) is working perfectly.

int Key_pressed(void)
{   
   while(1) {
      if (LEFT_S)  { while (LEFT_S);  return 1; }             
      if (RIGHT_S) { while (RIGHT_S); return 2; }
      if (UP_S)    { while (UP_S);    return 3; }
      if (DOWN_S)  { while (DOWN_S);  return 4; }
      if (OK_S)    { while (OK_S);    return 5; }
   }
}

The mentioned error is show when simulating in Proteus

girikks
  • 15
  • 7

2 Answers2

2

Probably you Key_pressed(); does the debouncing internally and you do not have to worry about it.

If you check the pin status you may receive tens or hundreds fake "key presses" as the metal contacts bounce for the very short time: enter image description here

0___________
  • 60,014
  • 4
  • 34
  • 74
1

It was the mistaken of Precedence of the != operator is higher than of the & (bitwise and) operator i was used as while (OK_S != 1) it means as

while (PINC & ((1 << 6) != 1))

to the C compiler would prefer something like

while ((PINC & (1 << 6)) != 1)

But the correct way is

while ((PINC & (1 << 6)) != (1 << 6))

so i corrected the macro definition as

#define OK_S (PINC & (1 << 6))

And working correctly .

girikks
  • 15
  • 7
  • `while ((PINC & (1 << 6)) != (1 << 6))` is not good. If you change OK_S to a different port, the testing against `(1 << 6)` will fail. Test it **always** against 0 or false, implicitly or explicitly. Parenthesis in macro definitions are a must. Always. – user5329483 Aug 29 '17 at 18:43
  • I dont want to change the port right now ,please mention How to test against 0 or false .in this case – girikks Aug 30 '17 at 03:43
  • `if (S_OK)` or `if (!S_OK)` or `if (S_OK==false)` or `if (S_OK==0)`. The last three are the same. – user5329483 Aug 30 '17 at 16:16