(In c code only, not c++)
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 <stdio.h>
void printBinary (unsigned char ch) {
int i, digit[8];
printf ("0b");
for (i = 0; i < 8; i++) {
digit[i] = (ch % 2 == 0 ? 0 : 1);
ch = ch >> 1;
}
for (i = 7; i >= 0; i--)
printf ("%d", digit[i]);
printf ("\n");
}
int main()
{
unsigned char led_reg = 0;
int menu_choice = -1;
printBinary (led_reg);
while (menu_choice != 7) {
printf ("Menu:\n");
printf ("0. Turn ON LED#4\n");
printf ("1. Turn OFF LED#4\n");
printf ("2. Add 1 to the LED Register\n");
printf ("3. Turn ON all the even numbered LEDs\n");
printf ("4. Turn OFF all the even numbered LEDs\n");
printf ("5. Toggle the state of LED#3.\n");
printf ("6. Shift the values of the LED Register right by 1\n");
printf ("7. Quit\n");
scanf ("%d[^\n]\n", &menu_choice);
switch (menu_choice) {
case 0:
led_reg |= (1 << 4);
printBinary (led_reg);
break;
case 1:
led_reg &= (0 << 4);
printBinary (led_reg);
break;
case 2:
led_reg += 1;
break;
case 3:
led_reg = led_reg | 0x55; // alternate bits set
printBinary (led_reg);
break;
case 4:
led_reg = led_reg & 0xAA;
printBinary (led_reg);
break;
case 5:
led_reg = (led_reg & 0x8) ? (led_reg & ~(0x8)) : (led_reg | 0x8);
printBinary (led_reg);
break;
case 6:
led_reg = (led_reg >> 1);
printBinary (led_reg);
break;
}
}
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.