Hopefully this tutorial will help you get the concept of a state machine. You'll need to decide on a good way to sense the top and bottom positions.