KY-040 rotary middle push button switch is unreliable
As you should be able to see from the picture above, pull-up resistors are required. In addition to this the arduino sketch recommends this: -


  It has no switch debounce,  nor does it use interrupts.    A fully
  developed application might need to incorporate these in order to make
  it robust.


So, switch debounce could be a problem too. I suspect the Arduino sketch enables internal pull-up resistors on the chip BTW. I also recommend you read through the list of comments to glean any other useful information on the application of this part.

The diagram below also tells you that "both (are) open" in certain positions and this informs you that you need pull-ups or pull-downs. 



Why are they not fitted? Because they cannot know whether you want to fit pull-ups or pull-downs i.e. it is an application thing.