In: Computer Science
Assignment (C language)
We will simulate the status of 8 LEDs that are connected to a microcontroller. Assume that the state of each LED (ON or OFF) is determined by each of the bits (1 or 0) in an 8-bit register (high-speed memory).
HINTS:
Here is the code:
#include <bits/stdc++.h>
using namespace std;
void printBinary(char);
int main()
{
char led_reg = '0';
while(1){
printBinary(led_reg);
cout<<"\n0. Turn ON LED #4
.\n";
cout<<"1. Turn OFF LED #4
.\n";
cout<<"2. Add 1 to the LED
Register .\n";
cout<<"3. Turn ON all the
even numbered LEDs .\n";
cout<<"4. Turn OFF all the
even numbered LEDs .\n";
cout<<"5. Toggle the state of
LED #3 .\n";
cout<<"6. Shifte the values
of the LED Register right by 1 .\n";
cout<<"7. Quit.\n";
int choice;
cin>>choice;
switch(choice)
{
case 0:
led_reg = (led_reg | (1 << 2));
// All the bits
that we count are from left side to right
break;
//but the operations are performed in opposite
dxn
case
1:
// so we do 7-i-1 for the ith bit from
left
led_reg = (led_reg & ~(1 << 2));
//hence we use 2 for 4 as
7-4-1=2
break;
case 2:
led_reg++;
break;
case 3:
for(int i = 0;i<8; i++){
if(i%2==0){
led_reg =
(led_reg | (1 << i));
}
}
break;
case 4:
for(int j = 0;j<8; j++){
if(j%2==0){
led_reg =
(led_reg & ~(1 << j));
}
}
break;
case 5:
led_reg = (led_reg ^ (1 << (5)));
break;
case 6:
led_reg = led_reg>>1;
break;
case 7:
exit(0);
break;
default:
cout<<"Invalid Choice!!\n Try
agin\n";
}
}
return 0;
}
void printBinary(char c){
/* step 1 */
if (c > 1)
printBinary(c/2);
/* step 2 */
cout << c % 2;
}