One part of the problem is that everything in the loop happens several times a second (even hundreds, thousands etc), depending on the frequency of the microcontroller.
In your code, as soon as you press the button, the microcontroller would turn off the led, as soon as you release the button the led would turn on. Try keeping the button pressed a few seconds.
In order to work like you want, as simple modification should do it :
while (1) {
if (ButtonInput == 1) {
if (LED_RA2 ==1) {
LED_RA2 = 0;
} else {
LED_RA2 = 1;
}
}
Basically, when you press the button, flip the LED_RA2. You can also do some basic debouncing of the button by adding a counter which makes your loop not change the state of the led if not enough time has passes since last press.
unsigned int counter = 501;
while (1) {
counter++;
if (counter > 65534) counter = 501;
if ((ButtonInput == 1) && (counter > 500)) {
if (LED_RA2 ==1) {
LED_RA2 = 0; counter = 0;
} else {
LED_RA2 = 1; counter = 0;
}
}
meaning every time microcontroller goes through loop, the counter goes up by one until counter is the maximum allowed by data type, 65535 and then it resets. In the loop you only change states if the counter is above a value. If you change state, you set the counter to 0, so now there must be at least that many loops (500) before your code will again do something if the button is pressed.
How fast those loops pass depends on the microcontroller frequency, 500 loops can be done in as little as 1-2 nanoseconds I think.
*debouncing = a pushbutton is mechanical and by design, due to the spring inside and the two pieces of metal that are supposed to touch, it often happens that before you get a continuous contact you can get some break in the contact due to the metals inside flexing. So you could get something like this from the button when you press it ... 0001001101111111
If you press the button for a very short time, it's possible that in the loop you'd catch the first 1 and then on the second pass you'd read a 0 even though the button is physically still pressed at that time. So your code should keep that in mind, or you would do debouncing in hardware (add a small capacitor so that when button is pressed, the capacitor has to charge and reach the threshold voltage on pin and then microcontroller sees that as 1)
ps.
and there's really no need to use LATAbits.LA2 in this context, you can use PORTABits.RA2
and by the way, on PIC16F1827, RA2 is shared with DACOUT (DAC) and that one has priority. But it's disabled by default so it should be I/O pin. Still you could make sure by settting DACCON0 =0 before the loop.