oscillator.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #ifndef __OSCILLATOR_H__
  2. #define __OSCILLATOR_H__
  3. #include "driver/ledc.h"
  4. #include "esp_log.h"
  5. #include "freertos/FreeRTOS.h"
  6. #include "freertos/task.h"
  7. #define M_PI 3.14159265358979323846
  8. #ifndef DEG2RAD
  9. #define DEG2RAD(g) ((g) * M_PI) / 180
  10. #endif
  11. #define SERVO_MIN_PULSEWIDTH_US 500 // 最小脉宽(微秒)
  12. #define SERVO_MAX_PULSEWIDTH_US 2500 // 最大脉宽(微秒)
  13. #define SERVO_MIN_DEGREE -90 // 最小角度
  14. #define SERVO_MAX_DEGREE 90 // 最大角度
  15. #define SERVO_TIMEBASE_RESOLUTION_HZ 1000000 // 1MHz, 1us per tick
  16. #define SERVO_TIMEBASE_PERIOD 20000 // 20000 ticks, 20ms
  17. class Oscillator {
  18. public:
  19. Oscillator(int trim = 0);
  20. ~Oscillator();
  21. void Attach(int pin, bool rev = false);
  22. void Detach();
  23. void SetA(unsigned int amplitude) { amplitude_ = amplitude; };
  24. void SetO(int offset) { offset_ = offset; };
  25. void SetPh(double Ph) { phase0_ = Ph; };
  26. void SetT(unsigned int period);
  27. void SetTrim(int trim) { trim_ = trim; };
  28. void SetLimiter(int diff_limit) { diff_limit_ = diff_limit; };
  29. void DisableLimiter() { diff_limit_ = 0; };
  30. int GetTrim() { return trim_; };
  31. void SetPosition(int position);
  32. void Stop() { stop_ = true; };
  33. void Play() { stop_ = false; };
  34. void Reset() { phase_ = 0; };
  35. void Refresh();
  36. int GetPosition() { return pos_; }
  37. private:
  38. bool NextSample();
  39. void Write(int position);
  40. uint32_t AngleToCompare(int angle);
  41. private:
  42. bool is_attached_;
  43. //-- Oscillators parameters
  44. unsigned int amplitude_; //-- Amplitude (degrees)
  45. int offset_; //-- Offset (degrees)
  46. unsigned int period_; //-- Period (miliseconds)
  47. double phase0_; //-- Phase (radians)
  48. //-- Internal variables
  49. int pos_; //-- Current servo pos
  50. int pin_; //-- Pin where the servo is connected
  51. int trim_; //-- Calibration offset
  52. double phase_; //-- Current phase
  53. double inc_; //-- Increment of phase
  54. double number_samples_; //-- Number of samples
  55. unsigned int sampling_period_; //-- sampling period (ms)
  56. long previous_millis_;
  57. long current_millis_;
  58. //-- Oscillation mode. If true, the servo is stopped
  59. bool stop_;
  60. //-- Reverse mode
  61. bool rev_;
  62. int diff_limit_;
  63. long previous_servo_command_millis_;
  64. ledc_channel_t ledc_channel_;
  65. ledc_mode_t ledc_speed_mode_;
  66. };
  67. #endif // __OSCILLATOR_H__