【问题标题】:ESP32-WROOM-32 PWD with millisESP32-WROOM-32 PWD 带毫秒
【发布时间】:2021-10-18 11:58:46
【问题描述】:

Arduino 和 ESP-32 初学者需要帮助。

大家好, 我正在使用 Pololu - VNH5019 电机驱动器载体来控制带有 ESP32 的 12v 电机。 在下面的草图中,我可以使用 delay(); 加速和减速斜坡。 我试图用millis()归档相同的结果,但直到现在我无法做到。 我的代码中缺少什么。

提前致谢。

#define MOTOR_IN1         27
#define MOTOR_IN2         16
#define PWMPIN            14
#define frequency         40000
#define resolutionbit     8

const unsigned long eventInterval = 30;
unsigned long previousTime = 0;

void setup() {
  pinMode(MOTOR_IN1, OUTPUT);
  pinMode(MOTOR_IN2, OUTPUT);
  ledcAttachPin(PWMPIN, 0);  // assign the speed control PWM pin to a channel
  ledcSetup(0, frequency, resolutionbit);
}

void loop() {
  //with_delay();
  with_millis();
}
//------------------------------------------
void with_delay() {
  // set direction
  digitalWrite(MOTOR_IN1, HIGH);
  digitalWrite(MOTOR_IN2, LOW);

  // ramp speed up
  for (int i = 0; i <= 255; i++) {
    ledcWrite(0, i);
    delay(30);
  }
  // ramp speed down
  for (int i = 255; i >= 0; i--) {
    ledcWrite(0, i);
    delay(30);
  }
}
//-------------------------------------------
void with_millis() {
  unsigned long currentTime = millis();

  if (currentTime - previousTime >= eventInterval) {
    digitalWrite(MOTOR_IN1, HIGH);
    digitalWrite(MOTOR_IN2, LOW);
    for (int i = 0; i <= 255; i++) {
      ledcWrite(0, i);
      previousTime = currentTime;
    }
  }
  if (currentTime - previousTime >= eventInterval) {
    digitalWrite(MOTOR_IN1, HIGH);
    digitalWrite(MOTOR_IN2, LOW);
    for (int i = 255; i >= 0; i--) {
      ledcWrite(0, i);
      previousTime = currentTime;
    }
  }
}

【问题讨论】:

    标签: arduino esp32


    【解决方案1】:

    您的问题是程序卡在for loop

    • 您还需要创建direction 变量,以便程序知道要执行哪个if statement
    • 您需要创建一些其他逻辑来增加i 变量而不停止整个程序。

    代码:

    //Initialize the i variable globaly:
    int i = 0;
    bool direction = 0;
    
    
    //Your function:
    void with_millis() {
      unsigned long currentTime = millis();
    
      if ((currentTime - previousTime >= eventInterval) && direction == true) {
        digitalWrite(MOTOR_IN1, HIGH);
        digitalWrite(MOTOR_IN2, LOW);
        i++;
        if (i <= 255) {
          ledcWrite(0, i);
          previousTime = currentTime;
        } elif (i > 255) {
          i = 0;
          direction = false;
        }
      }
    
      if ((currentTime - previousTime >= eventInterval) && direction == false) {
        digitalWrite(MOTOR_IN1, LOW);
        digitalWrite(MOTOR_IN2, HIGH);
        i++;
        if (i <= 255) {
          ledcWrite(0, i);
          previousTime = currentTime;
        } elif (i > 255) {
          i = 0;
          direction = true;
        }
      }
    }
    

    【讨论】:

    • 非常感谢您的回复和帮助。这正是我试图找出的。
    猜你喜欢
    • 2021-11-29
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    相关资源
    最近更新 更多