Advertisement
firtel

ESP32-motor-test

Aug 27th, 2022 (edited)
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //ピンアサイン
  2. //#define EN 19
  3. #define LPWM 22
  4. #define RPWM 23
  5. int PWMMAX = 1023;
  6.  
  7. void setup() {
  8.   //PWMタイマ設定
  9.   ledcSetup(0, 20000, 10); //ch0,20kHz,10bit
  10.   ledcSetup(1, 20000, 10); //ch1,20kHz,10bit
  11.  
  12.   //PWMタイマに出力PIN関連付け
  13.   ledcAttachPin(LPWM, 0);
  14.   ledcAttachPin(RPWM, 1);
  15.  
  16.   //ENピン初期化
  17.   //pinMode(EN, OUTPUT);
  18.  
  19.   //Serial初期化
  20.   Serial.begin(115200);
  21. }
  22.  
  23. void loop() {
  24.   if (Serial.available() > 0) { // check serial
  25.     char in = Serial.read();
  26.     if (in == 'k') {
  27.       //digitalWrite(EN, LOW);
  28.       ledcWrite(0, 0);
  29.       ledcWrite(1, 0);
  30.       Serial.println("Stop Motor");
  31.     } else if (in == 'p') {
  32.       int input = Serial.parseInt();
  33.       Serial.println(input);
  34.       Serial.println("PWM control");
  35.       setMotor(input);
  36.     } else if (in == 'f') {
  37.       int input = Serial.parseInt();
  38.       Serial.println(input);
  39.       Serial.println("freqency");
  40.       ledcSetup(0, input, 10); //ch0,20kHz,10bit
  41.       ledcSetup(1, input, 10); //ch1,20kHz,10bit
  42.     } else if (in == 'h') {
  43.       PWMMAX = 1023;
  44.       Serial.println("Slow-Decay");
  45.     } else if (in == 'l') {
  46.       PWMMAX = 0;
  47.       Serial.println("Fast-Decay");
  48.     }
  49.   }
  50. }
  51.  
  52. void setMotor(int pwm) {
  53.   if (pwm == 0) { //ブレーキ
  54.     //digitalWrite(EN, HIGH);
  55.     ledcWrite(0, 1023);
  56.     ledcWrite(1, 1023);
  57.   } else if (pwm > 0 && pwm <= 1023) {
  58.     //digitalWrite(EN, HIGH);
  59.     ledcWrite(0, abs(PWMMAX - pwm));
  60.     ledcWrite(1, PWMMAX);
  61.   } else if (pwm < 0 && pwm >= -1023) {
  62.     //digitalWrite(EN, HIGH);
  63.     ledcWrite(0, PWMMAX);
  64.     ledcWrite(1, abs(pwm + PWMMAX));
  65.   }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement