??? 01/27/05 22:43 Read: times |
#85972 - SMT160 example code in C Responding to: ???'s previous message |
Following my working code for the AT89C4051.
It use T0 in mode 3 because T1 was used for the UART. Thus TL0 and TH0 are cascaded to 16 bit inside its interupt handlers. For stable results the whole measuring was done over several periods. A value of about 200 * 256 CPU-cycle seems sufficient. #pragma src(measure.a51) #include <stdio.h> #include <math.h> #include <reg4051.h> #define XTAL 11.0592e6 #define BAUD 4800 typedef unsigned char u8; typedef unsigned short u16; u8 period_h; u8 period_l; u8 pulse_h; u8 pulse_l; bit conversion_done; u8 tl0_h; u8 th0_h; void int_tl0( void ) interrupt INT_T0 // count pulse { tl0_h++; } void int_th0( void ) interrupt INT_T1 // count period { if( ++th0_h == 200 ){ IE0 = 0; EX0 = 1; // enable next falling edge } } void int_ex0( void ) interrupt INT_EX0 { if( PX0 ){ #pragma asm xch a, pulse_l ; save A clr a xch a, th0 ; read and clear mov period_l, a clr a xch a, tl0 ; read and clear xch a, pulse_l #pragma endasm IE0 = 1; // force calling again IP = PT0_ | PT1_; // handle timers first }else{ period_h = th0_h; th0_h = 0; pulse_h = tl0_h; tl0_h = 0; conversion_done = 1; EX0 = 0; // disable IP = PX0_; // restore priority } } void main (void) { u16 period, pulse; PCON |= SMOD_; SCON = TI_ | REN_ | SM1_; TMOD = T0_M0_ | T0_M1_ | T0_GA_ | T1_M1_; TH1 = (u8) -(0.5 + XTAL / 12.0 / 16 / BAUD); TL1 = -1; TCON = TR0_ | TR1_ | IT0_; IP = PX0_; IE = ET0_ | ET1_ | EA_; printf( "Hallo Petern" ); for(;;){ // main loop conversion_done = 0; while( conversion_done == 0 ); period = (u16)period_h << 8 | period_l; pulse = (u16)pulse_h << 8 | pulse_l; printf("%8u", period ); printf("%8u", pulse ); printf("%8.2fn", 212.766 * ((float)pulse / period - 0.32) ); } } Peter |