Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I reduce code repetition in this C code for PIC microcontroller?

I’m working on this serial communication project with PIC microcontroller. I’m using CCS C For PIC as a programming software. The code works fine right now but I want to improve my programming skills (I am a beginner). Especially these if statements bother me. Because there are too many of them. How can I improve this?

#define bt1 pin_a0
#define bt2 pin_a1
#define bt3 pin_a2
#define bt4 pin_a3
#define bt5 pin_a4
#define bt6 pin_c0
#define bt7 pin_c1
#define bt8 pin_c2
#define bt9 pin_c3
#define bt10 pin_c4
#define bt11 pin_d0
#define bt12 pin_d1
#define bt13 pin_d2
#define bt14 pin_d3
#define bt15 pin_d4
#define enable pin_c5
#define tx pin_c6
#define rx pin_c7

#int_rda
void rda_isr(void)
{
  disable_interrupts(int_rda);
  output_high(pin_d7);
}

void main()
{
  set_tris_a(0xFF);
  set_tris_b(0x00);
  set_tris_c(0xFF);
  set_tris_d(0xFF);
  set_tris_e(0x00);

  output_high(tx);
  output_low(rx);
  output_high(enable);

  enable_interrupts(int_rda);
  enable_interrupts(GLOBAL);

  lcd_init();

  while(TRUE)
  {
    if(input(bt1))     puts("\fbuton 1");
    if(input(bt2))     puts("\fbuton 2");
    if(input(bt3))     puts("\fbuton 3");
    if(input(bt4))     puts("\fbuton 4");
    if(input(bt5))     puts("\fbuton 5");
    if(input(bt6))     puts("\fbuton 6");
    if(input(bt7))     puts("\fbuton 7");
    if(input(bt8))     puts("\fbuton 8");
    if(input(bt9))     puts("\fbuton 9");
    if(input(bt10))     puts("\fbuton 10");
    if(input(bt11))     puts("\fbuton 11");
    if(input(bt12))     puts("\fbuton 12");
    if(input(bt13))     puts("\fbuton 13");
    if(input(bt14))     puts("\fbuton 14");
    if(input(bt15))     puts("\fbuton 15");
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Place your button pins into an array:
const unsigned char pins[] = {bt1, bt2, ... bt_15};
  1. Iterate through this array
  while(TRUE)
  {
      for(int index = 1; index <= sizeof(pins); index++)
      {
          if(input(pins[index - 1]))     printf("\fbuton %d", index);
      }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading