You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP32用millis()替代delay()实现VNH5019驱动电机缓启停求助

问题原因
  • 你在millis()的非阻塞逻辑中嵌套了完整的for循环,一旦满足30ms的时间条件,程序会一次性跑完256级调速步骤,没有实现每30ms调整一级转速的效果,等同于直接切换到最高/最低转速
  • 缺少全局状态变量记录当前所处的调速阶段(升速/降速)、当前的PWM输出值,每次进入loop()无法承接上一次的调速进度
  • previousTime更新逻辑错误,在for循环中反复赋值为同一个currentTime,导致时间判断逻辑完全失效
修正后代码
#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;
int currentPWM = 0;
bool isRampingUp = true; // 标记当前处于升速/降速阶段

void setup() {
  pinMode(MOTOR_IN1, OUTPUT);
  pinMode(MOTOR_IN2, OUTPUT);
  // 固定电机转动方向,无需重复设置
  digitalWrite(MOTOR_IN1, HIGH);
  digitalWrite(MOTOR_IN2, LOW);
  ledcAttachPin(PWMPIN, 0);
  ledcSetup(0, frequency, resolutionbit);
}

void loop() {
  with_millis();
}

void with_millis() {
  unsigned long currentTime = millis();
  if (currentTime - previousTime >= eventInterval) {
    // 仅每次调整转速时更新时间戳
    previousTime = currentTime;
    
    if (isRampingUp) {
      currentPWM++;
      // 升到最高转速后切换为降速阶段
      if (currentPWM >= 255) {
        isRampingUp = false;
      }
    } else {
      currentPWM--;
      // 降到最低转速后切换为升速阶段
      if (currentPWM <= 0) {
        isRampingUp = true;
      }
    }
    ledcWrite(0, currentPWM);
  }
}

内容的提问来源于stack exchange,提问作者Carlos Costa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:54:05