|
#include <LiquidCrystal.h>
//Configure LCD
LiquidCrystal lcd(7,8,9,10,11,12); //configure rs, enable, d4-d7 pins on LCD (to pin9-pin12 on Arduino)
//Configure Ranging sensor
const int triggerPin = 4;
const int echoPin = 5;
long deltaT;
int distCM;
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16,2);
//Print a message to the LCD:
//lcd.print("Hello World!");
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
//Low-High-Low for triggering
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10); //at least 10 us TTL signal
digitalWrite(triggerPin, LOW);
//distance = time*speed
deltaT = pulseIn(echoPin, HIGH);
distCM = deltaT*0.0343/2; //cm
// set the cursor to column 0, line 1
lcd.setCursor(0,0);
// print the number of seconds since reset:
lcd.print("Distance: ");
lcd.print(distCM);
lcd.print(" cm");
delay(10); //ms
//second line printing if needed
//lcd.setCursor(0,1);
//lcd.print(millis()/1000);
}
References:
https://www.arduino.cc/en/Reference/LiquidCrystal
https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2025-1-10 05:55
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社