level 1
用msp432p401r开发板 连接hcsr04超声波测距 改了一点公式让这个模块能测出相对准确的值 但是在测距为20.60cm时 之后的距离都不会再变大了 而是从0开始向上增加
2023年04月24日 02点04分
1
level 1
void init_hcsr04()
{
//初始化引脚
GPIO_setAsOutputPin(TRIG_PORT, TRIG_PIN);
GPIO_setAsInputPinWithPullDownResistor(ECHO_PORT, ECHO_PIN);
// 配置TA3.0定时器
Timer_A_UpModeConfig initUpModeParam;
initUpModeParam.clockSource= TIMER_A_CLOCKSOURCE_SMCLK;
initUpModeParam.clockSourceDivider= TIMER_A_CLOCKSOURCE_DIVIDER_1;
initUpModeParam.timerPeriod= 48000;
initUpModeParam.timerInterruptEnable_TAIE = TIMER_A_TAIE_INTERRUPT_DISABLE;
initUpModeParam.captureCompareInterruptEnable_CCR0_CCIE = TIMER_A_CAPTURECOMPARE_INTERRUPT_ENABLE;
initUpModeParam.timerClear= TIMER_A_DO_CLEAR;
Timer_A_initUpMode(TIMER_A3_BASE, &initUpModeParam);
// 配置TA3.0定时器的CCR0比较匹配寄存器
Timer_A_clearCaptureCompareInterrupt(TIMER_A3_BASE, TIMER_A_CAPTURECOMPARE_REGISTER_0);
Timer_A_CompareModeConfig initCompareModeParam;
initCompareModeParam.compareRegister= TIMER_A_CAPTURECOMPARE_REGISTER_0;
initCompareModeParam.compareInterruptEnable= TIMER_A_CAPTURECOMPARE_INTERRUPT_ENABLE;
initCompareModeParam.compareOutputMode= TIMER_A_OUTPUTMODE_OUTBITVALUE;
initCompareModeParam.compareValue= 48000;
Timer_A_initCompareMode(TIMER_A3_BASE, &initCompareModeParam);
Timer_A_startCounter(TIMER_A3_BASE, TIMER_A_UP_MODE);
//输出低电平
GPIO_setOutputLowOnPin(TRIG_PORT, TRIG_PIN);
__delay_cycles(10 * 48); // 10us延时
}
float sonar_cm(void)
{
double distance = 0;
GPIO_setOutputHighOnPin(TRIG_PORT, TRIG_PIN);
__delay_cycles(15 * 48);
GPIO_setOutputLowOnPin(TRIG_PORT, TRIG_PIN);
while(GPIO_getInputPinValue(ECHO_PORT, ECHO_PIN) == 0);
// 计时器开始计时
Timer_A_clear(TIMER_A3_BASE);
uint32_t start_time = Timer_A_getCounterValue(TIMER_A3_BASE);
while(GPIO_getInputPinValue(ECHO_PORT, ECHO_PIN) == 1);
uint32_t end_time = Timer_A_getCounterValue(TIMER_A3_BASE);
uint32_t duration = end_time - start_time;
if(duration > 60)
{
distance = duration * 0.034;
distance = duration / (2 * 58);
//
2023年04月24日 02点04分
2
level 1
// distance = duration * 0.034 /2;
// distance = distance / 100;
}
return distance;
}
int main(void)
{
MAP_WDT_A_holdTimer(); /* Stop Watch dog */
SysInit(); //时钟初始化 48MHz
delay_init(); //延时初始化
uart_init(115200); //串口初始化
init_hcsr04();
MAP_Interrupt_enableMaster(); //开启总中断
printf("Hello MSP432\r\n");
while(1)
{
float dis = sonar_cm();
printf("Distance: %.2fcm\r\n", dis * 0.05);
__delay_cycles(4800000);
}
}
2023年04月24日 02点04分
3