esp32的小车代码

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值