文章目錄
- 快速上手Arduino -- 列印超聲波模塊測距資訊到OLED螢屏上
- 實作效果:
- 模塊說明:
- 引腳接線方法:
- 程式原始碼
- 附錄
快速上手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引腳原理圖

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/149155.html
標籤:python
