วันอาทิตย์ที่ 3 ตุลาคม พ.ศ. 2553

Lab6: การใช้งาน Module CCP(Capture วัดความถี่)


#include<18F4431.h>
#define  CLOCK_SP    20000000 // ความเร็วสัญญาณนาฬิกา
#fuses HS                     //   โหมดการทำงานแบบ High Speed
#fuses NOLVP,NOWDT           // No Low Voltage Program, No Watchdog timer
#fuses NOPROTECT              // Code no protection
#use delay (clock=CLOCK_SP)   // ใช้งานฟังก์ชัน delay_ms() & delay_us()
#use rs232(baud=9600,xmit= PIN_C6,rcv= PIN_C7 ) // ใช้งาน module RS232

float time1,time2;                      //ประกาศตัวแปร time1,time2 เป็น floating point number
BOOLEAN hook_cpp1, HookRise;     //ประกาศตัวแปร hook_cpp1, HookRise เป็น Boolean

#int_ccp1
void capture_isr()
{
   if(HookRise)
   {
    time1 = get_timer1();
    HookRise = FALSE;
   }
   else
   {
    time2 = get_timer1();
    HookRise = TRUE;
    hook_cpp1 = FALSE;                  
   }
}
// ฟังก์ชัน interrupt CCP1 เพื่อจับเวลาขอบขาขึ้นของสัญญาณ โดยเก็บเวลาที่ตัวแปร time1,time2

float T;                         //ประกาศตัวแปร T เป็น floating point number
void main(void){

while(true){

      HookRise=TRUE;
      hook_cpp1=TRUE;
      setup_timer_1(T1_INTERNAL|T1_DIV_BY_8);      // กำหนดค่า timer1
      setup_ccp1(CCP_CAPTURE_RE);           //กำหนดค่า CCP1(Capture ขอบขาขึ้น)
      enable_interrupts(INT_CCP1);              // Enable interrupt CCP1
      enable_interrupts(GLOBAL);                // ตั้งค่า interrupt รวม
      set_timer1(0);                                 //ตั้งค่า timer1 เป็น 0
     
      while(hook_cpp1);             //ตรวจสอบสัญญาณ เข้ามาหรือไม่
      setup_ccp1(CCP_OFF);                //ปิดการใช้งาน CCP1
      disable_interrupts (GLOBAL);        //ปิดการใช้งาน interrupt รวม
      
      T = (time2-time1)*0.0000002*8;            // Period time=cycle*(4/fosc)*PR
      printf("Frequency:%f Hz\r\n",1/T);   //แสดงค่าผ่าน RS232
    }
   }