快速上手Arduino -- 打印超声波模块测距信息到OLED屏幕上


快速上手Arduino – 打印超声波模块测距信息到OLED屏幕上

实现效果:

在这里插入图片描述
在这里插入图片描述


模块说明:
  • 使用的开发板是Arduino Uno R3版本
  • 使用了Arduino 硬件IIC通道 控制0.96寸OLED显示屏
  • 由于无法使用轮询的方式(笔者亲测会产生bug,超声波echo信息无法响应),因此使用了Arduino的中断响应系统,能满足信号采集的实时性。

引脚接线方法:
传感器引脚Arduino引脚
超声波-EchoPin2
超声波-TrigPin3
OLED屏幕-SCLA5
OLED屏幕-SDAA4

程序源码
#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引脚原理图
    image
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值