使用ESP32Servo
函数库
#include <Arduino.h>
#include<ESP32Servo.h>
Servo myservo;
const int duoji = 26;
const int botton = 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)
{
const float deadZone = 6.4;
const float max = 32;
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));
}
else{
ledcWrite(channel, calculatePWM(0));
}
}