Search code examples
buttonmicrocontrollerpicmplab

PIC microcontroller automatically pressed


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


Solution

  • 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.