Identify which button / switch pressed amongst multiples

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I have a circuit like below:

PORTA.0 = LED
PORTA.1 = LED
PORTA.2 = LED
PORTA.3 = LED

PORTB.0 = SWITCH / BUTTON
PORTB.3 = SWITCH / BUTTON

The objective of the code is that when button connected to PORTB.0 is pressed then LED should glow from PORTA 0-3 pattern while the reverse when button PORTB.3 is pressed.

I have the code does that but the issue is if I have already pressed button at PORTB.0, button pressed at PORTB.3 gets ignored while lighting the LEDs in PORTA 0-3 pattern.

Actually I am checking which button is pressed and start lighting the LED and then loop back again to check which one is pressed again - so in case I am lighting the LED and if at that time other button is pressed and released I am unable to catch that event - please let me know how to achieve that, rather even if I place it at last, middle it does not happens the way I want. Hence how it is possible that the lightning of LEDs pattern can be managed based upon the buttons pressed at any time of code execution.

Code:


#include 
#include 

int dir = -1;

void main()
{
DDRA  = 0b00001111;
PORTA = 0b00001111;
PINA  = 0b00000000;
DDRB  = 0b00000000;
PORTB = 0b00000000; 
PINB  = 0b00001001;
    while (1)
    {
      if(PINB.0 == 0)
        dir = 0;
      else if(PINB.3 == 0)
        dir = 1;
        if(dir == 0)
        {
        PORTA.0 = 0;
        delay_ms(200);
        PORTA.0 = 1;
        PORTA.1 = 0;
        delay_ms(200);
        PORTA.1 = 1;
        PORTA.2 = 0;
        delay_ms(200);
        PORTA.2 = 1;
        PORTA.3 = 0;  
        delay_ms(200);  
        PORTA.3 = 1;
        }
        else if ( dir == 1)
        {
        PORTA.3 = 0;
        delay_ms(200);
        PORTA.3 = 1;
        PORTA.2 = 0;
        delay_ms(200);
        PORTA.2 = 1;
        PORTA.1 = 0;
        delay_ms(200);
        PORTA.1 = 1;
        PORTA.0 = 0;  
        delay_ms(200);  
        PORTA.0 = 1;
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

This is a common problem. The solution is to choose a time tick, say 10ms and loop based on this time. Use variables to count off larger amounts of time. Each time through the loop (10ms) read the inputs and decide what to do next. I wrote a tutorial on multi-tasking that gives a framework and there are other tutorials on finite state machines which is a formal method you use to solve these problems.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks for the concept, can you please provide some useful links to incorporate the design.

There always seems a scenario when before completion of loop-through pass, another button can be pressed.

If possible please provide some code examples?