在使用Arduino IDE编程时,为V3 NodeMCU附加中断,我有点迷失。
所以我写了这个设置代码:
void setup() {
//declare output and input pins
pinMode(D4, OUTPUT);
pinMode(D2, INPUT);
attachInterrupt(digitalPinToInterrupt(D2), buttonPressed, CHANGE);
pinMode(D7, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(D7), motionDetected, CHANGE);
//start the serial monitor (test purposes only)
Serial.begin(115200);
//initiate the EEPROM access and check stored values
EEPROM.begin(512);
getSetupVariables();
//setup the wifi connection to previous set SSID and password
setup_wifi();
//set the MQTT server to previous declared values and set the callback function
client.setServer(mqtt_server, 1883);
client.setCallback(handleMQTTCommands);
}
中断ISR是这两个功能:
void buttonPressed() {
if(!isBusy && digitalRead(D2) == HIGH) {
Serial.println("button pressed");
if(targetDoorState == DOOR_STATE_OPEN) {
initiateOperation(DOOR_STATE_CLOSED);
} else if(targetDoorState == DOOR_STATE_CLOSED) {
initiateOperation(DOOR_STATE_OPEN);
}
}
}
void motionDetected() {
char MQTT_channel[100];
char msg[100];
detachInterrupt(D7);
MQTT_CHANNEL_SET_VALUE.toCharArray(MQTT_channel, (MQTT_CHANNEL_SET_VALUE.length() + 1));
if(digitalRead(D7) == HIGH) {
Serial.println("reached");
String MQTT_PAYLOAD_OBSTRUCTION_DETECTED = "{\"name\":\"" + DEVICE_NAME + "\", \"service_name\":\"garagedoor\",\"characteristic\":\"ObstructionDetected\", \"value\":"+ DOOR_STATE_OPEN +"}";
} else if(digitalRead(D7) == LOW) {
String MQTT_PAYLOAD_OBSTRUCTION_DETECTED = "{\"name\":\"" + DEVICE_NAME + "\", \"service_name\":\"garagedoor\",\"characteristic\":\"ObstructionDetected\", \"value\":"+ DOOR_STATE_CLOSED +"}";
}
MQTT_PAYLOAD_OBSTRUCTION_DETECTED.toCharArray(msg, (MQTT_PAYLOAD_OBSTRUCTION_DETECTED.length() + 1));
client.publish(MQTT_channel, msg);
delay(500);
attachInterrupt(digitalPinToInterrupt(D7), motionDetected, CHANGE);
}
因此,在引脚D2上连接了一个按钮。 D7必须收听运动传感器的变化。但是当触发运动传感器(因此需要发生D7中断)时,D2和D7中断IRE都会被调用。有没有人有同样的问题?或者看到我在这里做错了什么?
我尝试过不同的NodeMCU板,所有这些都有这个问题。我还搜索了代码示例,但它们都实现了一个attachInterrupt
。当我评论其中一个时,它们工作得很好......
提前致谢!