-1

I'm trying to turn on a LED on a pic24FV16KA301 microcontroller, through a button press. The problem is the LED automatically goes on. After some altering it looks like the PIC is automatically pressed. The button is connected with a pull up resistor. Here is part of the code(since some of the code is irrelavent to the problem).

#include <xc.h>
#include "Header_School_Project.h"
#include <stdlib.h>
#include <stdio.h>
#include <libpic30.h>
#define _XTAL_FREQ 20000000
#define LED_LOW LATAbits.LATA4  
#define BUTTON_LOW PORTAbits.RA1

void main(void)
{
   TRISAbits.TRISA4 = 0;
   TRISAbits.TRISA1 = 1;
    
    while(1)
    {           
        if(!BUTTON_LOW)                                   
        {
            __delay_ms(100);
            if(!BUTTON_LOW)   
            {
                LED_LOW = 1;
            }
        }
        else if(BUTTON_LOW)
        {
            LED_LOW = 0;
        }
  return;
}

If anyone can help me with this, that would be much appreciated.

EDIT: After changing the __delay_ms(100) to __delay_ms(1000) I see that the LED is flickering on and off really fast

  • 1
    Would you mind to show us the circuit? And did you measure the voltage at the port pin of the button? What does it show for the released button, and what for the pressed button? – the busybee Apr 19 '21 at 12:52
  • When it's released it says 3.3v and when it's pressed it says 0V –  Apr 19 '21 at 12:59
  • So your button level looks correct. What does the LED do if you press the button? – the busybee Apr 19 '21 at 13:02
  • When either the button is pressed or released the LED stays on. –  Apr 19 '21 at 13:16
  • 1
    Hi, add 'ANSA = 0' in your code before using the PORTA in order to use the PORTA as digital IO. – Kozmotronik Apr 19 '21 at 15:06

2 Answers2

1

First configure the pins of porta as digital pins as mentioned in the datasheet of corresponding microcontroller using ANSEL register.
One more thing is increase de-bouncing delay to about 300ms, this much can solve your problem.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
0

As mentioned by Kozmotronik you need to set the pin to digital first. PICs default to analog inputs... this "defualt" has wasted enormous number of man hours.