Could I have some help getting the following code work?
My purpose is to turn on 4(or N) LEDs in a binary sequence with 4 (or N) bits, A,B,C,D. When bit=1, LED on, otherwise LED off,...
I will have 16 combinations, 2^4=16, so:
- 0000 => All leds off
- 0001 => All leds off except the one on the right
- ...
Here's the code I came up with:
int LEDblu=4;
int LEDgiallo=2;
int LEDrosso=5;
int LEDverde=7;
int num_led;
String numeri="";
String output;
int i=0;
int p;
void setup() {
// put your setup code here, to run once:
pinMode(LEDblu,OUTPUT);
pinMode(LEDgiallo,OUTPUT);
pinMode(LEDrosso,OUTPUT);
pinMode(LEDverde,OUTPUT);
Serial.begin(9600);
if(Serial.available()) //Dimmi numero LED
{
num_led=Serial.readString().toInt();
Serial.print(num_led);
}
}
void loop() {
// put your main code here, to run repeatedly:
int vect[num_led];
for(int i=num_led-1, c=0; i>=0; i--, c++)
{
int num=2^i;
vect[c]=num;
}
output="";
if(i<2^num_led)
{
p=i;
for(int c=0; c<num_led; c++) //Convert binary to decimal
{
if(p>=vect[c])
{
output+="1";
int d=vect[c];
p-=d;
}
else
output+="0";
}
Serial.println(output);
if(output[0]=="1")
digitalWrite(LEDrosso,HIGH);
else
digitalWrite(LEDrosso,LOW);
if(output[1]=="1")
digitalWrite(LEDverde,HIGH);
else
digitalWrite(LEDverde,LOW);
if(output[2]=="1")
digitalWrite(LEDgiallo,HIGH);
else
digitalWrite(LEDgiallo,LOW);
if(output[3]=="1")
digitalWrite(LEDblu,HIGH);
else
digitalWrite(LEDblu,LOW);
}
delay(1000);
i++;
}
^
is for power. For powers use pow (e.g.pow(2, num_led)
)