【ESP32】 利用按钮控制舵机的旋转

使用ESP32Servo函数库

#include <Arduino.h>
#include<ESP32Servo.h>

Servo myservo; 
const int duoji = 26; //设置舵机引脚为26
const int botton = 12; //设置按钮引脚为12
void setup() {

  myservo.attach(duoji);
}
void loop() {

  int bottonstate = digitalRead(botton);
  if (bottonstate == HIGH){
    myservo.write(90);  
  }
  else{
    myservo.write(0);  

  }

不使用库函数

#include <Arduino.h>

int freq = 50;
int channel = 8;
int resolution = 8;
const int led = 13;
const int botton = 12;
int calculatePWM(int degree) //定义函数用于输出PWM的占空比
{ //0-180度
 //20ms周期内,高电平持续时长0.5-2.5ms,对应0-180度舵机角度,参考上面的180度对应图。
  const float deadZone = 6.4;//对应0.5ms(0.5ms/(20ms/256))
  const float max = 32;//对应2.5ms(2.5ms/(20ms/256))
  if (degree < 0)
    degree = 0;
  if (degree > 180)
    degree = 180;
  return (int)(((max - deadZone) / 180) * degree + deadZone); //返回度数对应的高电平的数值
}


void setup() {
  pinMode(botton, INPUT);
  Serial.begin(9600);
  ledcSetup(channel, freq, resolution);
  ledcAttachPin(led, channel);
  int bottonstate = 0;
}

void loop() {

  int bottonstate = digitalRead(botton);
  if (bottonstate == HIGH){
    ledcWrite(channel, calculatePWM(90)); // 输出PWM,设置 LEDC 通道的占空比。
  }
  else{
    ledcWrite(channel, calculatePWM(0));
  }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值