Electrical – How to toggle LED with button on dsPIC33 and dsPICDEM MCLV-2 devboard

buttonledmicrochipmicrocontrollerpic

I'm new to microcontrollers and the dsPIC33 and want to write a simple program before I get into anything more complex (even though this seems already very complex to me…). I am trying to toggle an LED on my dsPICDEM MCLV-2 development board using my dsPIC33EP256MC506 microcontroller. Right now, my code just makes the LED stay on without me pressing the button. Can anyone help me find whats wrong with my code?

If anyone knows of any sample programs that I can run and play with that would also be very helpful!

Compiler: MPLAB X

Programmer/Debugger: REAL ICE

Microcontroller: dsPIC33EP256MC506

Dev Board: dsPICDEM MCLV-2

main.c

int16_t main(void)
{

/* Configure the oscillator for the device */
ConfigureOscillator();
/* Initialize IO ports and peripherals */
InitApp();

TRISDbits.TRISD6 = 0; //set LED as output 
TRISGbits.TRISG6 = 1; //set Button as input, port unknown 

while(1)
{
    if(S3 == 0) { //start/stop switch
        uint32_t N = 21000000;
        while(S3) //debounce            
            while(N--);
            LATDbits.LATD6 = 1; //make LED pin high
    }
}
}

user.h

#define S3  !PORTGbits.RG6  //S2 button
#define S2  !PORTGbits.RG7  //S3 button

#define D2  !PORTDbits.RD6  //D2 LED  

#define DEBOUNCE_DELAY  30  //push button debounce delay, expressed in millisecond

/******************************************************************************/
    /* User Function Prototypes                                                   */
    /******************************************************************************/
    /* TODO User level functions prototypes (i.e. InitApp) go here */
    void InitApp(void);         /* I/O and Peripheral Initialization */

Best Answer

Try this out. make sure the S3 is the correct Macro definition for the button you are pressing, seems like you commented it wrong in the code.

while(1)
{
   uint32_t N = 21000000;
   uint32_t T = 21000000;

    if(S3 == 1) {
            LATDbits.LATD6 = 1; //make LED pin high
            while(N--); 
                        }
         else {  LATDbits.LATD6 = 0; //make LED pin low
               while(T--);  }

}

This won't check button debounce,(if this works, you can try out debounce) In some microcontroller there is Individual bits associated with the GPIO pins that can check the button debounce. If it is available,just enable it to check debounce.