有没有一种方法可以缩短它 D == 1 && C == 1 && B == 0 && A == 0只是一个像Key1这样的名字? 因为我想制作很多不同的
#include<xc.h>
#define Key1 (D==1 && C==1 && B==0 && A==0)
char K1[] = "Key 1 was pressed";
void main() {
unsigned char i;
while(DA==1){
if(Key1){
sendfunction(0b10000000);
for (i=0; K1[i]!=0; i++){
sendtext(K1[i]);
} //message
}//for loop
}
/*But if I put in this way, it works
and it will display "Key 1 was pressed"
*/
if((D==1 && C==1 && B==0 && A==0){
sendfunction(0b10000000);
for (i=0; K1[i]!=0; i++){
sendtext(K1[i]);
} //message
}//for loop
答案 0 :(得分:1)
这就是我在Visual Studio 2019上运行它的方式。据我了解,您在问如何制作宏以替换if语句。
#define KEY1(A,B,C,D) (A==0 && B==0 && C==1 && D==1) ? 1 : 0
int main(void)
{
int a = 0, b = 0, c = 1, d = 1;
if (KEY1(a, b, c, d))
printf("Key1 pressed\n");
printf("%d\n", KEY1(0, 0, 0, 0));
printf("%d\n", KEY1(0, 0, 1, 1));
return 0;
}
答案 1 :(得分:0)
我假设您的A
,B
,C
,D
是键盘上的某种输入线,您想查看按下了哪个键
如果是这种情况,并且它们只能采用值0
和1
,那么我认为将这些位组合为单个值然后使用常量进行检查会更清楚: >
#define KEY_1 0b1100
#define KEY_2 0b1010
#define KEY_3 0b1001
//...
unsigned char key = (A << 3) | (B << 2) | (C << 1) | D; // or the other way around
//now you can even use a switch
switch (key)
{
case KEY_1:
send_text1(...);
break;
case KEY_2:
send_text2(...);
break;
case KEY_3:
send_text3(...);
break;
//...
}