servos.ino 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**********************************************************************
  2. Copyright: 2016-2019 ROS小课堂 www.corvin.cn
  3. Author: corvin
  4. Description:
  5. Sweep servos one degree step at a time with a user defined
  6. delay in between steps. Supports changing direction mid-sweep.
  7. History:
  8. 20181225: initial this code.
  9. **********************************************************************/
  10. // Constructor function
  11. SweepServo::SweepServo()
  12. {
  13. this->currentPosDegrees = 0;
  14. this->targetPosDegrees = 0;
  15. this->lastMoveTime = 0;
  16. }
  17. // Init servo params, default all servos disabled.
  18. void SweepServo::initServo(byte servoPin, unsigned int initPosition, unsigned int stepDelayMs)
  19. {
  20. this->servo.attach(servoPin);
  21. this->stepDelayMs = stepDelayMs;
  22. this->currentPosDegrees = initPosition;
  23. this->targetPosDegrees = initPosition;
  24. this->lastMoveTime = millis();
  25. this->enabled = SERVO_DISABLE;
  26. this->servo.write(initPosition); //when power on, move all servos to initPosition
  27. }
  28. //Servo Perform Sweep
  29. void SweepServo::moveServo(void)
  30. {
  31. // Get ellapsed time from last cmd time to now.
  32. unsigned int delta = millis() - this->lastMoveTime;
  33. // Check if time for a step
  34. if (delta > this->stepDelayMs)
  35. {
  36. // Check step direction
  37. if (this->targetPosDegrees > this->currentPosDegrees)
  38. {
  39. this->currentPosDegrees++;
  40. this->servo.write(this->currentPosDegrees);
  41. }
  42. else if (this->targetPosDegrees < this->currentPosDegrees)
  43. {
  44. this->currentPosDegrees--;
  45. this->servo.write(this->currentPosDegrees);
  46. }
  47. // if target == current position, do nothing
  48. // reset timer, save current time to last cmd time.
  49. this->lastMoveTime = millis();
  50. }
  51. }
  52. // Set a new target position with step delay param.
  53. void SweepServo::setTargetPos(unsigned int targetPos, unsigned int stepDelayMs)
  54. {
  55. this->targetPosDegrees = targetPos;
  56. this->stepDelayMs = stepDelayMs;
  57. }
  58. byte SweepServo::getCurrentPos(void)
  59. {
  60. return this->currentPosDegrees;
  61. }
  62. void SweepServo::setEnable(byte flag)
  63. {
  64. if (flag == SERVO_ENABLE)
  65. {
  66. this->enabled = SERVO_ENABLE;
  67. }
  68. else
  69. {
  70. this->enabled = SERVO_DISABLE;
  71. }
  72. }
  73. byte SweepServo::isEnabled(void)
  74. {
  75. return this->enabled;
  76. }
  77. // Accessor for servo object
  78. Servo SweepServo::getServoObj()
  79. {
  80. return this->servo;
  81. }