Hi @frank0707 ,
feel free to read this tutorial
https://forum.arduino.cc/t/yet-another-finite-state-machine-introduction/1198997
created by @J-M-L where you'll also find a link to this example
https://wokwi.com/projects/383745078536243201
Using a state machine makes applications like yours much easier to handle ...
Good luck!
ec2021