红外控制舵机角度
Language | English |
---|
目的通过红外遥控器控制舵机的角度。 原理利用红外接收传感器接收红外遥控器发射的红外信号,根据不同的红外信号控制舵机旋转到不同的角度。 设备
准备
调试
#include <IRremote.h>
#include <IRremoteInt.h>
#include <Servo.h>
//遥控器按键编码定义
#define INCREASE 0XFF02FD //增加+
#define DECREASE 0xFF9867 //减少-
#define NUM_0 0xFF6897 //数字0
#define NUM_1 0xFF30CF //数字1
#define NUM_2 0xFF18E7 //数字2
#define NUM_3 0xFF7A85 //数字3
#define NUM_4 0xFF10EF //数字4
#define NUM_5 0xFF38C7 //数字5
#define NUM_6 0xFF5AA5 //数字6
#define NUM_7 0xFF42BD //数字7
#define NUM_8 0xFF4AB5 //数字8
#define NUM_9 0xFF52AD //数字9
Servo myservo; // create servo object to control a servo
#define servo_pin SDA
int RECV_PIN = 10;//红外控制引脚
IRrecv irrecv(RECV_PIN);
decode_results results;
int pos = 0; // variable to store the servo position
void setup()
{
myservo.attach(servo_pin); // attaches the servo on pin 9 to the servo object
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void loop()
{
if (irrecv.decode(&results))
{
Serial.println(results.value, HEX);//打印红外编码
switch (results.value)
{
case INCREASE:
pos += 10;
if (pos > 180)
pos = 180;
break;
case DECREASE:
pos -= 10;
if (pos < 0)
pos = 0;
break;
case NUM_0:
pos = 0;
break;
case NUM_1:
pos = 20;
break;
case NUM_2:
pos = 40;
break;
case NUM_3:
pos = 60;
break;
case NUM_4:
pos = 90;
break;
case NUM_5:
pos = 100;
break;
case NUM_6:
pos = 120;
break;
case NUM_7:
pos = 140;
break;
case NUM_8:
pos = 160;
break;
case NUM_9:
pos = 180;
break;
default:
break;
}
irrecv.resume(); // Receive the next value
myservo.write(pos);
delay(1000);
}
}
软件调试
//遥控器按键编码定义
#define INCREASE 0xFFA857 //增加+
#define DECREASE 0xFFE01F //减少-
#define NUM_0 0xFF6897 //数字0
#define NUM_1 0xFF30CF //数字1
#define NUM_2 0xFF18E7 //数字2
#define NUM_3 0xFF7A85 //数字3
#define NUM_4 0xFF10EF //数字4
#define NUM_5 0xFF38C7 //数字5
#define NUM_6 0xFF5AA5 //数字6
#define NUM_7 0xFF42BD //数字7
#define NUM_8 0xFF4AB5 //数字8
#define NUM_9 0xFF52AD //数字9
if(irrecv.decode(&results)) //接收红外编码
{
switch(results.value) //判断按键
{
case INCREASE:
pos += 10;
if(pos > 180)
pos = 180;
break;
case DECREASE:
pos -= 10;
if(pos < 0)
pos = 0;
break;
case NUM_0:
pos = 0;
break;
case NUM_1:
pos = 20;
break;
case NUM_2:
pos = 40;
break;
case NUM_3:
pos = 60;
break;
case NUM_4:
pos = 90;
break;
case NUM_5:
pos = 100;
break;
case NUM_6:
pos = 120;
break;
case NUM_7:
pos = 140;
break;
case NUM_8:
pos = 160;
break;
case NUM_9:
pos = 180;
break;
default:
break;
}
irrecv.resume(); //接收下一个信号
myservo.write(pos); //舵机旋转
delay(100);
}
结果红外遥控按下不同的按键 控制舵机旋转到不同的角度。 视频 |