Now, let's get back to coding. You probably tried out how the dispenser works with real material in it, controlled by sending commands as 1 and 0 over the Serial Monitor. Sending two commands to manually open and close the opening is not super useful.
Let's modify our code so that the servo automatically goes back to the closed position after x milliseconds. If you use a very fine material (such as sugar), this might be something like 150 milliseconds. For grainier material (dry cat food, for example), something in the seconds might be good. Remember, we always need to specify the time in milliseconds, so 2 seconds would be 2,000 milliseconds.
Save the existing sketch as a copy with the name ch5_02_servo_serial_auto_close.
To automatically close the cap shortly after it is opened, we need to add a few new variables. Follow these steps...