Day04
#include <ioCC2530.h>
#define TRIG P0_0
#define ECHO P0_1
#define buzzer P2_0
#define LED1 P1_4
#define ON 0
#define OFF 1
unsigned char ms_cnt = 0;
void rada_init(void);
int mark;
int getdistance();
void hc_sr04_init(void);
void Buzzer_Init(void);
void delay_10us(void);
void Buzzer_Init(void);
void led_init(void);
void main(void)
{
led_init();
rada_init();
hc_sr04_init();
Buzzer_Init();
while(1)
{
mark = getdistance();
if(mark <= 60){
LED1 = ON;
}else{
LED1 = OFF;
}
}
}
void rada_init(void)
{
P0SEL &= ~0x03;
P0DIR |= 0x01;
P0DIR &= 0x02;
P0INP &= 0x02;
P2INP |= 0x20;
P2SEL &= ~0x01;
P2DIR |= 0x01;
T1CTL = 0x04;
T1CNTL = 0x00;
T1CNTH = 0x00;
T1CC0L = 0x00;
T1CC0H = 0x07;
IEN1 |= 0x02;
IRCON = 0x00;
EA = 1;
}
#pragma vector=T1_VECTOR
__interrupt void time_ISR(void)
{
if(T1STAT&0x20)
{
ms_cnt++;
}
IRCON&=~0x02;
}
void hc_sr04_init()
{
TRIG=1;
delay_10us();
TRIG=0;
while(!ECHO);
T1CTL |= 0x01;
}
int getdistance()
{
unsigned char i;
int distance = 0;
unsigned char val;
unsigned char reg_val;
for(i = 0; i < 5; i++)
{
TRIG = 1;
delay_10us();
TRIG = 0;
while(!ECHO);
T1CTL &= ~0x03;
T1CTL |= 0x02;
while(ECHO){
if(ms_cnt > 40)
{
T1CTL &= ~0x03;
T1CNTL = 0x00;
T1CNTH |= 0x00;
ms_cnt = 0;
return 0;
}
}
T1CTL &= ~0x03;
val = T1CNTL;
reg_val = T1CNTH;
reg_val = ((reg_val<<8) | val)>>1;
distance += (ms_cnt*1000 + reg_val)/59;
T1CNTL = 0x00;
T1CNTH =
ms_cnt = 0;
}
distance = distance *17;
distance /= 5;
return distance;
}
void delay_10us(void)
{
int i;
for(i = 0; i < 10; i++);
}
void Buzzer_Init(void)
{
P2SEL &= ~0x01;
P2DIR |= 0x01;
buzzer = 0;
}
void led_init(void){
P1SEL &= ~0x10;
P1DIR |= 0x10;
LED1 = OFF;
}
|