Arduino 测距和OLED显示

oled 型号是128*64IIC的,参考了几个资料。我用的是U8glib。 遇到的最大麻烦就是现实距离,数字转换为char, 试了很多次,最后发现用itoa , 浮点用dtostrf。 定义char时要有长度,否则转换是会出乱码。

todo: 如何设定好刷新显示的时间

源代码

#include "U8glib.h"

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);  // I2C / TWI

long duration;
int distance;
int No=0;    //测距刷新次数
char  disTxt[20], c[10];
const int trig=10;
const int echo=9;

void draw(void) {

// graphic commands to redraw the complete screen should be placed here

u8g.setFont(u8g_font_unifont);

//u8g.setFont(u8g_font_osb21);
Serial.println(No);
itoa(No, disTxt, 10);
u8g.drawStr( 0, 22, disTxt);
itoa(distance, disTxt, 10);
u8g.drawStr( 0, 48, disTxt);
Serial.println(disTxt);
// float  f=3.1415;
// dtostrf(f,1,2,c);
// Serial.println(c);
No++;

}

int calculateDistance(){
    digitalWrite(trig, LOW); 
    delayMicroseconds(2);
     digitalWrite(trig, HIGH); 
    delayMicroseconds(10);
    digitalWrite(trig, LOW);
    duration = pulseIn(echo, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
    distance= duration*0.034/2;
    return distance;
}


void setup(void) {
   Serial.begin(9600);
  Serial.println("welcome to arduino");
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
}

void loop(void) {

// picture loop

u8g.firstPage();

do {
distance=calculateDistance();
draw();

} while( u8g.nextPage() );

// rebuild the picture after some delay

delay(1000);

}

https://www.jianshu.com/p/f70bee2dad1e

U8glib wiki资料 里面能告诉你很多关于硬件接线,代码的使用等等

U8glib in Google Code 访问这个页面需要翻墙,否则无法阅读

U8glib 使用手册查询 英文 需要翻墙使用,里面能够让你了解到很多U8glib库里面的方法和函数

这里说的SDA SLC连接A4 A5,我用的就是板上的SDA 和SLC

 

https://blog.csdn.net/TonyIOT/article/details/96367511  这里用的adafruit 库

https://blog.csdn.net/u012997311/article/details/83024472 这里用了getmode, 我没用,也没问题

https://blog.csdn.net/TonyIOT/article/details/103269514 这个用了adafruit库,显示距离是直接用int 类型没问题,省去了转换字符的操作。



 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值