Arduino+HC-SR04超声波模块+OLED显示
1)超声波测距的代码从我之前发的文章中学习
使用HC-SR04超声波模块与Arduino结合进行测距并串口显示
2)OLED的显示也可以从下面这篇文章学习
Arduino驱动OLED显示屏
!!结合了以上的知识,实现以下项目就很简单了。
1、项目简介
使用Arduino为控制核心,使用HC-SR04超声波测距模块进行距离的测量,将测量结果显示在SSD1306 OLED显示屏上,通过判断距离的远近来点亮或熄灭LED。
2、电路连接
3、程序代码
#include <splash.h>#include <Wire.h>#include <Adafruit_GFX.h>#include <Adafruit_SSD1306.h>//引入各种需要的库#define OLED_RESET 4const int pingPin = 2; const int echoPin = 3; int LED = 5; long Fdistance=0,duration;Adafruit_SSD1306 display(128, 64, &Wire, OLED_RESET);//声明OLEDvoid setup() {Serial.begin(9600); // Starting Serial TerminalpinMode(LED,OUTPUT);//设置LED输出pinMode(pingPin, OUTPUT);//设置触发引脚输出pinMode(echoPin, INPUT);//设置传出信号回响为输出digitalWrite(LED, LOW);//设置OLED显示屏的参数display.begin(SSD1306_SWITCHCAPVCC, 0x3C);display.setTextColor(WHITE);//开像素点发光display.clearDisplay();//清屏display.setTextSize(2); //设置字体大小}void Distance_test() // 量出前方距离 {digitalWrite(pingPin, LOW);delayMicroseconds(2);digitalWrite(pingPin, HIGH);delayMicroseconds(10);digitalWrite(pingPin, LOW);//产生一个10微秒的高电平触发信号duration = pulseIn(echoPin, HIGH); // 读取高电平时间(单位:微秒)Fdistance= (duration*0.034)/2; //计算距离 } //使用取模软件取的“距离”的模。static const unsigned char PROGMEM ju_16x16[] = {0x00,0x00,0x7D,0xFE,0x45,0x00,0x45,0x00,0x45,0x00,0x7D,0xFC,0x11,0x04,0x11,0x04,0x5D,0x04,0x51,0x04,0x51,0xFC,0x51,0x00,0x5D,0x00,0xE1,0x00,0x01,0xFE,0x00,0x00,//"距",0};static const unsigned char PROGMEM li_16x16[] = {0x02,0x00,0x01,0x00,0xFF,0xFE,0x00,0x00,0x14,0x50,0x13,0x90,0x14,0x50,0x1F,0xF0,0x01,0x00,0x7F,0xFC,0x42,0x04,0x44,0x44,0x4F,0xE4,0x44,0x24,0x40,0x14,0x40,0x08,//"离",1};void loop() {Distance_test(); //测量前方距离Serial.println(Fdistance);//对LED进行控制if(Fdistance < 15) //距离小于15cm,灯灭{digitalWrite(LED, LOW);delay(50);}if(Fdistance > 15)//距离大于15cm,灯亮{digitalWrite(LED, HIGH);delay(50);}//对OLED显示屏进行控制display.clearDisplay();//清屏display.drawBitmap(0,5,ju_16x16,16,16,SSD1306_WHITE);display.drawBitmap(20,5,li_16x16,16,16,SSD1306_WHITE);//显示“距离”两字display.setCursor(40,5);//设置光标位置display.print(Fdistance);//显示距离具体数值display.println("cm");display.drawRect(0, 33, 128, 12, WHITE);//绘制进度条display.fillRect(2, 35, map(Fdistance, 2, 15, 2, 124), 8, WHITE);//map(要映射的值,旧区间初值,旧区间终值,新区间初值,新区间终值)display.display();//开显示}
4、效果展示
OLED显示超声波模块测量的距离
参考的文章:
Arduino 超声波测距+OLED显示