#include <Adafruit_SSD1306.h>
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <DS18B20.h>
// 定义DS18B20数据口连接ESP32的4号IO上
#define ONE_WIRE_BUS 4
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// 初始连接在单总线上的单总线设备
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
const char* ssid = "yangyong";
const char* password = "";
String lastPrice;
unsigned long previousMillis = 0; //毫秒时间记录
const long interval = 1000; //时间间隔
//
DS18B20 ds18b20(4);
void setup() {
Serial.begin(115200);
pinMode(33, OUTPUT);
Serial.println("Dallas Temperature IC Control Library Demo");
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextSize(1.5);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0,0);
display.println("welcome Smart Water Dispenser");
display.println("Designed by Yangxiyuan");
display.display();
Serial.println("welcome Smart Water Dispenser");
display.display();
delay(5000);
// 初始库
sensors.begin();
}
void loop()
{
// 点亮LED灯
digitalWrite(33, HIGH);
delay(1000);
digitalWrite(33, LOW);
delay(1000);
// 记录温度
double temp = ds18b20.getTempC();//Read the temperature
delay(1000);
temp *= 0.0625;//The conversion accuracy is 0.0625/LSB
Serial.print(" ds18b20 Temperature: ");
Serial.print(temp);
Serial.println(" ℃");
delay(1000);
// Serial.print("Requesting temperatures...");
// sensors.requestTemperatures(); // 发送命令获取温度
// Serial.println("DONE");
// Serial.print("Temperature for the device 1 (index 0) is: ");
// Serial.println(sensors.getTempCByIndex(0));
// delay(500);
display.clearDisplay();
display.setTextSize(1.5);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0,0);
display.print("Temperature:");
display.print(temp);
display.println("℃");
// display.println(sensors.getTempCByIndex(0));
display.display();
delay(1000);
//以下段落相当于每秒读取前次温度,并发起新一次温度转换
// unsigned long currentMillis = millis(); //读取当前时间
// if (currentMillis - previousMillis >= interval) //如果和前次时间大于等于时间间隔
// {
// previousMillis = currentMillis; //更新时间记录
// float tempC = sensors.getTempCByIndex(0); //获取索引号0的传感器摄氏温度数据
// if (tempC != DEVICE_DISCONNECTED_C) //如果获取到的温度正常
// {
// Serial.print("\n当前温度是: ");
// Serial.print(tempC);
// display.print(tempC);
// display.display();
// Serial.println(" ℃");
// }
// sensors.requestTemperatures(); //发起新的温度转换
//}
//delay(20);
}
void printCenter(const String buf, int x, int y)
{
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(buf, x, y, &x1, &y1, &w, &h); //calc width of new string
display.setCursor((x - w / 2) + (128 / 2), y);
display.print(buf);
}