Arduino code for counting 1 to 15 in binary using LED light
Using Condition
int lights[] = {8, 9, 10, 11};
int maxNumber = 15;
int numOfLight = sizeof(lights)/sizeof(int);
void setup() {
// put your setup code here, to run once:
for (int i = 0; i < numOfLight ; i++) {
pinMode(lights[i], OUTPUT);
}
}
void loop() {
// put your main code here, to run repeatedly:
// represent 0 to 15 with light ->
for (int i = 1; i <= maxNumber; i++) {
// for all lights
for (int j = 0; j < numOfLight ; j++) {
digitalWrite(lights[j], LOW);
if (i == 1) {
digitalWrite(lights[0], HIGH);
}
if (i == 2) {
digitalWrite(lights[1], HIGH);
}
if (i == 3) {
digitalWrite(lights[0], HIGH);
digitalWrite(lights[1], HIGH);
}
if (i == 4) {
digitalWrite(lights[2], HIGH);
}
if (i == 5) {
digitalWrite(lights[0], HIGH);
digitalWrite(lights[2], HIGH);
}
if (i == 6) {
digitalWrite(lights[1], HIGH);
digitalWrite(lights[2], HIGH);
}
if (i == 7) {
digitalWrite(lights[0], HIGH);
digitalWrite(lights[1], HIGH);
digitalWrite(lights[2], HIGH);
}
if (i == 8) {
digitalWrite(lights[3], HIGH);
}
if (i == 9) {
digitalWrite(lights[0], HIGH);
digitalWrite(lights[3], HIGH);
}
if (i == 10) {
digitalWrite(lights[1], HIGH);
digitalWrite(lights[3], HIGH);
}
if (i == 11) {
digitalWrite(lights[0], HIGH);
digitalWrite(lights[1], HIGH);
digitalWrite(lights[3], HIGH);
}
if (i == 12) {
digitalWrite(lights[2], HIGH);
digitalWrite(lights[3], HIGH);
}
if (i == 13) {
digitalWrite(lights[0], HIGH);
digitalWrite(lights[2], HIGH);
digitalWrite(lights[3], HIGH);
}
if (i == 14) {
digitalWrite(lights[1], HIGH);
digitalWrite(lights[2], HIGH);
digitalWrite(lights[3], HIGH);
}
if (i == 15) {
digitalWrite(lights[j], HIGH);
}
}
delay(1000);
}
}
Using Array of HIGH and LOW
int red = 8;
int blue = 10;
int green = 12;
int yellow = 13;
int lights[] = {red, blue, green, yellow};
int numOfLights = sizeof(lights)/sizeof(int);
int lightDelay = 500;
void setup() {
// put your setup code here, to run once:
for (int j = 0; j < numOfLights; j++) {
pinMode(lights[j], OUTPUT);
}
}
void loop() {
//go from 1 to 15
for (int x = 1; x <= 15; x++) {
// array to store the HIGH and LOW values
// 0 means low and 1 means high
int a[] = {0, 0, 0, 0};
int n = x;
// get the array values [a,b,c,d]
for (int i = 0; n > 0; i++) {
a[i] = n % 2;
n = n / 2;
}
// now we get high and low values, put them to the lights
for (int j = 0; j < numOfLights; j++) {
digitalWrite(lights[j], a[j]);
}
delay(500);
}
delay(500);
}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)