#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHT.h"
// DHT22
#define DHTPIN 19
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHT22); // 引脚 类型:比如DHT11,DHT22
// OLED
#define WIDTH 128
#define HEIGHT 64
// #define RESET -1
#define ADDRESS 0X3C
Adafruit_SSD1306 display = Adafruit_SSD1306(WIDTH, HEIGHT, &Wire, -1);
SemaphoreHandle_t xoled = NULL;
TickType_t timeOut = 1000; // 用于获取信号量的Timeout 1000 ticks
typedef struct
{
float temperature;
float humidity;
} Dht22;
Dht22 dht22;
void DHT22Task(void *ptParam)
{
while (1)
{
if (xSemaphoreTake(xoled, timeOut) == pdPASS)
{
dht22.temperature = dht.readTemperature();
dht22.humidity = dht.readHumidity();
// Serial.println(dht22.temperature);
xSemaphoreGive(xoled); // 释放钥匙
}
else
{
}
vTaskDelay(500);
}
}
void displayoled(void *ptParam)
{
display.clearDisplay(); // 清理显示屏
display.setTextSize(1); // 字体大小
while (1)
{
if (xSemaphoreTake(xoled, timeOut) == pdPASS)
{
display.clearDisplay();
display.setCursor(0, 0); // 设置光标
display.setTextColor(2); // 设置颜色
display.println(dht22.temperature); // 打印字体
display.setCursor(0, 20); // 设置光标
display.setTextColor(2); // 设置颜色
display.println(dht22.humidity); // 打印字体
display.display();
xSemaphoreGive(xoled); // 释放钥匙
}
else
{
}
vTaskDelay(500);
}
}
void setup()
{
Serial.begin(9600);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
dht.begin();
xoled = xSemaphoreCreateMutex(); //创建MUTEX
xTaskCreate(DHT22Task, "DHT22", 1024 * 8, NULL, 1, NULL);
vTaskDelay(500);
// xTaskCreate(ledTask, "led2", 1024 * 1, (void *)&led2, 1, NULL);
xTaskCreate(displayoled, "displayoled", 1024 * 8, NULL, 1, NULL);
}
void loop()
{
// float temperature = dht.readTemperature();
// float humidity = dht.readHumidity();
// Serial.print(humidity);
// delay(600);
}