代码

#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
 
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

unsigned int EchoPin = 2;
 
unsigned int TrigPin = 3;
 
unsigned long Time_Echo_us = 0;

unsigned long Len_mm_X100  = 0;
 
unsigned long Len_Integer = 0; 
 
unsigned int Len_Fraction = 0;

void distance()
{
  
  digitalWrite(TrigPin, HIGH);
 
    delayMicroseconds(50);
 
    digitalWrite(TrigPin, LOW);
 
   
 
    Time_Echo_us = pulseIn(EchoPin, HIGH);
 
    if((Time_Echo_us < 60000) && (Time_Echo_us > 1))
 
    {
 
      Len_mm_X100 = (Time_Echo_us*34)/2;
 
      Len_Integer = Len_mm_X100/100;
 
      Len_Fraction = Len_mm_X100%100;
 
  /*    Serial.print("Present Length is: ");
 
      Serial.print(Len_Integer, DEC);
 
      Serial.print(".");
 
      if(Len_Fraction < 10) 
 
        Serial.print("0");
 
      Serial.print(Len_Fraction, DEC);
 
      Serial.println("mm");
 */
 
    }
 
  }
 
void setup(){
  lcd.init();                      // initialize the lcd 
  // Print a message to the LCD.
  lcd.backlight();
  
  Serial.begin(9600);
  pinMode(EchoPin, INPUT);
  pinMode(TrigPin, OUTPUT);
}


 
void loop(){
  distance();
  
  lcd.init(); 
  lcd.setCursor(0,0);
  lcd.print("distance:");
  lcd.print(Len_Integer);
  lcd.print("mm");
  lcd.setCursor(0,1);
  lcd.print("Ture!");
  delay(1000);


}

在这里插入图片描述

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐