relayModule.c
#include <stdio.h>
#include <wiringPi.h>
#include <string.h>
#define SWIT1 26
#define SWIT2 27
#define SWIT3 28
#define SWIT4 29
int main(void)
{
char cmd[16]={'\0'};
if (wiringPiSetup() == -1){
printf("树莓派开发板初始化失败\n");
return -1;
}
pinMode(SWIT1, OUTPUT);//配置引脚gpio7 输出模式
pinMode(SWIT2, OUTPUT);
pinMode(SWIT3, OUTPUT);
pinMode(SWIT4, OUTPUT);
digitalWrite(SWIT1, HIGH);
digitalWrite(SWIT2, HIGH);
digitalWrite(SWIT3, HIGH);
digitalWrite(SWIT4, HIGH);
while(1){
printf("输入:‘on’或‘off’,on-断开开关,off-打开开关\n");
gets(cmd);
if (strcmp(cmd, "all off") == 0){
digitalWrite(SWIT1, HIGH);
digitalWrite(SWIT2, HIGH);
digitalWrite(SWIT3, HIGH);
digitalWrite(SWIT4, HIGH);
}
else if(strcmp(cmd, "all off") == 0){
digitalWrite(SWIT1, LOW);//继电器为低电平输出()
digitalWrite(SWIT2, LOW);
digitalWrite(SWIT3, LOW);
digitalWrite(SWIT4, LOW);
}
else if (strcmp(cmd, "1 off") == 0){
digitalWrite(SWIT1, HIGH);
}
else if (strcmp(cmd, "2 off") == 0){
digitalWrite(SWIT2, HIGH);
}
else if (strcmp(cmd, "3 off") == 0){
digitalWrite(SWIT3, HIGH);
}
else if (strcmp(cmd, "4 off") == 0){
digitalWrite(SWIT4, HIGH);
}
else if (strcmp(cmd, "1 on") == 0){
digitalWrite(SWIT1, LOW);
}
else if (strcmp(cmd, "2 on") == 0){
digitalWrite(SWIT2, LOW);
}
else if (strcmp(cmd, "3 on") == 0){
digitalWrite(SWIT3, LOW);
}
else if (strcmp(cmd, "4 on") == 0){
digitalWrite(SWIT4, LOW);
}
//写多个if 最后else,else只与最后一个if配对,如条件不满足最后一个if,但是前面的if,else会每次判断不满足最后if而运行
else{
printf("cmd输入错误,重新输入\n");
}
memset(cmd,'\0',sizeof(cmd));
}
return 0;
}
注意:
写多个if else if 最后else,程序会判断多次,就相当于每个if 判断一次,如;“else if” 替换成“if”
if (strcmp(cmd, "4 on") == 0){
digitalWrite(SWIT4, LOW);
}
else{
printf("cmd输入错误,重新输入\n");
}
memset(cmd,'\0',sizeof(cmd));
在这里输入的cmd满足 if (strcmp(cmd, “4 on”) == 0) 语句时,会先判断看是否满足上面的if 和 else ,如果满足进入,接下来它还会再来判断一次 if (strcmp(cmd, “4 on”) == 0) 和else
例如:你输入 1 on
输出的是:
digitalWrite(SWIT1, LOW);
printf(“cmd输入错误,重新输入\n”);