I'm trying to create a project that involves a motor being turned on, and then turning off once it completes a single rotation, as indicated by the switch. Its easier to describe using the attached picture.
In the picture, the switch starts open because the level is in the indent of the wheel. Once the motor turns on, it depresses the switch and the switch remains pressed until the wheel completes the turn, at which point it reaches the indent again and the switch is released. At this point I would like the motor to turn off.
The switch is connected through a pull-down resistor such that when the switch is open, it is pulled to ground, but when it is closed, the switch pulls +5V. The switch is connected to a pin which I have named "motorSwitch" in the code below.
I'm trying to use the 'while' function, but I've had very inconsistent results. Sometimes it works as intended. Other times, the motor turns on and very quickly turns off. I've troubleshooted by removing the switch and manually providing +5V to the pin. When I do this carefully, the motor turns on, then I apply +5V and the motor stays on until I release the +5V, at which point it turns off. However, if I do not create good contact, the motor turns off. Based on this operation, I believe that the cause of my problem is that the switch is bouncy.
I understand the concept of debouncing a switch (take the reading about 10 ms apart and if they are the same, consider that the switch has settled), but cannot integrate this idea in the while function. The code that I am using is below:
digitalWrite(motorPin, HIGH); //power to motor circuit
while(digitalRead(motorSwitch) == LOW) {;} //while the switch is not pressed, take no action
delay(100); //once the switch has been pressed, wait 0.1 seconds
while(digitalRead(motorSwitch) == HIGH) {;} //take the reading again, while the switch is still high, take no action
digitalWrite(motorPin, LOW); //once the switch is released, turn the motor off
I think that the switch is bouncing in each of the 'while' functions, when it is reading the motorSwitch pin. Once it bounces from low, it kicks out of the while loop and continues the rest of the code, but it shouldn't.
I apologize if this is an easy question, but I am new to Arduino and programming as a whole. If you have any help on how to implement the above, that would be great. Thanks so much for your help.