#define STEP_PIN 26
#define DIR_PIN 27
#define BUTTON_PIN 33
int i_FOREWARD_STEP=1600;//正转到多少位置(脉冲)
int i_REVERSE_STEP=0;//正转到多少位置(脉冲)
// setting PWM properties
const uint8_t freq_PWM = 1000000;//设置频率,控制速度
const uint8_t channel_PWM = 0;//通道号,取值0 ~ 15
const uint8_t resolution_PWM = 10;//PWM分辨率,取值0 ~ 20
unsigned long STEP=0;
void IRAM_ATTR isr() {
//下降沿触发中断
if(digitalRead(DIR_PIN)==HIGH){
STEP++;
if(STEP>=i_FOREWARD_STEP){//到位
digitalWrite(DIR_PIN, LOW);//反转
}
}
else{
STEP--;
if(STEP<=0){//到位
ledcWriteTone(channel_PWM, 0);//停止
}
}
}
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 口上以实现输出
attachInterrupt(digitalPinToInterrupt(STEP_PIN), isr, FALLING);
}
void loop() {
// put your main code here, to run repeatedly:
if(digitalRead(BUTTON_PIN)==LOW){
delay(100);
if (digitalRead(BUTTON_PIN)==LOW){
Serial.println("RUN");
digitalWrite(DIR_PIN, HIGH);//正转
ledcWriteTone(channel_PWM, freq_PWM);
}
}
delay(10);
}