00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030 #include "pic24_all.h"
00031 #include <stdio.h>
00032
00040 uint8 getPeriodAdjust (uint8 ICMbits) {
00041 if (ICMbits == IC_EVERY_16_RISE_EDGE) return 16;
00042 else if (ICMbits == IC_EVERY_4_RISE_EDGE) return 4;
00043 else return 1;
00044 }
00045
00046 volatile uint8 u8_captureFlag = 0;
00047 volatile uint16 u16_lastCapture;
00048 volatile uint16 u16_thisCapture;
00049 volatile uint32 u32_period;
00050
00051 void _ISRFAST _IC1Interrupt() {
00052 _IC1IF = 0;
00053 u16_thisCapture = IC1BUF;
00054 if (u8_captureFlag == 0) {
00055 u32_period = (uint32) computeDeltaTicks(u16_lastCapture,u16_thisCapture,PR2);
00056 u32_period = ticksToNs (u32_period, getTimerPrescale(T2CONbits));
00057
00058 u32_period = u32_period/getPeriodAdjust(IC1CONbits.ICM);
00059 u8_captureFlag = 1;
00060 }
00061 u16_lastCapture = u16_thisCapture;
00062 }
00063
00064 void configInputCapture1(void) {
00065 CONFIG_RB13_AS_DIG_INPUT();
00066 CONFIG_IC1_TO_RP(13);
00067 IC1CON = IC_TIMER2_SRC |
00068 IC_INT_1CAPTURE |
00069 IC_EVERY_16_RISE_EDGE;
00070 _IC1IF = 0;
00071 _IC1IP = 1;
00072 _IC1IE = 1;
00073 }
00074
00075 void configTimer2(void) {
00076 T2CON = T2_OFF | T2_IDLE_CON | T2_GATE_OFF
00077 | T2_32BIT_MODE_OFF
00078 | T2_SOURCE_INT
00079 | T2_PS_1_64 ;
00080 PR2 = 0xFFFF;
00081 TMR2 = 0;
00082 _T2IF = 0;
00083 T2CONbits.TON = 1;
00084 }
00085
00086 int main (void) {
00087 uint32 u32_maxPeriodNs;
00088 configBasic(HELLO_MSG);
00089 configTimer2();
00090 configInputCapture1();
00091 u32_maxPeriodNs = ticksToNs (65536, getTimerPrescale(T2CONbits))/getPeriodAdjust(IC1CONbits.ICM);
00092 printf("Maximum period is %ld ns\n",u32_maxPeriodNs);
00093 while (1) {
00094 outString("Press button...");
00095 while (!u8_captureFlag) doHeartbeat();
00096 printf(" %ld ns\n",u32_period);
00097 u8_captureFlag = 0;
00098 }
00099 }