ESP32 with PWM
PWM 很常拿來控制馬達或是LED用,本篇文章單純紀錄如何透過Arduino IDE 開發使用ESP32的PWM。
目 標:
使用Arduino IDE 控制ESP32 指定腳位輸出PWM
軟 體:
Arduino IDE
硬 體:
1. EP32
2. USB TTL
3. 杜邦線若干條
4. 示波器 一台
說 明:
跟平常使用的PWM 控制差不多,但是需要特別去注意以下幾點
1. 需要特別去設定通道(只有0~16)
2. 頻率
程式碼
#define PWM_CHANNEL_0 0 // use first channel of 16 channels (started from zero) #define PWM_TIMER_12_BIT 12 // use 12 bit precission for LEDC timer #define PWM_BASE_FREQ 5000 // use 5000 Hz as a LEDC base frequency #define PWM_PIN 5 // fade LED PIN (replace with LED_BUILTIN constant for built-in LED) int Value = 0; // how bright the LED is int Step = 5; // how many points to fade the LED by // Arduino like analogWrite // value has to be between 0 and valueMax void PWMAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 255) { // calculate duty, 4095 from 2 ^ 12 - 1 uint32_t duty = (4095 / valueMax) * min(value, valueMax); ledcWrite(channel, duty);// write duty to PWM Pin } void setup() { // Setup timer and attach timer to a led pin ledcSetup(PWM_CHANNEL_0, PWM_BASE_FREQ, PWM_TIMER_12_BIT); ledcAttachPin(PWM_PIN, PWM_CHANNEL_0); } void loop() { PWMAnalogWrite(PWM_CHANNEL_0, Value); // set the Value on channel 0 Value = Value + Step;// add the Value if (Value <= 0 || Value >= 255) { Step = -Step; } delay(50); }
執行結果
影片中可以看到,PWM波型的輸出及變化,在示波器右側量測到的頻率也與設定的5kHz一致
參考資料
沒有留言:
發佈留言