分类
笔记

51单片机超声避障(HC-SR04)小车程序代码

适用于51单片机的超声避障小车程序代码

利用HC-SR04超声波模块实现小车超声避障UV_Car

 

演示视频:

 

 

头文件 BoeBot.h

#ifndef __BOEBOT_H__
#define __BOEBOT_H__

#include <at89x52.h>

void delay_nms(int ms); 
void delay_nus(int us);

#endif
const unsigned char CONST_MILLISECONDCOUNT = 115;
const unsigned char CONST_MICROSECONDDIVISER = 12;

void delay_nms(int ms) {
  unsigned char i;
  while((--ms) >= 0) {
    for(i = 0;i < CONST_MILLISECONDCOUNT;i++);
  }
}

void delay_nus(int us) {
  us /= CONST_MICROSECONDDIVISER;
  while((--us) >= 0) {}
}

主程序 main.c

#include "BoeBot.h"

sbit Led = P1^0;  // Led指示
sbit Trig = P1^1; // 脉冲引脚
sbit Echo = P3^2; // 回波引脚

volatile unsigned short outcomeH,outcomeL;
volatile char succeed_flag;

void ConfigTimer() {
  TMOD = 0x1;  //定时器0,16位工作方式
}

void StartTimer() {
  TH0 = TL0 = 0;
  TR0 = 1;
}

void StopTimer() {
  TR0 = 0;
}

void ConfigExternal() {
  IT0 = 1;
}

void ConfigInterput() {
  ET0 = 1;
  EX0 = 1;
}

void EnableInterput() {
  EA = 1;
}

void DisableInterput() {
  EA = 0;
}

//距离计算公式
// distance = v * t / 2
// distance = 344 m/s * t * 12 / 11.0592 * us / 2
//          = 344 mm/ms * t * 12/11.0592 / 1000 * ms / 2
//          = 187 / 1000 * t mm
//         ~= t / 5.3 mm
unsigned short ComputeDistance() {
  return (((outcomeH << 8) | outcomeL) / 5);
}

unsigned short FilterDistance(unsigned short distance) {
  static unsigned short distanceArray[5];
  static char index = 0;
  char i;
  unsigned short sum;
  
  distanceArray[index] = distance;
  if((++index) == 5) {
    index = 0;
  }
  
  sum = 0;
  for(i = 0;i < 5;i++) {
    sum += distanceArray[i];
  }
  
  return sum / 5;
}

void main() {
  unsigned short distanceMM;
  
  ConfigExternal();
  ConfigTimer();
  ConfigInterput();
  
  while(1) {
    // 启动定时器
    EnableInterput();
    StartTimer();
    succeed_flag = 0;
    
    // 产生一个20us的脉冲,在Trig引脚  
    Trig = 1;
    delay_nus(20);
    Trig = 0;

    // 停止定时器
    while(!succeed_flag);
    StopTimer();
    DisableInterput();
    
    // 计算距离,并根据阈值点亮Led
    distanceMM = ComputeDistance();
    //Led = (FilterDistance(distanceMM) < 300 ? 0 : 1);
    Led = (distanceMM < 200 ? 0 : 1);
    
    delay_nms(10);
  }
}

//外部中断0,用做判断回波电平
void IE0_Handler(void)  interrupt IE0_VECTOR   // 外部中断是0号 { 
  outcomeH = TH0;     // 取出定时器H值
  outcomeL = TL0;     // 取出定时器L值
  succeed_flag = 1;   // 设置测量成功标记
  
  IE0 = 0;
}

void TF0_Handler(void) interrupt TF0_VECTOR   // 定时器0  {}

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注