Arduino红外遥控风扇3挡转速代码
时间: 2023-08-13 15:17:43 浏览: 100
以下是一个基于Arduino的红外遥控风扇3挡转速代码:
```
#include <IRremote.h>
// 定义红外遥控编码
#define IR_KEY_1 0xFFA25D
#define IR_KEY_2 0xFF629D
#define IR_KEY_3 0xFFE21D
#define IR_KEY_4 0xFF22DD
#define IR_KEY_5 0xFF02FD
#define IR_KEY_6 0xFFC23D
#define IR_KEY_POWER 0xFFE01F
#define IR_KEY_MENU 0xFFA857
#define IR_KEY_PLUS 0xFF906F
#define IR_KEY_MINUS 0xFF9867
#define IR_KEY_EQ 0xFFB04F
#define IR_KEY_MODE 0xFF6897
#define IR_KEY_0 0xFF30CF
#define IR_KEY_MUTE 0xFF18E7
// 定义风扇控制引脚
#define FAN_LOW_PIN 3
#define FAN_MEDIUM_PIN 5
#define FAN_HIGH_PIN 6
// 定义风扇状态
#define FAN_OFF 0
#define FAN_LOW 1
#define FAN_MEDIUM 2
#define FAN_HIGH 3
// 定义红外遥控对象
IRrecv irrecv(2);
decode_results results;
// 初始风扇状态设为关闭
int fan_state = FAN_OFF;
void setup()
{
// 初始化串口
Serial.begin(9600);
// 初始化红外遥控
irrecv.enableIRIn();
// 设置风扇引脚为输出模式
pinMode(FAN_LOW_PIN, OUTPUT);
pinMode(FAN_MEDIUM_PIN, OUTPUT);
pinMode(FAN_HIGH_PIN, OUTPUT);
// 初始关闭风扇
digitalWrite(FAN_LOW_PIN, LOW);
digitalWrite(FAN_MEDIUM_PIN, LOW);
digitalWrite(FAN_HIGH_PIN, LOW);
}
void loop()
{
// 检测红外遥控信号
if (irrecv.decode(&results))
{
switch (results.value)
{
case IR_KEY_1: // 1键,设置风扇为低档
fan_state = FAN_LOW;
break;
case IR_KEY_2: // 2键,设置风扇为中档
fan_state = FAN_MEDIUM;
break;
case IR_KEY_3: // 3键,设置风扇为高档
fan_state = FAN_HIGH;
break;
case IR_KEY_POWER: // 开关键,关闭风扇
fan_state = FAN_OFF;
break;
default:
// 其他键不做处理
break;
}
// 根据风扇状态控制风扇转速
switch (fan_state)
{
case FAN_OFF: // 关闭风扇
digitalWrite(FAN_LOW_PIN, LOW);
digitalWrite(FAN_MEDIUM_PIN, LOW);
digitalWrite(FAN_HIGH_PIN, LOW);
break;
case FAN_LOW: // 低档转速
digitalWrite(FAN_LOW_PIN, HIGH);
digitalWrite(FAN_MEDIUM_PIN, LOW);
digitalWrite(FAN_HIGH_PIN, LOW);
break;
case FAN_MEDIUM: // 中档转速
digitalWrite(FAN_LOW_PIN, LOW);
digitalWrite(FAN_MEDIUM_PIN, HIGH);
digitalWrite(FAN_HIGH_PIN, LOW);
break;
case FAN_HIGH: // 高档转速
digitalWrite(FAN_LOW_PIN, LOW);
digitalWrite(FAN_MEDIUM_PIN, LOW);
digitalWrite(FAN_HIGH_PIN, HIGH);
break;
default:
// 非法状态,关闭风扇
fan_state = FAN_OFF;
digitalWrite(FAN_LOW_PIN, LOW);
digitalWrite(FAN_MEDIUM_PIN, LOW);
digitalWrite(FAN_HIGH_PIN, LOW);
break;
}
// 输出当前风扇状态
Serial.print("Fan state: ");
Serial.println(fan_state);
// 重置红外遥控状态
irrecv.resume();
}
}
```
注意:该代码需要使用IRremote库,可以通过Arduino IDE的“库管理器”安装。同时,需要将红外遥控接收器连接到Arduino板子的2号引脚。另外,由于风扇可能会产生噪音,建议将风扇控制引脚与风扇电源引脚分开,以避免干扰。
阅读全文