2016年9月27日 星期二

DIY - Robot 機器人 - TowerPro MG995 舵機 PWM 測試程式一(五)

DIY - Robot 機器人 - TowerPro MG995 舵機 PWM 測試程式一(五):

產生脈衝寬度調變(PWM)信號是很多方式,其中利用 Microchip PIC24FJ64GA008 內的 Timer ,再加上調整 OC 輸出,便可以輸出不同的 PWM 信號,便可以利用不同的 PWM 信號來驅動 TowerPro MG995 舵機(Servo)的轉動角度。

TowerPro MG995 舵機 PWM 測試程式一 LCD 顯示
▼例:假設振盪頻率 8MHz ( Fosc = 8MHz) TM2 預分頻值 164
PWM週期 = [ PR2+1] × (1(/Fosc/2)) × TM2 預分頻值  
PR2 = (99+1) × (1/(8MHz/2)) × 64 
PR2 = (1250) × (0.25us) × 64  
PR2 = (1250) × 16us
PR2 = 20ms (50Hz)

Calculation Example
Clock frequency = 8MHz
PWM frequency = 50Hz(8MHz/2)/50Hz = 8000/64
PR2 = (8000/64)-1 = 1249

1˙Duty Cycle = 0.5ms/20ms = 2.5%
OC1RS = 0.5ms / 16us = 31.25 (Clockwise = 30)

2˙Duty Cycle = 1.5ms/20ms = 7.5%
OC1RS = 1.5ms / 16us = 93.75 (Centre = 95)

3˙Duty Cycle = 2.5ms/20ms = 12.5%
OC1RS = 2.5ms / 16us = 156.25 (AntiClockwise = 160)

Microchip PIC24FJ64GA008 Timer2 初始化程式:
        CloseTimer2();              // Timer2 Close
                     ConfigIntTimer2(T2_INT_ON); // Timer2 Interrupt ON
        SetPriorityIntT2(1);        // Set Interrupt Priority 0~7
        OpenTimer2
        (
           T2_ON &                       // Timer2 ON
           T2_IDLE_CON &            // Idle Time Continue Run
           T2_GATE_OFF &            // Timer2 Gate Time Accumulation OFF/ON
           T2_32BIT_MODE_OFF &      // Timer2 32-bit Mode OFF/ON
           T2_PS_1_64 &              // Prescaler 1:1/8/64/2566
           T2_SOURCE_INT,           // Timer2 Source Oscillator INT/EXT
           1249                      // PRx=0~65535 1249+1=20ms
        );

Microchip PIC24FJ64GA008 OC1 初始化程式:
// Configure PWM OC1
// (PRx+1) * (1/(8MHz/2)) * Timer Divider
// ( 1249+1) * (0.25us * 2) * 64 = 20ms
// Reset PWM
OC1CON = 0x0000;    // Turn Off Output Compare 1 Module
// Set PWM Duty Cycle
OC1RS  =   1249;      // Initialize Second Compare Register (Duty Cycle =Timer/RS)
OC1R   =   1249;      // Initialize Compare Register        (RS/R)
// Enable PWM
OC1CON = 0x0005;    // Load the New Comapre mode to OC1CON
                    // Mode5 DC=50% OC1R=High=Timer OC1RS=Low=Timer/2

Microchip PIC24FJ64GA008 Timer2 中斷程式
// Timer2 Interrup
void __attribute__((interrupt, no_auto_psv)) _T2Interrupt(void) {
IFS0bits.T2IF = 0;
}

Microchip PIC24FJ64GA008 OC1 主程式
while(1){
//OC1RS = 1249*0.08;
OC1RS = 95;     // 96=Ctr 94~95=Ctr+1 98=Ctr-1
delayms(800);

OC1RS = 30;     // 0.5ms Clockwise 100=45 32-36<90 26="" 28="">90 20=135
delayms(500);

OC1RS = 160;    // 2.5ms Anticlockwise 45
delayms(500);

OC1RS = 95;     // 96=Ctr 94~95=Ctr+1 98=Ctr-1
delayms(500);
}


TowerPro MG995 舵機 PWM 測試程式一

2016年 9月 27日 天氣報告
氣溫:31.0@ 21:40
相對濕度:百分之 53%
天氣:天色大致良好

沒有留言:

張貼留言