Serial 16×2 LCD 和 超声波测距我们之前的实验有涉猎到,把这两个结合起来能完成很有趣的实验。
一、实验器材:
Serial 16×2 LCD 一块 HC-SR04 超声波模块一块 面包板一个 杜邦线若干
二、硬件连接:
三、实验代码:
#include <core.h> const int LCDdelay=10;
const int TriPin = 2;
const int EchoPin = 3;
float cm;
void lcdPosition(int row, int col) {
Serial.write(0xFE); //command flag
Serial.write((col + row*64 + 128)); //position
delay(LCDdelay);
}
void clearLCD(){
Serial.write(0xFE); //command flag
Serial.write(0×01); //clear command.
delay(LCDdelay);
}
void backlightOn() { //turns on the backlight
Serial.write(0x7C); //command flag for backlight stuff
Serial.write(157); //light level.
delay(LCDdelay);
}
void backlightOff(){ //turns off the backlight
Serial.write(0x7C); //command flag for backlight stuff
Serial.write(128); //light level for off.
delay(LCDdelay);
}
void serCommand(){ //a general function to call the command flag for issuing all other commands
Serial.write(0xFE);
} void setup()
{
Serial.begin(9600);
pinMode (TriPin, OUTPUT);
pinMode (EchoPin, INPUT);
} void loop()
{
digitalWrite (TriPin, LOW);
delayMicroseconds (2);
digitalWrite (TriPin, HIGH);
delayMicroseconds (10);
digitalWrite (TriPin, LOW);
cm = pulseIn (EchoPin, HIGH, 100000) / 58.0;
cm = (int (cm * 100.0)) / 100.0;
backlightOn ();
clearLCD ();
lcdPosition (0, 0);
Serial.print (“cm = “);
Serial.print (cm);
Serial.print (” LinkSprite”);
delay (1000);
}
四、实验结果:
当有阻挡物在超声波模块面前时候,就会在Serial 16×2 LCD上显示出阻挡物的距离 如开始的图一样。超声波模块成功测试到我与超声波模块的距离
|