快速上手Arduino -- 打印超声波模块测距信息到OLED屏幕上
生活随笔
收集整理的這篇文章主要介紹了
快速上手Arduino -- 打印超声波模块测距信息到OLED屏幕上
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 快速上手Arduino -- 打印超聲波模塊測距信息到OLED屏幕上
- 實現效果:
- 模塊說明:
- 引腳接線方法:
- 程序源碼
- 附錄
快速上手Arduino – 打印超聲波模塊測距信息到OLED屏幕上
實現效果:
模塊說明:
- 使用的開發板是Arduino Uno R3版本
- 使用了Arduino 硬件IIC通道 控制0.96寸OLED顯示屏
- 由于無法使用輪詢的方式(筆者親測會產生bug,超聲波echo信息無法響應),因此使用了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 bufferdisplay.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引腳原理圖
總結
以上是生活随笔為你收集整理的快速上手Arduino -- 打印超声波模块测距信息到OLED屏幕上的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 快速上手ANTLR--在Windows环
- 下一篇: [转]自动驾驶基础--路径规划