Самый простой способ - добавить переменную, которая хранит состояние кнопки.
Когда вы нажимаете кнопку, эта переменная устанавливается в значение true и запускается нужный код.Хотя эта переменная имеет значение true, написанный вами код не будет выполнен во второй раз.Когда вы отпустите кнопку, для переменной будет установлено значение false, поэтому при следующем нажатии кнопки ваш код будет выполнен снова.
Код:
bool isPressed = false; // the button is currently not pressed
void loop ()
{
if (digitalRead(btn) == LOW) //button is pressed
{
if (!isPressed) //the button was not pressed on the previous loop (!isPressed means isPressed == FALSE)
{
isPressed = true; //set to true, so this code will not run while button remains pressed
ledValue = !ledValue;
digitalWrite(ledPin, ledValue);
Serial.println(digitalRead(ledPin));
}
}
else
{
isPressed = false;
// the button is not pressed right now,
// so set isPressed to false, so next button press will be handled correctly
}
}
Редактировать: добавлен второй пример
const int btn = 5;
const int ledPin = 3;
int ledValue = LOW;
boolean isPressed = false;
void setup(){
Serial.begin(9600);
pinMode(btn, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop ()
{
if (digitalRead(btn) == LOW && isPressed == false ) //button is pressed AND this is the first digitalRead() that the button is pressed
{
isPressed = true; //set to true, so this code will not run again until button released
doMyCode(); // a call to a separate function that holds your code
} else if (digitalRead(btn) == HIGH)
{
isPressed = false; //button is released, variable reset
}
}
void doMyCode() {
ledValue = !ledValue;
digitalWrite(ledPin, ledValue);
Serial.println(digitalRead(ledPin));
}