快速上手Arduino – 打印超声波模块测距信息到OLED屏幕上
实现效果:
模块说明:
- 使用的开发板是Arduino Uno R3版本
- 使用了Arduino 硬件IIC通道 控制0.96寸OLED显示屏
- 由于无法使用轮询的方式(笔者亲测会产生bug,超声波echo信息无法响应),因此使用了Arduino的中断响应系统,能满足信号采集的实时性。
引脚接线方法:
传感器引脚 | Arduino引脚 |
---|---|
超声波-Echo | Pin2 |
超声波-Trig | Pin3 |
OLED屏幕-SCL | A5 |
OLED屏幕-SDA | A4 |
程序源码
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <SoftwareSerial.h>
/*OLED*/
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
#define NUMFLAKES 10
#define XPOS 0
#define YPOS 1
#define DELTAY 2
#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH 16
/*Bluetooth*/
// Pin10为RX,接HC05的TXD
// Pin11为TX,接HC05的RXD
SoftwareSerial BT(10, 11);
char BT_val;
/*Ultrasound*/
unsigned long elapsed;
unsigned int EchoPin = 2;
unsigned int TrigPin = 3;
void echo() {
noInterrupts();
int s = digitalRead(EchoPin);
if(s == HIGH) {
elapsed = micros(); // Echo 变为高电平时记下时间 t1
} else {
elapsed = micros() - elapsed; // Echo 变为低电平时记下时间 t2
}
interrupts();
}
// the setup function runs once when you press reset or power the board
void setup() {
/*Ultrasound*/
pinMode(TrigPin, OUTPUT); // 引脚TrigPin默认为低电平,15uS的高电平脉冲会触发发送测距超声包.
digitalWrite(TrigPin, LOW);
pinMode(EchoPin, INPUT);// 引脚EchoPin可中断,电平跳变会触发中断
attachInterrupt(digitalPinToInterrupt(EchoPin), echo, CHANGE);
/*OLED*/
elapsed = 0;
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3D (for the 128x64)
//delay(500);
Serial.begin(38400);
/*Bluetooth*/
Serial.println("BT is ready!");
BT.begin(38400); //HC-05默认,38400
}
// the loop function runs over and over again forever
void loop() {
while(true) {
// 发出 15微秒的脉冲.
digitalWrite(TrigPin, HIGH);
delayMicroseconds(15);
digitalWrite(TrigPin, LOW);
float sec = float(elapsed)/1000000;
float distance = (sec * 340/2)*100; // *100 米转换为厘米
if (Serial) {
Serial.print(sec*1000, 3);
Serial.print(" ms, ");
Serial.print(distance, 2);
Serial.print(" cm\n");
}
if (Serial.available()) {
BT_val = Serial.read();
BT.print(BT_val);
}
if (BT.available()) {
BT_val = BT.read();
Serial.print(BT_val);
}
display.clearDisplay(); // clears the screen and buffer
display.setTextSize(1); //选择字号
display.setTextColor(WHITE); //字体颜色
display.setCursor(0,0); //起点坐标
display.print("DIS: ");
display.print(distance, 3);
display.println(" CM");
display.display();
delay(100);
}
}
附录
- 附[1] Arduino引脚原理图