servos.ino 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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.
  7. History:
  8. 20181121: initial this code.
  9. 20181130: 新增获取和设置舵机使能状态的函数。
  10. 20181204: 删除了舵机的disable函数,使用enable来实现。新增了getCurrentPos()
  11. 函数,用户获取当前舵机的角度。
  12. **********************************************************************/
  13. // Constructor function
  14. SweepServo::SweepServo()
  15. {
  16. this->currentPosDegrees = 0;
  17. this->targetPosDegrees = 0;
  18. this->lastMoveTime = 0;
  19. }
  20. // Init servo params, default all servos disabled.
  21. void SweepServo::initServo(int servoPin, unsigned int initPosition, unsigned int stepDelayMs)
  22. {
  23. this->servo.attach(servoPin);
  24. this->stepDelayMs = stepDelayMs;
  25. this->currentPosDegrees = initPosition;
  26. this->targetPosDegrees = initPosition;
  27. this->lastMoveTime = millis();
  28. this->enabled = SERVO_DISABLE;
  29. this->servo.write(initPosition); //when power on, move all servos to initPosition
  30. }
  31. //Servo Perform Sweep
  32. void SweepServo::moveServo(void)
  33. {
  34. // Get ellapsed time from last cmd time to now.
  35. unsigned int delta = millis() - this->lastMoveTime;
  36. // Check if time for a step
  37. if (delta > this->stepDelayMs)
  38. {
  39. // Check step direction
  40. if (this->targetPosDegrees > this->currentPosDegrees)
  41. {
  42. this->currentPosDegrees++;
  43. this->servo.write(this->currentPosDegrees);
  44. }
  45. else if (this->targetPosDegrees < this->currentPosDegrees)
  46. {
  47. this->currentPosDegrees--;
  48. this->servo.write(this->currentPosDegrees);
  49. }
  50. // if target == current position, do nothing
  51. // reset timer, save current time to last cmd time.
  52. this->lastMoveTime = millis();
  53. }
  54. }
  55. // Set a new target position with step delay param.
  56. void SweepServo::setTargetPos(unsigned int targetPos, unsigned int stepDelayMs)
  57. {
  58. this->targetPosDegrees = targetPos;
  59. this->stepDelayMs = stepDelayMs;
  60. }
  61. int SweepServo::getCurrentPos(void)
  62. {
  63. return this->currentPosDegrees;
  64. }
  65. void SweepServo::setEnable(byte flag)
  66. {
  67. if (flag == SERVO_ENABLE)
  68. {
  69. this->enabled = SERVO_ENABLE;
  70. }
  71. else
  72. {
  73. this->enabled = SERVO_DISABLE;
  74. }
  75. }
  76. byte SweepServo::isEnabled(void)
  77. {
  78. return this->enabled;
  79. }
  80. // Accessor for servo object
  81. Servo SweepServo::getServoObj()
  82. {
  83. return this->servo;
  84. }