#include <LiquidCrystal_I2C.h>
int columns = 16;
int rows = 2;
LiquidCrystal_I2C lcd(0x27, columns, rows);
// define pin led
const int led0 = 3;
const int led1 = 4;
const int led2 = 5;
const int led3 = 6;
const int led4 = 7;
const int led5 = 8;
const int led6 = 9;
const int led7 = 10;
const int led8 = 11;
const int led9 = 12;
// defines led states
int st0 = LOW;
int st1 = LOW;
int st2 = LOW;
int st3 = LOW;
int st4 = LOW;
int st5 = LOW;
int st6 = LOW;
int st7 = LOW;
int st8 = LOW;
int st9 = LOW;
int number = 0;
int previousNumber = number;
void setup() {
// put your setup code here, to run once:
pinMode(led0, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(led5, OUTPUT);
pinMode(led6, OUTPUT);
pinMode(led7, OUTPUT);
pinMode(led8, OUTPUT);
pinMode(led9, OUTPUT);
pinMode(2, INPUT);
lcd.begin(16,2);
lcd.init();
lcd.backlight();
number = 1;
}
void controlLEDState() {
digitalWrite(3,st0);
digitalWrite(4,st1);
digitalWrite(5,st2);
digitalWrite(6,st3);
digitalWrite(7,st4);
digitalWrite(8,st5);
digitalWrite(9,st6);
digitalWrite(10,st7);
digitalWrite(11,st8);
digitalWrite(12,st9);
}
void clearLED() {
digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
digitalWrite(11,LOW);
digitalWrite(12,LOW);
}
void setLed(int itr, bool yes) {
int whathi = LOW;
if (yes) {
whathi = HIGH;
} else {
whathi = LOW;
}
if (itr==1) {
st0 = whathi;
} else if (itr==2) {
st1 = whathi;
} else if (itr==3) {
st2 = whathi;
} else if (itr==4) {
st3 = whathi;
} else if (itr==5) {
st4 = whathi;
} else if (itr==6) {
st5 = whathi;
} else if (itr==7) {
st6 = whathi;
} else if (itr==8) {
st7 = whathi;
} else if (itr==9) {
st8 = whathi;
} else if (itr==10) {
st9 = whathi;
}
}
int decimalToBinary(int num) {
int decimal;
int a = num;
int logx=0;
// logx is the number of digits a binary number has.
// up to 10 because of the amount of leds.
if (a<2) {
logx=1;
} else if (a<4) {
logx=2;
} else if (a<8) {
logx=3;
} else if (a<16) {
logx=4;
} else if (a<32) {
logx=5;
} else if (a<64) {
logx=6;
} else if (a<128) {
logx=7;
} else if (a<256) {
logx=8;
} else if (a<512) {
logx=9;
} else if (a<1024) {
logx=10;
} else {
logx = 11;
}
// loop until the n-th loop, where n is the log base 2 of num.
for (int i = 0; i <= logx; i++) {
// divide a (num) by 2, see if there is a remainder, if not,
// the i-th digit is 0, where i=1 equals the ones place, and i=10 equal the 10^9th place
if (a % 2 == 0) {
// set digit to 0
setLed(i+1,false);
} else {
// set digit to 1
setLed(i+1,true);
}
if (a >= 2) {
a = floor(a / 2);
} else {
break;
}
}
return decimal;
}
void test() {
decimalToBinary(number);
controlLEDState();
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(2) == HIGH) {
decimalToBinary(number);
controlLEDState();
lcd.setCursor(0,0);
lcd.print(number);
delay(300);
number++;
}
}