I'm trying to implement a code that when a button is pressed, it will trigger to send a message via uart.
Unfortunately, my code always detect the button as "always pressed" resulting to continuous send of message. I only want it to send everytime I press the button.
This is my code below:
Code: Select all
char read;
unsigned int oldstate;
void main() {
AD1PCFG = 0XFFFF; //SETTING AN INPUTS AS DIGITAL I/O
JTAGEN_bit = 0; //disable JTAG
UART2_Init(9600);
Delay_ms(1000);
TRISA = 1; //setting All portA as inputs
UART_Set_Active(&UART2_Read, &UART2_Write, &UART2_Data_Ready, &UART2_Tx_Idle); //Sets UART2 as active
UART_Write_Text("UART is now ready.");
UART_Write(13);
UART_Write(10);
while(1)
{
if (Button(&PORTA, 15, 1 ,1)) //detect if button is pressed
{
UART_Write_Text("Button is pressed.");
UART_Write(13);
UART_Write(10);
oldstate = 1;
}
if (oldstate && Button(&PORTA, 15, 1, 0)) //detect from logic 1 to 0
{
UART_Write_Text("Button is pressed again.");
UART_Write(13);
UART_Write(10);
oldstate = 0;
}
}
}