#define INCLUDE_eTaskGetState 1
#define STEP_PIN 26
#define DIR_PIN 27
#define BUTTON_PIN 33
static TaskHandle_t xTask1 = NULL;
int i_FOREWARD_STEP=1600;//前进到多少位置并返回
// setting PWM properties
const uint8_t freq_PWM = 500;//设置最高频率,控制速度
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);
vTaskDelete(xTask1);//删除task1
}
}
}
void task1(void *pt) {
Serial.println("RUN");
digitalWrite(DIR_PIN, HIGH);//正转
ledcWriteTone(channel_PWM,freq_PWM);
vTaskSuspend(NULL);//挂起任务
}
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){
if(xTaskGetHandle("task1")==NULL){
xTaskCreate(task1,
"task1",
1024,
NULL,
1,
&xTask1);
}
}
}
delay(10);
}