如何仅在状态更改时执行操作?

How to perform an action only when a state is changed?

基本上,当蓝牙连接状态为 CONNECTED 时,我想让我的红外 LED 发送 一个 代码。当连接状态变为 DISCONNECTED 时,红外灯应发送一次不同的代码。但是,我的代码不断发送一个 IR 代码。当蓝牙状态发生变化时,会不断发送另一个红外码。

如何将我的代码更改为每次蓝牙连接状态更改时只发送一个 IR 代码?

#include "BluetoothA2DPSink32.h"
#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRsend.h>

const uint16_t kIrLed = 2; 
IRsend irsend(kIrLed);
const uint16_t rawData[71] = {9004, 4556,  534, 602,  506, 654,  490, 624,  514, 1762,  490, 1764,  486, 1768,  516, 1762,  490, 626,  516, 622,  486, 1770,  514, 1762,  492, 1762,  486, 654,  490, 624,  514, 622,  486, 652,  490, 626,  514, 622,  488, 632,  512, 626,  512, 602,  532, 628,  490, 626,  514, 622,  486, 1770,  514, 1744,  510, 1742,  508, 1768,  516, 1762,  490, 1764,  512, 1744,  514, 1762,  492, 41344,  9022, 2298,  508};
const uint16_t rawData2[71] = {9022, 4574,  518, 622,  486, 654,  490, 628,  512, 1762,  490, 1764,  486, 1770,  514, 1762,  490, 626,  514, 622,  488, 1768,  514, 1762,  490, 1744,  506, 654,  490, 624,  516, 622,  486, 652,  492, 1764,  486, 1768,  516, 622,  488, 652,  490, 624,  516, 622,  488, 652,  490, 626,  514, 622,  488, 654,  490, 1764,  486, 1770,  514, 1762,  490, 1764,  486, 1770,  514, 1764,  490, 41360,  9006, 2318,  488};

BluetoothA2DPSink32 a2dp_sink;

void setup() {
  irsend.begin();
  a2dp_sink.set_bits_per_sample(32);  
  a2dp_sink.start("Hifi32bit");   
}

void loop() {
  if (a2dp_sink.get_connection_state()==ESP_A2D_CONNECTION_STATE_CONNECTED) {
    irsend.sendRaw(rawData, 71, 38);
  }

  if (a2dp_sink.get_connection_state()==ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
    irsend.sendRaw(rawData2, 71, 38);
  }
}

问题是您正在连续执行检查,对于每次检查,您都执行 if-您在其中发送 IR 代码的语句。因此,您的应用程序将尽可能快地发送 IR 代码。

如果您只想在状态更改时发送操作(发送 IR 代码),您应该记住状态,并在状态更改时执行操作 代替。

这很容易通过添加变量previous_connection_state来实现。下面的示例代码(这将替换您当前代码中的 loop())。

esp_a2d_connection_state_t previous_connection_state;

void loop() {
    esp_a2d_connection_state_t connection_state = a2dp_sink.get_connection_state();

    if (connection_state != previous_connection_state) {

        if (connection_state == ESP_A2D_CONNECTION_STATE_CONNECTED) {
            irsend.sendRaw(rawData, 71, 38);
        }

        if (connection_state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
            irsend.sendRaw(rawData2, 71, 38);
        }

        previous_connection_state = connection_state;
    }
}