This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Implementation of Switch function

Other Parts Discussed in Thread: MSP430F47186

I would like to check whether my code for Switch function is correct or not.

I attach at the bottom my code for testing only switch function.

 

By pushing the switch, LED will be toggled. However, sometimes (once in a 10 times or so), one push causes LED light-turn-off and light-turn-on. It seems the SW1_Pushed functin is called twice by the one push.

I appreciate your suggetion on correction of my code.

 

I am using MSP430F47186 on my own board. LED_D6 means LED named D6.

Best regards

=====================

#include <msp430x471x6.h>
#include <stdbool.h>

#define SW1_BIT     BIT4    // P1.4
#define SW2_BIT     BIT5    // P1.5

#define LED_D6_BIT  BIT2    // P1.2

void SW1_Pushed(void);
void SW2_Pushed(void);

void main(void)
{
    WDTCTL = WDTPW + WDTHOLD;
    FLL_CTL0 |= XCAP14PF;
    
    P1DIR |= LED_D6_BIT;

    //SW
    P1DIR &= ~SW1_BIT;
    P1DIR &= ~SW2_BIT;
   
    P1IE |= SW1_BIT;
    P1IES |= SW1_BIT;
    P1IFG &= ~SW1_BIT;
   
    P1IE |= SW2_BIT;
    P1IES |= SW2_BIT;
    P1IFG &= ~SW2_BIT;

   
    while(1) {
        _BIS_SR(LPM3_bits + GIE);
    }
   
}

void LED_D6(bool bfOn)
{

    if(bfOn) {
        P1OUT |= LED_D6_BIT;
    } else {
        P1OUT &= ~LED_D6_BIT;  
    }
   
}

#pragma vector=PORT1_VECTOR
static __interrupt void Port1_ISR (void)
{
 
    if((P1IN & SW1_BIT) == 0) {
        SW1_Pushed();
        P1IFG &= ~SW1_BIT;
    }

    if((P1IN & SW2_BIT) == 0) {
        SW2_Pushed();
        P1IFG &= ~SW2_BIT;
    }   
   
}

void LED_D6Toggle(void)
{
    P1OUT ^= LED_D6_BIT;
}

void SW1_Pushed(void)
{
 
    LED_D6Toggle();
    _NOP();
   
}

void SW2_Pushed(void)
{
   
}

 

  • I don't see any debouncing in your code.

    It is possible that the LED is always switched on and of and on again with a frequency of some kHz until it finally settles.

    You should introduce a timeout which starts at the first detected edge and does prevent any more interrupt action for some time (e.g. 100ms).

    There's another thread about this with code snippets. search vor 'debounce' or 'debouncing'

  • Thank you very much for checking my code, Jens-Michael.

     

    I will consider to introduce the timeout. Also I will read the post related to debounce.

     

    Best regards

     

**Attention** This is a public forum