Electronic – Handling large number of inputs in PIC microcontroller

cifinputpic

I am interfacing PIC32 MCU with 24 inputs and UART. When any inputs comes, this data is transferred to PC via uart. I am using multiple if condition like

if(input1==high)
{
  putsUART("input 1 ON\n");
}
if(input2==high)
{
  putsUART("input 2 ON\n");
}

What this if condition is doing is whenever an input comes, it keep on printing the data like

input 1 ON
input 1 ON
input 1 ON

and it goes on. I want it to be displayed once only. For example, if I applied input1, input 1 ON should be printed once and if remove the input input 1 OFF should be displayed once.
I don't know how can I run this if condition only once. Please help. Thanks.!

CODE(just for 3 inputs):

 int main()
 {
  TRISAbits.TRISA6 = 1;
  TRISAbits.TRISA7 = 1;
  TRISGbits.TRISG13 = 1;
  while(1)
  {
   if(PORTAbits.RA6 == 0)         //INPUT 1
  {
   putsUART2("Input: 1 ON\n");
   Delayms(1000);
  }
  if(PORTAbits.RA7 == 0)          //INPUT 2
   {
   putsUART2("Input: 2 ON\n");
   Delayms(1000);
  }
  if(PORTAbits.RG13 == 0)          //INPUT 3
  {
   putsUART2("Input: 3 ON\n");
   Delayms(1000);
  }
 }
}

Best Answer

You need to remember the state of each input, and only output to the UART if it changes.

Something like this, just for one input so you get the idea :

// NB - put these lines outside your loop
uint8_t uLastRA6State = 0;                // last known state of RA6
uint8_t uLastRA7State = 0;                // last known state of RA7
// ... etc. 
// use one variable for each input, or if memory is tight, you could
// alternatively use one byte per 8 pins, but this more "wasteful"
// version is easier to understand the principle

while (1)
{
    // ...

    // NB - put this code inside your loop
    if (PORTAbits.RA6 != uLastRA6State)
    {
        // save current state
        uLastRA6State = uLastRA6State ? 0 : 1;

        // output change
        if (uLastRA6State)
            putsUART2("Input: 1 ON\n");
        else
            putsUART2("Input: 1 OFF\n");
    }

    // ... do the same for other inputs, e.g.
    if (PORTAbits.RA7 != uLastRA7State)
    {
        // ... similar to above, for RA7
    }
}