|
发表于 2013-6-24 22:11:56
|
显示全部楼层
本帖最后由 smching 于 2013-6-24 22:22 编辑
请参考http://forum.arduino.cc/index.php/topic,43062.0.html
- int servo1 = 2;
- unsigned long servo1_startPulse;
- volatile unsigned servo1_val;
- int servo1_Ready;
- void setup() {
- pinMode(servo1, INPUT);
- attachInterrupt(0, rc1_begin, RISING); // catch interrupt 0 (digital pin 2) going HIGH and send to rc1()
- }
- void rc1_begin() { // enter rc1_begin when interrupt pin goes HIGH.
- servo1_startPulse = micros(); // record microseconds() value as servo1_startPulse
-
- detachInterrupt(0); // after recording the value, detach the interrupt from rc1_begin
-
- attachInterrupt(0, rc1_end, FALLING); // re-attach the interrupt as rc1_end, so we can record the value when it goes low
-
- }
- void rc1_end() {
-
- servo1_val = micros() - servo1_startPulse; // when interrupt pin goes LOW, record the total pulse length by subtracting previous start value from current micros() vlaue.
-
- detachInterrupt(0); // detach and get ready to go HIGH again
-
- attachInterrupt(0, rc1_begin, RISING);
-
- if (servo1_val < 150 || servo1_val > 600) { // only set the servo1_Ready flag if the value is a valid Servo pulse between 600-2400 microseconds.
- servo1_Ready = false;
- }
- else {
- servo1_Ready = true; // if not, don't pass the value to be processed
- }
- }
- void loop() {
- Serial.print("ch1: ");
- Serial.print(servo1_val);
- Serial.print(" ");
- }
复制代码 |
|