Instead of repeating several calls to digitalwrite
you should consider changing the pins directly as described here.
This now depends on which port your LEDs are connected to. Assuming port D you would use DDRD
to define the pins as output (usually in setup()
) and PORTD
to set their values (in loop
), e.g.
DDRD = B11111110; // define pins 1..7 as outputs, pin 0 as input
and
PORTD = B11110000; // switch on first 4 LEDs
Now all you need to do is to write a function to map your number range to suitable bit strings.
The function could look like this:
int convert(int n) {
int res = 0; // start with all pins off (zero)
while (n > 0100) {// repeat while n not (yet) zero
res <<= 1; // shift pattern 1 bit (i.e. pin) to the left
res |= 1; // "switch on" lowest pin
n -= 100; // defines step size (1 LED for every 100)
}
return res;
}
It takes your value and returns an int
that you can assign to the port. I.e. for 0..100 it returns 0
, for 1101..100200 it returns 1
, for 101201..200300 it returns 3
= B11
, for 201301..300400 it returns 7
= B111
and so on. (Note that it does not do any sanity checks on the input / output but that's certainly easy for you to add if needed.)
(In response to comment: Note that the bit pattern I use as example for DDRD
above is an example: It sets bit / pin 0 as input. If you use convert
you would, of course, set the lowest bit of DDRD
to 1 to make it an output.)