I followed the steps below which was suggested on this forum and it worked for me.
Simple solution to auto rotate failure - HTC One M9+:
Go to help app
select "tips and help", then "hardware misbehaving",
then select G-sensor test.
test it once , or twice. If it returns failed, from that...