2013-12-22 199 views
0

我试图将我的arduino板连接到我的RC接收器。我有接收机使用一个非常标准的4xAA包供电,并且我有一个接收器的通道连接到arduino上的端口7(我尝试了几个不同的引脚)。下面的代码只返回8000的范围内的数字(有时是9000,有时是7000),但是当我将控制从发射机应用到通道时,这并不会改变。更值得一提的是,即使从接收器拔下端口7的电线(但仍连接到arduino),数字仍会返回。这有意义吗?有什么想法吗?Arduino pulseIn返回奇怪值

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 
} 

回答

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的到期,其已经扩展了中断处理能力。但是,这应该给你如何去做的一般想法。中断功能仅适用于certain pins,这可能是pulseIn函数不适用于您的原因。

+0

这是有道理的。我会试一试。谢谢! – kschembri

+0

如果这对你有用,我会很高兴将它标记为答案。如果没有,让我们看看我们是否可以搞清楚。 – achase90

+0

嗨achase90,你的解决方案的工作原理,但真正的问题是由我的不适当的地面引起的。这是造成奇怪的数字,而不是代码本身。我投票给你,因为你的解决方案在长期运作,但不会解决眼前的问题:) – kschembri