简体   繁体   中英

How can i print something on the serial monitor only once

I have a button connect to my arduino board and i want the serial monitor to display pressed when the button is pressed and released when the button is not pressed. My problem is that i want it to be print only once but with my code it prints it non stop. I already tried writing the code in void setup but i cant seem to make it work. Does anyone have any suggestions? I would really appreciate the help.

const int pinButton = 8;

void setup() {
  pinMode(pinButton, INPUT);
  Serial.begin(9600);
}

void loop() {
  int stateButton = digitalRead(pinButton);
  if(stateButton == 1) {
     Serial.println("PRESSED"); 
  } else {
     Serial.println("RELEASED"); 
  }
  delay(20);
}

this is my first answer on stack overflow. Anyway, the solution I suggest is to save previous state of the button in another variable, compare it to the new state, if they are diffrent you print the message, else you don't. Here's a code example:

const int pinButton = 8;
int previous_state;

void setup() {
   pinMode(pinButton, INPUT);
   Serial.begin(9600);
   previous_state = digitalRead(pinButton);
}

void loop() {
    int new_state = digitalRead(pinButton);
    if(new_state == 1 && previous_state==0) {
       Serial.println("PRESSED"); 
    } if(new_state == 0 && previous_state==1) {
       Serial.println("RELEASED"); 
    }
    previous_state=new_state;
    delay(20);
}

This is not the optimal solution, but it should work. Chek out interruptions on Arduino to see how to do it better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM