If command

I am using this type of programming.

Serial.println(distance);
}
}
if (distance<=4)
{digitalWrite(22, HIGH);
}
else if (distance<=6)
{
digitalWrite(23, HIGH);
}
else if (distance<=8)
{
digitalWrite(24, HIGH);
}

else if (distance<=10)
{
digitalWrite(25, HIGH);
}
else if (distance<=12)
{
digitalWrite(26, HIGH);
}
else if (distance<=14)
{
digitalWrite(27, HIGH);
}
else
{
}
i have some questions,
1)How to simplify the code?? (because m using 25 leds with respect to distance)
2)as distance increse, led (level) increse as it is decreasing, it should decrease with respect to level…
I need little guidance

You can map 'distance' to your 'output' since they are linearly related. Keeping both as integers so that neither take on partial numbers. Then you wouldn't need any if statements. Just one digitalWrite.

After a dozen posts, you should know how to post code properly. Please read Nick Gammon's two posts at the top of this Forum for instructions, especially the use of code tags for source code listing.

Next, are you creating a "bar graph" of LEDs where they remain on as the signal gets stronger, or should only one LED at a time be on?

ApexM0Eng:
You can map ‘distance’ to your ‘output’ since they are linearly related.

something like this:

int lastDistance = 0;
int ledPin[25] = {22, 23, 24, 25, 26, ... }; //pseudo code, put your 25 pin numbers here

void setup() 
{
  for (int i = 0; i < 25; i++)
  {
    pinMode(ledPin[i],OUTPUT);
  } 
}

void loop() 
{
  int currentDistance = map(getDistance(), 0, 50 , 0, 25); //pseudo code to get your distance and map it zero to 25 leds
  if (lastDistance != currentDistance)
  {
    for(int i = 0; i < 25 ; i++)
    {
      digitalWrite(ledPin[i], i <= currentDistance? HIGH : LOW);
    }
    lastDistance = currentDistance;
  }
}

If the linear mapping holds ...

#define ENTRY_COUNT(ARRAY)  (sizeof(ARRAY) / sizeof(ARRAY[0]))

const uint8_t   pinLED_1    = 22;
const uint8_t   pinLED_2    = 23;
const uint8_t   pinLED_3    = 24;
const uint8_t   pinLED_4    = 25;
const uint8_t   pinLED_5    = 26;
const uint8_t   pinLED_6    = 27;

//... others as needed ...

const uint8_t   LED_OFF     = LOW;
const uint8_t   LED_ON      = HIGH;

const uint8_t   pinsLED[] =
{
      pinLED_1
    , pinLED_2
    , pinLED_3
    , pinLED_4
    , pinLED_5
    , pinLED_6
// ... others as needed ...
};

size_t index = ((distance - 4) / 2) % ENTRY_COUNT(pinsLED);

digitalWrite(pinsLED[index], LED_ON);

umerchamp:
2)as distance increse, led (level) increse as it is decreasing, it should decrease with respect to level...

Position the LEDS upside down, so the highest pin number drives the bottom LED. In other words, label them differently. :slight_smile: