Electronic – Toggle LED on when Button is pressed PIC

pic

I've got an olimex board with a PIC16LF76(Schematic – PIC IS a different pic):
Schematic of board

I'm trying to toggle the LED when the button is pressed down, my C code looks like:

#include <xc.h>
#pragma config FOSC = HS        // Oscillator Selection bits (XT oscillator)
#pragma config WDTE = OFF       // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF       // Power-up Timer Enable bit (PWRT enabled)
#pragma config CP = OFF         // FLASH Program Memory Code Protection bit (Code protection off)
#pragma config BOREN = OFF

int main() {
    TRISA = 0x20;
    ADCON0 = 0b111;
    while(1){
        if((PORTA & 0x20)==0) {
            PORTA |= 0x01;
        } else {
            PORTA &= ~0x01;
        }
    }
}

Whats going wrong(Something similar would work for Atmel AVR)? My compiler is XC8 and I am using MPLabX. I can confirm the switch works, and so does the LED as I have tested these parts of the olimex board individually and independently without the PIC chip in the board..

EDIT:

I've tried the answers supplied still to no avail. Also the LED is on despite not setting it on.

Best Answer

Your problem is probably caused by the analogue module. According to page 84 of the data sheet you linked the ADCON1 register needs to be set correctly to enable digital functions on PORTA.

A value of 0b111 is likely to make your code work (but see other answers about debouncing). Various other combinations of values are available in the table for REGISTER 11-2:

REGISTER 11-2 ADCON1 REGISTER

This type of configuration is common on the smaller 12F and 16F devices, which lack the ability to individually select analogue or digital per-pin.

As Spehro notes in the comments there are a number of ways to find which registers are associated with a port. The easiest is TABLE 4-2: SUMMARY OF REGISTERS ASSOCIATED WITH PORTA, which looks like this:

TABLE 4-2 SUMMARY OF REGISTERS ASSOCIATED WITH PORTA

This table becomes even more useful on large devices that have lots of functions such as extended analog features or capture and compare. Many of these need to be disabled after reset (e.g. comparators) and some might interfere unintentionally if misconfigured (e.g. MSSP).

Note that this table also shows that the 16LF76 does not have LATx registers, so other comments above can be safely ignored for this device.