although my code works perfectly fine, I want to know if there is another simpler way to do the same thing, or if someone can help me simplify my code. I just need to have pin A0 read and have 4 leds showing the level of voltage on that pin, which is 1023 steps. Never mind the lcd.print code. they are there just for debugging.
int a0 = analogRead (A0);
int a0b= map (a0, 0, 1023, 0, 100);
int a0c= map (a0b, 0, 100, 1, 4);
lcd.setCursor (13,0);
lcd.print(a0b);
lcd.print (" ");
lcd.setCursor (13,1);
lcd.print(a0c);
lcd.print (" ");
int ledbar1[]={1,3,5,7};
if (a0c==1 || a0c>0)digitalWrite (ledbar1[0], HIGH);
else digitalWrite (ledbar1[0], LOW);
if (a0c==2 || a0c>1)digitalWrite (ledbar1[1], HIGH);
else digitalWrite (ledbar1[1], LOW);
if (a0c==3 || a0c>2)digitalWrite (ledbar1[2], HIGH);
else digitalWrite (ledbar1[2], LOW);
if (a0c==4 || a0c>3)digitalWrite (ledbar1[3], HIGH);
else digitalWrite (ledbar1[3], LOW);
thanks all for the help, here is the tested working code:
majenko:
The trick is to look at things that repeat with only small changes. In your code the following block is repeated with just a change of number:
if (a0c==1 || a0c>0)digitalWrite (ledbar1[0], HIGH);
else digitalWrite (ledbar1[0], LOW);
Replace those static numbers with a variable generated by a for loop, and you only have the block once. eg:
for (unsigned char i = 0; i < 4; i++) {
if (a0c>i)
digitalWrite (ledbar1[i], HIGH);
else
digitalWrite (ledbar1[i], LOW);
}
gateway:
Or even combine both suggestions above for even more simplicity:
for (unsigned char i = 0; i < 4; i++)
digitalWrite (ledbar1[0], (a0c>i));
(Untested, but you get where I'm going)
this is interesting, but I don't think it works, but it's still great idea. It doesn't work because the number of ledbar and a0c is not equal. using i here for both doesn't really work. and it needs a code to turn off the led when a0c is smaller. thanks for the help anyway.