//********************************************************************** /*   <静電容量スイッチ> */ //********************************************************************** #define LED GPIO.F4 #define SW GPIO.F3 //********************************************************************** void Pwm_Change_DutyEx(unsigned int duty_ratio) { CCPR1L = duty_ratio >> 2; CCP1CON.DC1B0 = duty_ratio & 0b00000001; CCP1CON.DC1B1 = (duty_ratio & 0b00000010) >> 1; } //********************************************************************** unsigned int measurement() { static unsigned int tm; // TMR1L = 0; TMR1H = 0; PIR1.TMR1IF = 0; T1CON.TMR1ON = 0; // VRCON.VR3 = 0; VRCON.VR2 = 0; VRCON.VR1 = 0; VRCON.VR0 = 1; // GPIO.F0 = 1; Delay_us(100); GPIO.F0 = 0; // while (CMCON0.COUT == 1) ; // VRCON.VR3 = 1; VRCON.VR2 = 1; VRCON.VR1 = 1; VRCON.VR0 = 1; // T1CON.TMR1ON = 1; while (CMCON0.COUT == 1) ; // T1CON.TMR1ON = 0; tm = TMR1H << 8; tm |= TMR1L; // return(tm); } //********************************************************************** unsigned int Average(int cnt) { static unsigned long tm; static unsigned int i; // tm = 0; for (i = 0; i < cnt; i++) { tm += measurement(); } return(tm / cnt); } //********************************************************************** void Soft_Uart_Write_Str(char* str) { while (*str != 0x00) { Soft_Uart_Write(*str); str++; } } //********************************************************************** void main() { static long tm0, tm1, tm2; static short mode, cnt, on_cnt; static char buf[10]; static double val; // OSCCON = 0b01110000; // クロックは8Mhz CMCON0 = 0b00000100; // コンパレータを使用する。 ANSEL = 0b00000000; // A/D変換は使用しない。 TRISIO = 0b00001010; GPIO = 0b00000000; // T1CON.T1CKPS1 = 0; T1CON.T1CKPS0 = 0; // Pwm_Init(1000); Pwm_Change_DutyEx((PR2 * 4) / 2); Pwm_Stop(); // Soft_Uart_Init(GPIO, 3, 5, 9600, 0); // VRCON.VREN = 1; VRCON.VRR = 1; // LED = 0; tm0 = 0; //浮遊容量 tm1 = 0; //基準値 tm1 = 0; //実測値 //動作モードの設定 if (SW == 1) { mode = 1; //静電容量スイッチ } else { while (SW == 0) { Delay_ms(50); } mode = 0; //静電容量計 Soft_Uart_Write_Str("C-Meter\r\n"); //浮遊容量の測定 tm0 = Average(100); } //基準値の測定 if (mode == 0) { while (SW == 1) { LED = 1; Delay_ms(50); LED = 0; Delay_ms(50); } } tm1 = Average(100) - tm0; // while (1) { if (mode == 1) { on_cnt = 0; for (cnt = 0; cnt < 10; cnt++) { //実測値の測定 tm2 = Average(10) - tm0; //基準値と実測値の差を求める。 if (labs(tm1 - tm2) > (tm1 / 20)) { on_cnt++; } } if (on_cnt > 5) { LED = 1; Pwm_Start(); } else { LED = 0; Pwm_Stop(); } } else { //実測値の測定 tm2 = Average(100) - tm0; val = (double)tm2 / ((double)tm1 / 1000.0); // WordToStr(val, buf); Soft_Uart_Write_Str(buf); Soft_Uart_Write_Str("pF\r\n"); // LED = 1; Delay_ms(100); LED = 0; } //基準値を再設定する。 if (SW == 0) { tm1 = tm2; } } } //**********************************************************************