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

相关内容

  • 没有找到相关文章

最新更新