今天嘗試使用PWM控制led和電機(jī),按照教程寫下如下程序:
int ledPin = 2; // 設(shè)定控制 LED 的數(shù)字 IO 腳
int val; //定義一個(gè)變量
void setup()
{
? pinMode(ledPin, OUTPUT); // 設(shè)定數(shù)字 IO 口的模式贱傀, OUTPUT 為輸出
}
void loop()
{
? for(val=0;val<255;val++) //變量循環(huán)+1
? {
? ? analogWrite(ledPin, val); //PWM 輸出
? ? delay(50); //設(shè)定延時(shí)時(shí)間
? }
? for(val=255;val>0;val--) //變量循環(huán)-1
? {
? ? analogWrite(ledPin, val);
? ? delay(50);
? }
}
編譯的時(shí)候提示error: 'analogWrite' was not declared in this scope
經(jīng)多方查找以后發(fā)現(xiàn)esp32中并未實(shí)現(xiàn)analogWrite方法轴合,詳見(jiàn)analogWrite() not implemented?#4
官方說(shuō)法是這個(gè)函數(shù)正在搞,暫時(shí)可以用下面三個(gè)方法實(shí)現(xiàn)PWM:
16 channels?LEDC?which is PWM
8 channels?SigmaDelta?which uses SigmaDelta modulation
2 channels?DAC?which gives real analog output
下面是2個(gè)例子平酿,分別使用SigmaDelta 和 LEDC
1凤优、使用PWM:SigmaDelta實(shí)現(xiàn)呼吸燈效果,PIN2
int ledPin=2;
int val;
void setup() {
? //設(shè)置 channel 0 頻率為 312500 Hz
? ? sigmaDeltaSetup(0, 312500);
? ? //IO口 pin 18 附加到 channel 0
? ? sigmaDeltaAttachPin(ledPin,0);
? ? //channel 0 初始狀態(tài)為關(guān)閉
? ? sigmaDeltaWrite(0, 0);
}
void loop() {
? for(val=0;val<255;val++)
? {
? ? sigmaDeltaWrite(0,val);
? ? delay(50);
? }
? for(val=255;val>0;val--)
? {
? ? sigmaDeltaWrite(0,val);
? ? delay(50);
? }
}
2蜈彼、使用LEDC控制led和電機(jī)
// use first channel of 16 channels (started from zero)
#define LEDC_CHANNEL_0? ? 0
// use 13 bit precission for LEDC timer
#define LEDC_TIMER_13_BIT? 13
// use 5000 Hz as a LEDC base frequency
#define LEDC_BASE_FREQ? ? 20000
// fade LED PIN (replace with LED_BUILTIN constant for built-in LED)
#define LED_PIN? ? ? ? ? ? 2
int brightness = 0;? ? // how bright the LED is
int fadeAmount = 5;? ? // how many points to fade the LED by
// Arduino like analogWrite
// value has to be between 0 and valueMax
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 255) {
? // calculate duty, 8191 from 2 ^ 13 - 1
? uint32_t duty = (8191 / valueMax) * min(value, valueMax);
? // write duty to LEDC
? ledcWrite(channel, duty);
}
void setup() {
? // Setup timer and attach timer to a led pin
? ledcSetup(LEDC_CHANNEL_0, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
? ledcAttachPin(LED_PIN, LEDC_CHANNEL_0);
}
void loop() {
? // set the brightness on LEDC channel 0
? ledcAnalogWrite(LEDC_CHANNEL_0, brightness);
? // change the brightness for next time through the loop:
? brightness = brightness + fadeAmount;
? // reverse the direction of the fading at the ends of the fade:
? if (brightness <= 0 || brightness >= 255) {
? ? fadeAmount = -fadeAmount;
? }
? // wait for 30 milliseconds to see the dimming effect
? delay(30);
}
用上這段代碼筑辨,nidec的無(wú)刷直流電機(jī)終于轉(zhuǎn)動(dòng)了