Instruction:
Code:
- L.E.Ds act as binary 1 and 0 (LED ON=1; LED OFF= 0).
- Write a code that will continuously count from 0 to max. Each number will be displayed for 2 seconds.
Code:
/* Name: 4 bit counter.
*/
int led_1 = 1; //0th bit led pin
int led_2 = 2; //1st bit led pin
int led_3 = 3; //2nd bit led pin
int led_4 = 4; //3rd bit led pin
void setup() {
//setup the pinmode as output
pinMode(led_1, OUTPUT);
pinMode(led_2, OUTPUT);
pinMode(led_3, OUTPUT);
pinMode(led_4, OUTPUT);
}
void loop() {
//loop from 0 to max
for(int i=0; i<=15; i++) {
//switch-case for 0-max
switch(i) {
case 0:
digitalWrite(led_1, LOW);
digitalWrite(led_2, LOW);
digitalWrite(led_3, LOW);
digitalWrite(led_4, LOW);
break;
case 1:
digitalWrite(led_1, HIGH);
digitalWrite(led_2, LOW);
digitalWrite(led_3, LOW);
digitalWrite(led_4, LOW);
break;
case 2:
digitalWrite(led_1, LOW);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, LOW);
digitalWrite(led_4, LOW);
break;
case 3:
digitalWrite(led_1, HIGH);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, LOW);
digitalWrite(led_4, LOW);
break;
case 4:
digitalWrite(led_1, LOW);
digitalWrite(led_2, LOW);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, LOW);
break;
case 5:
digitalWrite(led_1, HIGH);
digitalWrite(led_2, LOW);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, LOW);
break;
case 6:
digitalWrite(led_1, LOW);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, LOW);
break;
case 7:
digitalWrite(led_1, HIGH);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, LOW);
break;
case 8:
digitalWrite(led_1, LOW);
digitalWrite(led_2, LOW);
digitalWrite(led_3, LOW);
digitalWrite(led_4, HIGH);
break;
case 9:
digitalWrite(led_1, HIGH);
digitalWrite(led_2, LOW);
digitalWrite(led_3, LOW);
digitalWrite(led_4, HIGH);
break;
case 10:
digitalWrite(led_1, LOW);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, LOW);
digitalWrite(led_4, HIGH);
break;
case 11:
digitalWrite(led_1, HIGH);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, LOW);
digitalWrite(led_4, HIGH);
break;
case 12:
digitalWrite(led_1, LOW);
digitalWrite(led_2, LOW);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, HIGH);
break;
case 13:
digitalWrite(led_1, HIGH);
digitalWrite(led_2, LOW);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, HIGH);
break;
case 14:
digitalWrite(led_1, LOW);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, HIGH);
break;
case 15:
digitalWrite(led_1, HIGH);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, HIGH);
break;
default:
//reset at default
digitalWrite(led_1, LOW);
digitalWrite(led_2, LOW);
digitalWrite(led_3, LOW);
digitalWrite(led_4, LOW);
break;
}
delay(2000); //Each number will be displayed for 2 seconds.
}
}
No comments:
Post a Comment