#define STEP_PIN 26
#define DIR_PIN 27
#define BUTTON_PIN 33
int i_FOREWARD_STEP=1600;//正转多少脉冲
int i_REVERSE_STEP=1600;//反转多少脉冲
// setting PWM properties
const uint8_t freq_PWM = 500;//设置频率,控制速度
const uint8_t channel_PWM = 0;//通道号,取值0 ~ 15
const uint8_t resolution_PWM = 8;//PWM分辨率,取值0 ~ 20
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(DIR_PIN, OUTPUT);
ledcSetup(channel_PWM, freq_PWM, resolution_PWM); // 设置通道
ledcAttachPin(STEP_PIN, channel_PWM); //将 LEDC 通道绑定到指定 IO 口上以实现输出
}
void loop() {
// put your main code here, to run repeatedly:
if(digitalRead(BUTTON_PIN)==LOW){
delay(300);
if (digitalRead(BUTTON_PIN)==LOW){
digitalWrite(DIR_PIN, HIGH);//正转
// 1/频率*1000=毫秒
float ms=1.0/freq_PWM*1000.0*i_FOREWARD_STEP;
Serial.printf("%f",ms);
ledcWrite(channel_PWM, 50);
double intPart;
double fracPart=modf(ms, &intPart);
delay(intPart);
delayMicroseconds(fracPart*1000);
digitalWrite(DIR_PIN, LOW);//反转
ms=1.0/freq_PWM*1000.0*i_REVERSE_STEP;
intPart=0;
fracPart=modf(ms, &intPart);
delay(intPart);
delayMicroseconds(fracPart*1000);
ledcWrite(channel_PWM, 0);
}
}
delay(10);
}