การสร้างสัญญาณ pwm ที่สามารถปรับค่าความถี่ และดิวตี้ไซเคิลได้ตามต้องการ

ลองโค้ดนี้ดูครับ สามารถปรับความถี่ได้จากคำสั่ง Timer1.initialize() ต้องการความถี่เท่าไหร่ก็ลองไปปรับค่าดู ตอนนี้ 20 = 50kHz ปรับค่าได้ตั้งแต่ 0 - 255 สัญญาณ pwm จะออกมาหน้าตาเหมือนกันที่ pin9 และ pin10 ไม่รู้ว่าตรงกับที่ต้องการหรือป่าวนะครับ น่าจะลงรายละเอียดมากกว่านี้อีกนิด ลองไปเทสดูครับ

       #include "TimerOne.h"
        int pot = 0; // analog value 0-5VDC : 0-255
        void setup()
        {
          OCR2A = pot;
          pinMode(9, OUTPUT);
          Timer1.initialize(20);         // initialize timer1, and set at 50kHz
          Timer1.pwm(9, pot);         // setup pwm on pin 9, 25% duty cycle
          Timer1.pwm(10, pot);       // setup pwm on pin 10, 25% duty cycle

        TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
        TCCR2B = _BV(CS20); // prescaler à 1.
        OCR2A = pot;
        }

        void loop()
        {
         pot = analogRead(A0)/4; // Value between 0 and 255
         Timer1.pwm(9, pot);         // setup pwm on pin 9, 25% duty cycle
          Timer1.pwm(10, pot);       // setup pwm on pin 10, 25% duty cycle
        }