// the number of the PWM pin
const int pwmA = 22; //通道A的PWM引脚
const int motorPinA1 = 16; //通道A的控制引脚
const int motorPinA2 = 17;
const int pwmB = 23; //通道B的PWM引脚
const int motorPinB1 = 18; //通道B的控制引脚
const int motorPinB2 = 19;
// setting PWM properties
const int freq = 5000; //PWM频率
int channelA = 0; //PWM通道0
int channelB = 1; //PWM通道1
int resolution = 8; //PWM的分辩率
int sensorValue1;
int sensorValue2;
void setup(){
Serial.begin(9600);
pinMode(motorPinA1, OUTPUT);
pinMode(motorPinA2, OUTPUT);
pinMode(motorPinB1, OUTPUT);
pinMode(motorPinB2, OUTPUT);
// configure LED PWM functionalitites
ledcSetup(channelA, freq, resolution); //设置PWM控制器
ledcSetup(channelB, freq, resolution); //设置PWM控制器
// attach the channel to the GPIO to be controlled
ledcAttachPin(pwmA, channelA); //将PWM控制器A绑定于22引脚//left
ledcAttachPin(pwmB, channelB); //将PWM控制器B绑定于23引脚//right
}
void loop(){
/*analogRead(pin)函数用于读取引脚的模拟量电压值,参数pin表示所要获取模拟量电压值的引脚,返回值为0~1023;*/
sensorValue1 = analogRead(34);
sensorValue2 = analogRead(35);
// increase the LED brightness
ledcWrite(channelA, 200); //设定PWMA控制器的占空比
ledcWrite(channelB, 200); //设定PWMB控制器的占空比
Serial.printf("%d\t\t%d\n",sensorValue1,sensorValue2);
if(sensorValue1<1500&&sensorValue2<1500)//前进
{
digitalWrite(motorPinA1, HIGH);
digitalWrite(motorPinA2, LOW);
digitalWrite(motorPinB1, HIGH);
digitalWrite(motorPinB2, LOW);
}
else if(sensorValue1>1500&&sensorValue2>1500)//后退
{
digitalWrite(motorPinA1, LOW);
digitalWrite(motorPinA2, HIGH);
digitalWrite(motorPinB1, LOW);
digitalWrite(motorPinB2, HIGH);
}
else if(sensorValue1<1500&&sensorValue2>1500)//右转
{
digitalWrite(motorPinA1, HIGH);
digitalWrite(motorPinA2, LOW);
digitalWrite(motorPinB1, LOW);
digitalWrite(motorPinB2, HIGH);
}
else if(sensorValue1>1500&&sensorValue2<1500)//左转
{
digitalWrite(motorPinA1, LOW);
digitalWrite(motorPinA2, HIGH);
digitalWrite(motorPinB1, HIGH);
digitalWrite(motorPinB2, LOW);
}
}
esp32的小车代码
最新推荐文章于 2024-08-05 15:24:51 发布