/* sonar.c */ #include "door.h" #include "sonar.h" #include "rf.h" /* states and flags */ static unsigned char dist = 0; // count the cycle before echo comes back static unsigned int count = 0; // counter static bit run = 1; static bit echo = 0; char xdata *leda = 0x0f000; // the FPGA is configured to memory map led to this address /* fire sonar and do distance calculations; signals serialTask to do RF stuff when user is near by */ void Sonar_Task() { /* interrupt settings */ EA = 1; ET1 = 0; ES = 0; /* set timer */ TMOD = 0x21; PCON = PCON | 0x80; TH1 = 249; TR1 = 1; /* Set up and enable Timer0 for a 1 millisecond timer */ TL0 = RELOAD_LO; /* Load the timer high and low bytes */ TH0 = RELOAD_HI; TMOD = 0x21; /* Timer1 & Timer0 as 16-bit timers */ TR0 = 1; /* Start the timer 0 */ ET0 = 1; /* Enable the timer interrupt 0 (Page 55) */ EX0 = 0; /* Enable the external interrupt 0 */ EA = 1; /* Enable the global interrupt */ IT0 = 1; /* Enable the TCON for falling edge trigger */ T0 = 0; /* T0 = P3.4 is connected to sonar INIT, pin 68 on the XS40 */ count = 0; echo = 0; PT0 = 1; run = 1; while (run) { } }/* end Sonar_Task */ /* called by Ext0 ISR in DETECTING_USER state */ void Sonar_Ext0_Handler() { // pin 12 echo = 1; }/* end Sonar_Ext0_Handler() */ /* called by Timer0 ISR in DETECTING_USER state */ void Sonar_Timer0_Handler() { TL0 = TL0 + RELOAD_LO ; // Load the timer high and low bytes TH0 = RELOAD_HI; count = count + 1; if((count >=0) && (count < 60)) // RESET { EX0 = 0; T0 = 0; // init = 0 dist = 0; echo = 0; } else if((count >= 60) && (count < 1060)) // logic high { *leda = 0x12; // 1 T0 = 1; // init = 1 if(echo == 0) dist = dist + 1; else { ET0 = 0; // disable timer0 interrupt EX0 = 0; // disable external interrupt IE = 0; /***** Check here later ****/ state = REQUESTING_ID; // echo comes back, switch state run = 0; return; } if((dist < L_THERSHOLD) || (dist > H_THERSHOLD)) { IE0 = 0; EX0 = 0; } else EX0 = 1; } else if((count >= 1060) && (count < 11060)) //logic low { *leda = 0x5D; // 2 T0 = 0; } else { count = 0; } } /* end Sonar_Timer0_Handler() */ /* void print(char c) { SBUF = c; while(TI == 0); TI = 0; } void putChar(unsigned char c) { unsigned char a = c/100; unsigned char b = c%100; unsigned char d = b/10; unsigned char e = b%10; print(a+48); print(d+48); print(e+48); } */