如何在arduino每次模式更改时只打印一次

问题描述 投票:0回答:1

如何让它在每次在 Arduino 上切换模式时只打印一次。我尝试过使用我知道的各种算法,但尚未找到解决方案。如果我在更改模式时尝试打印,它将连续打印

algorithm loops for-loop if-statement arduino
1个回答
0
投票

您可以使用标志变量来跟踪自上次打印以来模式是否已更改。

// Define pin numbers for mode switch
const int modeSwitchPin = 2;

// Define variables to store current and previous mode
int currentMode = 0;
int previousMode = 0;

// Define a flag variable to track if mode has changed
bool modeChanged = false;

void setup() {
  // Initialize serial communication
  Serial.begin(9600);

  // Set mode switch pin as input
  pinMode(modeSwitchPin, INPUT_PULLUP);

  // Read initial mode
  currentMode = digitalRead(modeSwitchPin);
}

void loop() {
  // Read current mode
  currentMode = digitalRead(modeSwitchPin);

  // Check if mode has changed
  if (currentMode != previousMode) {
      // Mode has changed
      modeChanged = true;
      previousMode = currentMode;
  } else {
      // Mode hasn't changed
      modeChanged = false;
  }

  // If mode has changed, print message
  if (modeChanged) {
      Serial.println("Mode has changed!");
  }

  // Add other code related to your modes here

  // Delay for stability
  delay(100);
}
© www.soinside.com 2019 - 2024. All rights reserved.