//----------------------------------------------------------------------------- // Note // CCP1とタイマ2を使用してDCモータを動かす // PICの周波数を32Mhzに設定 //----------------------------------------------------------------------------- #include #include #include #include // コンフィグレーションBIT1 設定 #pragma config FOSC = INTOSC // Oscillator Selection (INTOSC oscillator: I/O function on CLKIN pin) #pragma config WDTE = OFF // Watchdog Timer Enable (WDT disabled) #pragma config PWRTE = ON // Power-up Timer Enable (PWRT enabled) #pragma config MCLRE = OFF // MCLR Pin Function Select (MCLR/VPP pin function is MCLR) #pragma config CP = OFF // Flash Program Memory Code Protection (Program memory code protection is disabled) #pragma config CPD = OFF // Data Memory Code Protection (Data memory code protection is disabled) #pragma config BOREN = OFF // Brown-out Reset Enable (Brown-out Reset disabled) #pragma config CLKOUTEN = OFF // Clock Out Enable (CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin) #pragma config IESO = OFF // Internal/External Switchover (Internal/External Switchover mode is disabled) #pragma config FCMEN = OFF // Fail-Safe Clock Monitor Enable (Fail-Safe Clock Monitor is disabled) // コンフィグレーションBIT2 設定 #pragma config WRT = OFF // Flash Memory Self-Write Protection (Write protection off) #pragma config PLLEN = ON // PLL Enable (4x PLL enabled) #pragma config STVREN = ON // Stack Overflow/Underflow Reset Enable (Stack Overflow or Underflow will cause a Reset) #pragma config BORV = HI // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (Vbor), high trip point selected.) #pragma config LVP = OFF // Low-Voltage Programming Enable (High-voltage on MCLR/VPP must be used for programming) // モータへのデューティ比設定 // duty 100?-100 void set_dc_motor( signed char duty ) { if( duty > 100 ) duty = 100; if( duty < -100 ) duty = -100; // 出力pin設定 if( duty > 0 ) { STR1A = 1; // ステアリングレジスタ設定(ON) CCP1SEL = 0; // RA2をPWM出力 } else if( duty < 0 ) { STR1A = 1; // ステアリングレジスタ設定(ON) CCP1SEL = 1; // RA5をPWM出力 } else { STR1A = 0; // ステアリングレジスタ設定(OFF) } if( duty < 0 ) duty *= -1; // デューティ比をCCP1へ設定 // PR2が100の為、デューティー比をそのまま設定 CCPR1L = duty; } int main(int argc, char** argv) { long i; OSCCON = 0b01110000 ; // 内部クロック8MHz ANSELA = 0b00000000 ; // すべてデジタルI/Oに割当てる TRISA = 0b00001000 ; // RA3を入力とする PORTA = 0b00000000 ; // ピン状態初期化 CCP1SEL = 0; // RA2をPWM出力 CCP1CON = 0b00001100 ; // PWMシングルモード T2CON = 0b00000001 ; // TMR2プリスケーラ値を1/4に設定 CCPR1L = 0; CCPR1H = 0; TMR2 = 0; PR2 = 99; // PWMの周期を設定(20khz) STR1A = 0; // ステアリングレジスタ設定 TMR2ON = 1; // TMR2開始 for(;;) { set_dc_motor(15); for(i=0; i<1000000; i++) { // 処理無し(一定時間待ち) } set_dc_motor(20); for(i=0; i<1000000; i++) { // 処理無し(一定時間待ち) } set_dc_motor(15); for(i=0; i<1000000; i++) { // 処理無し(一定時間待ち) } set_dc_motor(0); for(i=0; i<1000000; i++) { // 処理無し(一定時間待ち) } set_dc_motor(-15); for(i=0; i<1000000; i++) { // 処理無し(一定時間待ち) } set_dc_motor(0); for(i=0; i<1000000; i++) { // 処理無し(一定時間待ち) } } return (EXIT_SUCCESS); }