serial.println(" subject ") run continuously when hold a push button

hi all

I use an arduino Uno for make a project turn on led and serial monitor display " LED is ON"

const int LED1 = 13;
const int BUTTON1 = 7;
int val1 = 0;

void setup()
{
  pinMode(LED1, OUTPUT);
  pinMode(BUTTON1, INPUT);
  
  Serial.begin(9600);
}

void loop()
{
  val1 = digitalRead(BUTTON1);  
  if (val1 == HIGH)
  {
    digitalWrite(LED1, HIGH);
    Serial.println(" You have turned on the LED 1!!"); 
    delay(100);
  }
  else 
  {
    digitalWrite(LED1, LOW);       
  }

  
}

The problem is when I hold push button, the serial.print( " You have turned on the LED 1! ") run continuously. What i want is when i hold the push button, it only display " You have turned on the LED 1!" once. Please help me

The state change detection method lets you only take an action when the state of the swich changes from off to on or on to off instead of is on or is off.

Thanks. I will try on my project

A couple of thoughts:

  1. Depending on how you've got your switch wired, you might have trouble with this. If you have the switch wired to VCC on one side and the pin on the other, when the switch is open the input will float which is bad. The usual method of connecting switches is to connect one side to ground and the other to the pin and specify "INPUT_PULLUP" as the pin mode (or use an external pull-up resistor...)

  2. Switch debounce. Mechanical switches can be electrically noisy when they change from open-to-closed and closed-to-open. Because your micro is running very quickly it can read some of this noise ("bounce") and fool the logic. One way to filter this is to read the switch and then a short period of time later -- 10, 20mS or so -- read it again. If it's the same as the first read, you've probably got a valid switch press/release.

Here's your code modified for both 1 and 2 above:

const int LED1 = 13;
const int BUTTON1 = 7;
int val1 = 0;

byte
    nowSwitch,
    lastSwitch;

void setup()
{
    pinMode(LED1, OUTPUT);
    pinMode(BUTTON1, INPUT_PULLUP);
    lastSwitch = digitalRead( BUTTON1 );
    
    Serial.begin(9600);
}

void loop()
{
    nowSwitch = digitalRead(BUTTON1);
    delay(20);
    if( (digitalRead(BUTTON1) == nowSwitch) && (nowSwitch != lastSwitch) )
    {
        lastSwitch = nowSwitch;
                
        if( nowSwitch == LOW )
        {
            digitalWrite(LED1, HIGH);
            Serial.println(" You have turned on the LED 1!!"); 
            
        }//if
        else 
        {
            digitalWrite(LED1, LOW);       
            
        }//else
        
    }//if
      
}//loop