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

Lab8: การวัดค่า Duty Cycle (CCP1,CCP2)


#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;
BOOLEAN hook_cpp1, HookRise;

#int_ccp1
void capture_isr()
{
   if(HookRise)
   {
    time1 = get_timer1();
    HookRise = FALSE;
   }
   else
   {
    time2 = get_timer1();
    HookRise = TRUE;
    hook_cpp1 = FALSE;                          //done
   }
}

// ฟังก์ชัน interrupt CCP1 เพื่อจับเวลาขอบขาขึ้นของสัญญาณ โดยเก็บเวลาที่ตัวแปร time1,time2

long rise,fall,pulse_width;

#int_ccp2
void isr()
{
   rise = CCP_1;
   fall = CCP_2;

   pulse_width = fall - rise;    
}
// ฟังก์ชัน interrupt CCP2 เพื่อจับเวลาขอบขาขึ้นของสัญญาณ และขอบขาลงของสัญญาณ โดยเก็บเวลาที่ตัวแปร rise, fall

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

   while(true)
   {

      HookRise=TRUE;
      hook_cpp1=TRUE;
      setup_ccp1(CCP_CAPTURE_RE);           //กำหนดค่า CCP1 Capture ขอบขาขึ้น
      setup_ccp2(CCP_CAPTURE_FE);           //กำหนดค่า CCP2 Capture ขอบขาลง
      enable_interrupts(INT_CCP1);              // เปิดการทำงาน interrupt CCP1
      enable_interrupts(INT_CCP2);                   // เปิดการทำงาน interrupt CCP2
      enable_interrupts(GLOBAL);                // All interrupts ON
      set_timer1(0);                                             // กำหนดค่า Timer1 เป็น 0
      while(hook_cpp1==TRUE);                       //เงื่อนไขการตรวจสอบสัญญาณครบ 1 period
     
      setup_ccp1(CCP_OFF);                            //ปิดการทำงาน CCP1
      disable_interrupts (GLOBAL);                    //ปิดการทำงาน interrupt รวม
      
      T = (time2-time1)*0.0000002*8;                // Period time = cycle*(4/fosc)*PR
      width = (float)pulse_width / 5000000;            //width = pulse_width / (clock / 4)
      duty = (width*100)/T;                      //หาค่า Duty Cycle (T_on*100 / Period time)
     
      printf(“ %.3f\r\n",duty);                   //แสดงค่าผ่าน RS232
   
   }
}