我有一张pic 18F4550如何读取超声波传感器的距离

问题描述 投票:-1回答:1

我有PIC 18f4550,需要在picBasic pro中编写代码。 我正在连接直流电机,超声波传感器和红外传感器等 我做了一切,但仍然对如何接口超声波传感器感到困惑。

这是PIC中的超声波引脚

trisb.3=0    'trigger ultrasound
trisb.4=1    ' Echo from Ultrasound

我需要一个示例代码

visual-studio embedded microcontroller sensor pic
1个回答
1
投票

编程的基本步骤:

1 - 为超声波模块提供TRIGGER 2 - 听Echo 收到ECHO HIGH时的3启动定时器 ECHO变为低电平时的4档定时器 5读取计时器值 6 - 将其转换为距离 7-显示它

Distance Calculation

  • 距离=速度*时间
  • 设d是超声波传感器和目标之间的距离
  • 超声波爆发行进的总距离:2d(向前和向后)
  • 空气中声速:340 m / s = 34000 cm / s
  • 因此,d =(34000 *时间)/ 2,其中时间=(TMR1H:TMR1L)/(1000000)
  • 因此,d =(TMR1H:TMR1L)/58.82cm
  • TMR1H:TMR1L = TMR1L | (TMR1H << 8)

MikroC代码

// LCD module connections
sbit LCD_RS at RD2_bit;
sbit LCD_EN at RD3_bit;
sbit LCD_D4 at RD4_bit;
sbit LCD_D5 at RD5_bit;
sbit LCD_D6 at RD6_bit;
sbit LCD_D7 at RD7_bit;

sbit LCD_RS_Direction at TRISD2_bit;
sbit LCD_EN_Direction at TRISD3_bit;
sbit LCD_D4_Direction at TRISD4_bit;
sbit LCD_D5_Direction at TRISD5_bit;
sbit LCD_D6_Direction at TRISD6_bit;
sbit LCD_D7_Direction at TRISD7_bit;
// End LCD module connections

void main()
{
  int a;
  char txt[7];
  Lcd_Init();
  Lcd_Cmd(_LCD_CLEAR);          // Clear display
  Lcd_Cmd(_LCD_CURSOR_OFF);     // Cursor off

  TRISB = 0b00010000;           //RB4 as Input PIN (ECHO)

  Lcd_Out(1,1,"Developed By");
  Lcd_Out(2,1,"Mina Karam");

  Delay_ms(3000);
  Lcd_Cmd(_LCD_CLEAR);

  T1CON = 0x10;                 //Initialize Timer Module

  while(1)
  {
    TMR1H = 0;                  //Sets the Initial Value of Timer
    TMR1L = 0;                  //Sets the Initial Value of Timer

    PORTB.F0 = 1;               //TRIGGER HIGH
    Delay_us(10);               //10uS Delay
    PORTB.F0 = 0;               //TRIGGER LOW

    while(!PORTB.F4);           //Waiting for Echo
    T1CON.F0 = 1;               //Timer Starts
    while(PORTB.F4);            //Waiting for Echo goes LOW
    T1CON.F0 = 0;               //Timer Stops

    a = (TMR1L | (TMR1H<<8));   //Reads Timer Value
    a = a/58.82;                //Converts Time to Distance
    a = a + 1;                  //Distance Calibration
    if(a>=2 && a<=400)          //Check whether the result is valid or not
    {
      IntToStr(a,txt);
      Ltrim(txt);
      Lcd_Cmd(_LCD_CLEAR);
      Lcd_Out(1,1,"Distance = ");
      Lcd_Out(1,12,txt);
      Lcd_Out(1,15,"cm");
    }
    else
    {
      Lcd_Cmd(_LCD_CLEAR);
      Lcd_Out(1,1,"Out of Range");
    }
    Delay_ms(400);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.