oled
本篇结合温湿度传感器DHT11和OLED,将采集到的温湿度显示到OLED屏幕上。
OLED屏的VCC和GND分别连接开发板的3.3V和GND,OLED屏的SDA和SCL分别连接开发板A4和A5。DHT11模块VCC、GND分别连接到开发板的5V、GND,模块的DATA引脚连接开发板数字引脚2。
1#include < Arduino.h >
2#include < U8g2lib.h >
3#include < Wire.h >
4#include "DHT.h"
5
6#define DHTPIN 2
7#define DHTTYPE DHT11
8
9//iic驱动方式
10U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE);
11DHT dht(DHTPIN, DHTTYPE);
12
13void setup() {
14 u8g2.begin();
15 dht.begin();
16}
17
18char h_str[3];
19char t_str[3];
20float h;
21float t;
22
23void loop() {
24
25 h = dht.readHumidity();//读湿度
26 t = dht.readTemperature();//读温度(摄氏度)
27 strcpy(h_str, u8x8_u8toa(h, 2)); /* convert m to a string with two digits */
28 strcpy(t_str, u8x8_u8toa(t, 2)); /* convert m to a string with two digits */
29
30 u8g2.firstPage();
31 do {
32 u8g2.setFont(u8g2_font_fur20_tf);
33 u8g2.drawStr(0, 23, "T");
34 u8g2.drawStr(20, 23, ":");
35 u8g2.drawStr(40, 23, t_str);
36 u8g2.drawStr(90, 23, "C");
37
38 u8g2.drawStr(0, 63, "H");
39 u8g2.drawStr(20, 63, ":");
40 u8g2.drawStr(40, 63, h_str);
41 u8g2.drawStr(90, 63, "%");
42 } while ( u8g2.nextPage() );
43 delay(1000);
44}