If the officer was not wearing his hat he has no official authority over you as he was out of uniform. If an officer is out of uniform he by law can't write you a ticket so I would also bring this up in court if it was the case.
Ask the judge for a Department of Motor Vehicles ID-10-t form to contest the legality of his traffic stop while out of uniform. If you have anymore questions feel free to ask. I hope this helped, I know the peanut gallery was of no help.



