HI ALL, Here is my code, the main perpose is, when the IR get a single, let the servo running, to avoid more command to servo, I set global "running" to flag the servo status. but I always equal 0. why?
#define IR_RECEIVE_PIN 2
#define IR_SEND_PIN 3
#define SERVO_PIN 9 // D9 是舵机脚
#include <IRremote.hpp>
#include <Arduino.h>
#include <Servo.h>
uint8_t sAddress = 0;
uint8_t sCommand = 0x63; // 十进制 99
uint8_t rCommand = 0x58; // 十进制 88
uint8_t sRepeats = 0;
int running = 0; // set it the Servo runing.
volatile uint8_t hitData;
Servo myservo; // 创建一个舵机.
void setup() {
Serial.begin(9600); // 初始化串口通信
IrSender.begin();
IrReceiver.begin(IR_RECEIVE_PIN);
pinMode(LED_BUILTIN, OUTPUT);
attachInterrupt(digitalPinToInterrupt(IR_RECEIVE_PIN), HIT, CHANGE);
trun();
}
void HIT() {
if (IrReceiver.decode()) {
hitData = IrReceiver.decodedIRData.command;
Serial.print("Reciev.");
Serial.print(hitData);
Serial.print("....running.....");
Serial.println((int)&running,HEX);
if (hitData == rCommand && running==0) { // indicates received signal, checking it runing or not.
Serial.println("Get Drop Command....");
hitData = 0x00;
running=1; // set 1, flag it is running.
trun();
running=0; // set it back to ready to run....
}
}
IrReceiver.resume();
}
void loop() {
// Serial.print("Send.");
// Serial.println(sCommand);
IrSender.sendNEC(sAddress, sCommand, sRepeats);
delay(355);
// trun();
}
void trun() {
digitalWrite(LED_BUILTIN, HIGH);
myservo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object
// 开始旋转电机,100度
int pos = 0; // variable to store the servo position
for (int pos = 0; pos <= 60; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(12); // waits 15 ms for the servo to reach the position
}
delay(200);
for (int pos = 60; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(12); // waits 15 ms for the servo to reach the position
}
digitalWrite(LED_BUILTIN, LOW);
myservo.detach();
}