/**超声波测距离HC-SR04模块,在12864上显示出来,误差为5cm以内********/
#include <msp430x14x.h>
#include "Config.h"
#include "12864.c"
#define uchar unsigned char
#define uint unsigned int
#define ulong unsigned long
#define CLK_Trig P1OUT &= ~BIT0 //P1.0产生脉冲引脚
#define SET_Trig P1OUT |= BIT0 //P1.0产生脉冲引脚
#define Echo (P1IN & BIT2) //回波引脚
//unsigned char tt[]=" hc-sr04 ";
//uchar distance[]="distance: CM";
uchar distance[3];
unsigned int distance_data, M;
uchar succeed_bit;
uint count=0;
//函数的声明//
/*20us延时函数*/
void Delay20us()
{
uchar i;
for(i=0; i<20; i++);
}
/***测量获取数据**/
void Measure()
{ /******************************HC-sr04的初始化部分****************************/
succeed_bit=0;
_DINT();
SET_Trig;//P1.0产生脉冲引脚
Delay20us();//延时20us,把Trig的引脚的电位拉高20us//之后,超声波内部自动发送8个40KHz的脉冲
CLK_Trig;//再输出低电平
_EINT();//中断使能,打开中断,上升沿捕获和下降沿捕获
/*********************************************************************
*********************************************************************/
while(Echo == 0);//判断echo是否变为高电平,上升沿
TACTL &= ~MC_1;
TACTL |= TACLR; //连续计数 清除TA的计数值
TACTL |= TASSEL_2 + MC_1 + ID_3 ;//选择SMLK时钟频率,8分频,1M,增计数模式
TACCTL0 &= ~CCIFG; //清中断标志
TACCTL0 |= CM_2; //下降沿捕捉
while(Echo == 1); //等待echo变回低电平,下降沿
distance_data = CCR0;//TA0R是所需时间
while(!(succeed_bit));//等待succeed为 1
M =(distance_data * 17)/1000;//测量结果为CM
succeed_bit = 0;
}
//显示函数
void display()
{
distance[2] = M%10+0x30; //取个位
distance[1] = M/10%10+0x30; //取十位
distance[0] = M/100+0x30; //取百位
LCD_write_str(0x01,2,distance);
delay_ms(60);
}
void main(void)
{
uchar i;
//Stop watchdog
timer to prevent time out reset
WDTCTL = WDTPW + WDTHOLD;
Port_init();
Clock_Init();
BCSCTL2 |= SELM_2 + SELS +DIVS_3;//使MCLK和SMCLK都为高频振荡器,8分频
CCTL0 |= CCIE + CM_3 + SCS + CAP + CCIS_1 ;
TACTL |= TASSEL_2 + MC_1 + ID_3 ;//选择SMLK时钟频率,8分频,1M,增计数模式
P1DIR &= ~BIT2;//设置P1.1为输入端
P1DIR |= BIT0;//设置P1.0为输出端
P1OUT &= ~BIT0;//先输出0
delay_ms(600);
LCD_init();
LCD_Desk();
_EINT(); //进入全局中断
while(1)
{ Measure();
display();
LCD_write_str(0x00,2,distance);
}
}
#pragma vector = TIMERA0_VECTOR
__interrupt void vector_TimeA(void)
{
TACTL &= ~TAIFG ; //中断标志清零
succeed_bit =1;
CCTL0 &= ~CCIE; //关闭中断使能;
}
IO口配置 要看你板子具体是怎么接的
一周热门 更多>