Advertisement
ces-engine

pwm

Apr 7th, 2025
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #ifndef PWM_CONTROLLER_H
  2. #define PWM_CONTROLLER_H
  3.  
  4. #include "settings.h"
  5.  
  6. class PWMController {
  7. public:
  8.     PWMController() {
  9.         for (int i = 0; i < 4; i++) {  // Все 4 канала
  10.             ledcSetup(pwmChannels[i], frequencies[i], getResolution(frequencies[i]));
  11.             ledcAttachPin(pwmPins[i], pwmChannels[i]);
  12.             ledcWrite(pwmChannels[i], 0);
  13.         }
  14.     }
  15.  
  16.     void setFrequency(int channel, int freq) {
  17.         if (channel >= 0 && channel < 4 && freq >= 1 && freq <= 20000) {
  18.             frequencies[channel] = freq;
  19.             ledcSetup(pwmChannels[channel], freq, getResolution(freq));
  20.         }
  21.     }
  22.  
  23.     void setDuty(int channel, int duty) {
  24.         if (channel >= 0 && channel < 4 && duty >= 0 && duty <= 100) {
  25.             duties[channel] = duty;
  26.             int pwmValue = map(duty, 0, 100, 0, (1 << getResolution(frequencies[channel])) - 1);
  27.             ledcWrite(pwmChannels[channel], pwmValue);
  28.         }
  29.     }
  30.  
  31.  
  32. private:
  33.     int getResolution(int freq) {
  34.         if (freq < 10) return 16;
  35.         if (freq < 100) return 14;
  36.         if (freq < 1000) return 12;
  37.         return 10;
  38.     }
  39. };
  40.  
  41. #endif
  42.  
  43. ///
  44. ///settings.h
  45. ///
  46. #ifndef SETTINGS_H
  47. #define SETTINGS_H
  48.  
  49. // Пины для ШИМ
  50. const int pwmPins[] = {1, 2, 3, 10}; // GPIO
  51. const int pwmChannels[] = {0, 1, 2, 3}; // Каналы LEDC
  52.  
  53. extern int frequencies[] = {1, 100, 1000, 1000};
  54. extern int duties[] = {5, 25, 50, 100};
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement