根据题主的描述编写了下面的小程序。首先是程序的部分截图:
在代码led.c中各函数功能描述如下:
① void pwr_all_on(void)是开启16盏LED。
② void pwr_all_off(void)是关闭16盏LED。
③ void print_led_state(void)的依次描述16盏LED灯的状态。
④ int get_led(int led_no)是获取指定次序(1~16号)LED灯的状态。返回值为1,表示灯开启;返回值为0,表示灯关闭。
⑤ void set_led(int led_no, int state)用于设置指定次序(1~16号)LED灯的状态。
int led_no表示LED次序
int state表示LED灯状态。1表示LED开启,0表示LED关闭。
最后是led.c中的源代码:
-------------------------------led.c-------------------------------------------
#include
#include
#include
// 表示LED灯的状态
#define POWER_ON (1)
#define POWER_OFF (0)
// LED各位依次有电的状态
static uint16_t pwr_on[16] = {
0x1, 0x2, 0x4, 0x8,
0x10,0x20, 0x40, 0x80,
0x100, 0x200, 0x400, 0x800,
0x1000, 0x2000, 0x4000, 0x8000
};
// LED各位依次无电的状态
static uint16_t pwr_off[16] = {
0xfffe, 0xfffd, 0xfffb, 0xfff7,
0xffef, 0xffdf, 0xffbf, 0xff7f,
0xfeff, 0xfdff, 0xfbff, 0xf7ff,
0xefff, 0xdfff, 0xbfff, 0x7fff
};
// 在不同的软硬件平台上,char、int、long等的存储空间并不一致,
// 因而为了确定使用的是16位存储空间,我使用了stdint.h中的uint16_t
// 表示16位无符号整形。
// led_state表示16盏LED灯,其中第0位表示LED1,
// 第1位表示LED2,以此类推
static uint16_t led_state = 0xffff;
// 用于设置led_state状态
// int led_no表示LED灯的序号,有效范围1~16
// int state表示灯的状态。取值POWER_ON或POWER_OFF
void set_led(int led_no, int state);
// 获取特定LED灯的状态
// 返回值为POWER_ON或者POWER_OFF
// int led_no为指定的LED灯序号。有效值为1~16
int get_led(int led_no);
// 依次描述16盏LED的状态
void print_led_state(void);
// 开启所有的LED灯
void pwr_all_on(void);
// 关闭所有的LED灯
void pwr_all_off(void);
int main(void) {
printf("power all on\n");
pwr_all_on();
print_led_state();
printf("\npower off LED 16\n");
set_led(16, POWER_OFF);
printf("power off LED 1\n");
set_led( 1, POWER_OFF);
print_led_state();
printf("\npower all off\n");
pwr_all_off();
print_led_state();
return 0;
}
void set_led(int led_no, int state) {
if (led_no < 1 || led_no > 16) {
fputs("The specificed LED number is unavailable and "
"the effective range is from 1 to 16.\n", stderr);
exit(0);
}
uint16_t set_token;
if(POWER_ON == state) {
led_state |= pwr_on[led_no-1];
} else if (POWER_OFF == state) {
led_state &= pwr_off[led_no-1];
} else {
fputs("The state of LED is unavailable and "
"the effective range is 0 or 1.\n", stderr);
exit(0);
}
}
int get_led(int led_no) {
if (led_no < 1 || led_no > 16) {
fputs("The specificed LED number is unavailable and "
"the effective range is from 1 to 16.\n", stderr);
exit(0);
}
int state = led_state & pwr_on[led_no-1];
if (state) {
state = POWER_ON;
} else {
state = POWER_OFF;
}
return state;
}
void print_led_state(void) {
int i;
printf("LED state:\n");
for (i=1; i<=16; i++) {
if (POWER_ON == get_led(i)) {
printf("\tLED %2d is power on.\n", i);
} else {
printf("\tLED %2d is power off.\n", i);
}
}
}
void pwr_all_on(void) {
led_state = ~(led_state ^ led_state);
}
void pwr_all_off(void) {
led_state ^= led_state;
}