我正在尝试将我的arduino板连接到RC接收器。我的接收器使用非常标准的4xAA电池供电,我有一个接收器的通道连接到arduino上的端口7(为此尝试了几个不同的引脚)。下面的代码只返回8000范围内的数字(有时是9000,有时是7000),但是当我将控制器从发送器应用到通道时,这不会改变。更奇怪的是,即使从接收器拔出端口7的电线(但仍然连接到arduino),数字也会返回。这有意义吗?有什么想法吗?
int pin = 7;
unsigned long duration;
void setup()
{
pinMode(pin, INPUT);
Serial.begin(9600); // Pour a bowl of Serial
}
void loop()
{
duration = pulseIn(pin, LOW);
Serial.print("Channel 1:"); // Print the value of
Serial.println(duration); // each channel
}
答案 0 :(得分:1)
为了澄清,您想测量R / C接收器输出信号的脉冲宽度吗?为此,您需要使用中断。我这样做的方式如下:
volatile int16_t pwm = 0; //pwm value
volatile int16_t trig = 0; //timer value
#define pin 7 //pin the interrupt is attached to
void intHandler() //function to call on interrupt
{
if(digitalRead(pin)) //if the pin is HIGH, note the time
{
trig = micros();
}
else
{
pwm = micros()-trig; //if it is low, end the time
}
}
void setup(){
pinMode(pin, INPUT); //set the pin to input
attachInterrupt(pin,intHandler,CHANGE); //attach the interrupt function "intHandler" to "pin" whenever the state changes
Serial.begin(9600); //begin serial comms
}
void loop()
{
Serial.print("PWM = ");
Serial.println(pwm);
}
请注意,这可能仅适用于Arduino Due,它具有扩展的中断处理能力。但是,这应该让您了解如何做到这一点。中断功能仅在certain pins上可用,这可能就是为什么pulseIn功能不适合你。