單片機+超聲波實時測距
我寫的代碼:
下面是代碼:
#include
LCD4Bit_mod lcd = LCD4Bit_mod(2);
int inputPin=15;
int outputPin=16;
int ledPin = 17;
void setup() {
pinMode(inputPin, INPUT);
pinMode(outputPin, OUTPUT);
pinMode(ledPin,OUTPUT);
lcd.init();
lcd.clear();
lcd.cursorTo(1, 0);
lcd.printIn("www.geeetech.com");
}
void display(int number,unsigned char address)
{
unsigned char a,b,c,d;
if(number <100)
digitalWrite(ledPin,LOW);
if(number >=100 )
digitalWrite(ledPin,HIGH);
a=(number/1000);
b=(number/100)%10;
c=(number/10)%10;
d=number%10;
lcd.commandWrite(0x80+address);
lcd.print(a+48);
lcd.print(b+48);
lcd.print(c+48);
lcd.print(46);
lcd.print(d+48);
lcd.print(99);
lcd.print(109);
}
void loop() {
digitalWrite(outputPin, LOW);
delayMicroseconds(2);
digitalWrite(outputPin, HIGH);
delayMicroseconds(10);
digitalWrite(outputPin, LOW);
float distance = pulseIn(inputPin, HIGH);
distance= distance/5.8;
lcd.cursorTo(2, 0);
lcd.printIn("Distance:");
display(distance,0x49);
}
評論