Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
8 years, 9 months ago.
Multiple "else if" statements to control servo
Good day, gentlemen. I think I have a problem with my "else if" statement ladder. Here is the problem - I am trying to make mbed to read a DC voltage input and based on that, to control a servo motor's rotor position. I am confident that servo itself works - I have tested it on all of the pwm1.pulsewidth ranges I need, but when I implement "else if" ladder, it does not seem to care much. Oh, and I am using quite precise voltage input with conjunction with digital multi meter, so this part is covered as well. I am using NXP LPC1768 for this project. Here is the code:
Any help would be greatly appreciated. Thank you very much.
2 Answers
8 years, 9 months ago.
I think the problem in the code is a logical error. You have a while loop. First you set PWM to 2500us, you wait 5s while that 2500us pulse is being generated.Then you check ain and set a new pulsewidth. However, as soon as the if case is finished the while loop is re-entered and the pulsewidth is reset to 2500us. There is just no time to see any change let alone give the servo a chance to move.. You need delays after setting the new value or change the logic of the code. You may also want to add some parenthesis around the ain tests to make the code more safe and replace the 'and'.with the more common 'logical and' symbol '&&'.
A switch wont do in this case since it only accepts discrete values for the cases, You would then have to do the range testing and pulsewidth setting in two steps.