Count At Each Button Press

Thread Starter

em_cardc

Joined Apr 5, 2016
43
Hello,

I have this code which is supposed to implement counting in increments and decrements at a button press to light up LEDs 0-15...

The code works but I want the program to hold the value it is counting until it is pressed again.

Any idea ?

Code:
#include <msp430.h>
unsigned int i;
int increment();
int decrement();
int reset();

int main(void) {
WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer

  P1DIR |= BIT0 + BIT1 + BIT2 + BIT3;
  P2IE  |= BIT0 + BIT1 + BIT2;
  P2IES |= BIT0 + BIT1 + BIT2;
  P2IFG |= 0x00;

_BIS_SR(LPM4_bits+GIE);
while(1);
}

#pragma vector=PORT2_VECTOR
  __interrupt void PORT2_ISR(void){
  if((P2IFG & 0x01) == 0x01){  // First button Press?
  increment();  // call Increment subroutine
  P2IFG &= ~0x01;  // Then clear Interrupt Flag
  }
  else if((P2IFG & 0x02) == 0x02) {  // Decrement if Second Button is Pressed
  decrement();
  P2IFG &= ~0x02;
  }
  else if((P2IFG & 0x04) == 0x04) {  // Reset Button
  reset();
  P2IFG &= ~0x02;
  }
  }

int increment()
{
for(i = 0; i <= 15; i++){
  P1OUT = i;
  __delay_cycles(1000000);
}
}

int decrement()
{
for(i = 15; i > 0; i--){
  P1OUT = i;
  __delay_cycles(1000000);
}
}

int reset()
{
  P1OUT &= ~0x0F;
  __delay_cycles(1000000);
}
Moderator edit: added code tags and added blank lines between functions
Tip: Pretty up your format by indenting code blocks { ... }.
 

MrChips

Joined Oct 2, 2009
34,807
It would be easier to follow your code if you start using some basic formatting and programming style.

Indent every code block { ... }. The control structure will become more apparent.

Start using more #define statements, for example:

Code:
#define INC_BUTTON BIT0
#define DEC_BUTTON BIT1
#define RESET_BUTTON BIT2
Anyhow, writing code is the last thing you want to do.
Design your program using control structures first.
That is, use flow charts or pseudo code to make sure your control flow works on paper first before writing code.

The same advice was given in this thread.

https://forum.allaboutcircuits.com/threads/hardware-interrupt-programming.137559/
 
Top