r/arduino • u/stillnotfamous14 • 2d ago
Why would a print statement solves an input or timing problem?
I built a very simple system with a momentary switch that activates a linear actuator, which then goes through a sequence of motions (hence the Arduino instead of a simple switch).
My main loop has a variable that tracks the previous status of the switch and then I assign a digitalRead() to a second variable. By comparing the digitalRead to the previous status, the code only responds once to status changes (I don't know how long the user will hold the button down).
It worked, but had unexpected problems - the actuator would only complete part of its sequence and then branch into other parts or re-start its sequence. I figured the mechanical switch was bouncing or something like that, so I added in delays and so forth, but nothing solved the problem.
To try to figure it out, I added a print statement immediately after where I assign the digitalRead() status so I could see what status was being read. This was just a debug attempt, but it completely solved the problem and everything worked properly. I thought that was a coincidence, I must have made some other change somewhere so when everything was working properly, I commented out the print statement, and the timing problems came back.
I tried other variations like just doing a second digitalRead() after the first one (without printing anything) and assigning the second digitalRead() to a dummy variable, but none of those fixed the problem; the print statement seemed to clear some buffer or something.
Can anyone explain this, or is there a better way to fix the problem? Thanks.
void loop() {
buttonPush = digitalRead(buttonPin);
Serial.println(digitalRead(buttonPin)); <--- This is the debug line that fixed everything
if (buttonPush == HIGH && buttonState == LOW) { // Button released
// Go through button release sequence
}



