效果图
硬件说明
HC-SR04超声波距离传感器
Arduino pro mini
0.96'oled屏幕
led×5,杜邦线
HC-SR04 trig -> arduino pro mini 13
HC-SR04 echo -> arduino pro mini 12
0.96'oled SCL -> arduino pro mini 3
0.96'oled SDA -> arduino pro mini 5
下载程序部分略去
程序代码
使用的库 SR04提取码: g9e9,U8g2
#include <SR04.h>
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
//设备定义
SR04 sen = SR04(12, 13);
float distance;
int led[5] = {2, 4, 6, 8, 9};
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ 3, /* data=*/ 5, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display
void setup() {
Serial.begin(9600);
u8g2.begin();
}
void loop() {
// put your main code here, to run repeatedly:
distance = sen.GetDistance();
Serial.print(distance);
Serial.println(" cm");
u8g2.clearBuffer();
//u8g2.setFont(u8g2_font_fub30_tf);
u8g2.setFont(u8g2_font_courB24_tf);
u8g2.drawStr(0, 30, "Distance");
//u8g2.drawStr(0,40,distance);
// u8g2.setFont(u8g2_font_6x12_tn);
u8g2.setCursor(0, 64);
u8g2.print(distance);
u8g2.sendBuffer();
if (distance <= 5.0) {
digitalWrite(led[0], HIGH);
digitalWrite(led[1], LOW);
digitalWrite(led[2], LOW);
digitalWrite(led[3], LOW);
digitalWrite(led[4], LOW);
} else if (distance <= 10.0) {
digitalWrite(led[0], HIGH);
digitalWrite(led[1], HIGH);
digitalWrite(led[2], LOW);
digitalWrite(led[3], LOW);
digitalWrite(led[4], LOW);
} else if (distance <= 20.0) {
digitalWrite(led[0], HIGH);
digitalWrite(led[1], HIGH);
digitalWrite(led[2], HIGH);
digitalWrite(led[3], LOW);
digitalWrite(led[4], LOW);
} else if (distance <= 30.0) {
digitalWrite(led[0], HIGH);
digitalWrite(led[1], HIGH);
digitalWrite(led[2], HIGH);
digitalWrite(led[3], HIGH);
digitalWrite(led[4], LOW);
} else if (distance <= 40.0) {
digitalWrite(led[0], HIGH);
digitalWrite(led[1], HIGH);
digitalWrite(led[2], HIGH);
digitalWrite(led[3], HIGH);
digitalWrite(led[4], HIGH);
}
//delay(10);
}