我的舵機的三條線是紅的、黃色、棕色,接法如下:
棕 : GND
紅 : VCC(5V)
黃:信號線(IO16)
#include <Arduino.h>
int freq = 50; // 頻率(20ms周期)
int channel = 8; // 通道(高速通道(0 ~ 7)由80MHz時鍾驅動,低速通道(8 ~ 15)由 1MHz 時鍾驅動。)
int resolution = 8; // 分辨率
const int led = 16;
int calculatePWM(int degree)
{ //0-180度
//20ms周期,高電平0.5-2.5ms,對應0-180度角度
const float deadZone = 6.4;//對應0.5ms(0.5ms/(20ms/256))
const float max = 32;//對應2.5ms
if (degree < 0)
degree = 0;
if (degree > 180)
degree = 180;
return (int)(((max - deadZone) / 180) * degree + deadZone);
}
void setup()
{
Serial.begin(9600);
ledcSetup(channel, freq, resolution); // 設置通道
ledcAttachPin(led, channel); // 將通道與對應的引腳連接
}
void loop()
{
for (int d = 0; d <= 180; d += 10)
{
ledcWrite(channel, calculatePWM(d)); // 輸出PWM
Serial.printf("value=%d,calcu=%d\n", d, calculatePWM(d));
delay(1000);
}
}
