PWM輸出如果使用官方定義的analogWrite(),雖然可以調節想要的電壓,但除此之外就沒了
因此有人針對這個問題寫了涵式庫,但請注意這個庫只限於AVR(arduino)系列,像是STM或ESP之類的就不適用
PWM主要用途有兩個
1.調節電壓(也就是用三用電表量測會看到的)(改變工作週期就能調節電壓)
2.輸出指定的方波來做應用(要用示波器才能到)
首先請先到https://github.com/terryjmyers/PWM下載涵式庫
下面為程式範例:
#include <PWM.h>
//use pin 11 on the Mega instead, otherwise there is a frequency cap at 31 Hz
int led = 9; // GPIO
int brightness = 127; //range: 0-255,127為工作週期50%
int32_t frequency = 500; //frequency (in Hz)
void setup()
{
Serial.begin(115200);
//initialize all timers except for 0, to save time keeping functions
InitTimersSafe();
//sets the frequency for the specified pin
bool success = SetPinFrequencySafe(led, frequency);//設定腳位及頻率
Serial.print("START");
}
void loop()
{
//use this functions instead of analogWrite on 'initialized' pins
pwmWrite(led, brightness);//輸出
delay(30);
}