ESP32-WROOM-32 PWD 带毫秒

ESP32-WROOM-32 PWD with millis

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;
    }
  }
}

你的问题是程序卡在了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;
    }
  }
}