C++
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#define DHTPIN 6
#define DHTTYPE DHT11
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
DHT dht(DHTPIN, DHTTYPE);
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// ---- ตั้งค่าพื้นที่กราฟ ----
#define GRAPH_X 0
#define GRAPH_Y 10
#define GRAPH_WIDTH 128
#define GRAPH_HEIGHT 44
// เก็บค่าอุณหภูมิและความชื้นย้อนหลัง 128 จุด (เต็มจอ)
float tempHistory[SCREEN_WIDTH];
float humiHistory[SCREEN_WIDTH];
uint8_t dataIndex = 0;
void setup() {
Serial.begin(115200);
Wire.begin();
dht.begin();
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
display.setTextColor(WHITE);
// ข้อความต้อนรับ
display.setTextSize(2);
display.setCursor(10, 20);
display.println(F("HELLO!"));
display.display();
delay(2000);
// เคลียร์ history
for (int i = 0; i < SCREEN_WIDTH; i++) {
tempHistory[i] = 0;
humiHistory[i] = 0;
}
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println(F("Failed to read from DHT sensor!"));
delay(2000);
return;
}
// บันทึกค่าลง history (แบบ circular)
tempHistory[dataIndex] = t;
humiHistory[dataIndex] = h;
dataIndex = (dataIndex + 1) % SCREEN_WIDTH;
// แสดงผล Serial
Serial.print(F("Temp: "));
Serial.print(t, 1);
Serial.print(F(" °C | Hum: "));
Serial.print(h, 0);
Serial.println(F(" %"));
// --- วาดหน้าจอ ---
display.clearDisplay();
// วาดกรอบหลัก
display.drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, WHITE);
// แสดงค่าแบบตัวเลขด้านบน
display.setTextSize(1);
display.setCursor(4, 1);
display.print(F("T:"));
display.print(t, 1);
display.print(F("C"));
display.setCursor(64, 1);
display.print(F("H:"));
display.print(h, 0);
display.print(F("%"));
// --- วาดกราฟอุณหภูมิ (สีขาวเต็ม) ---
drawGraph(tempHistory, GRAPH_Y, 20.0, 40.0, WHITE); // ช่วง 20-40°C
// --- วาดกราฟความชื้น (ทับด้วยเส้นบาง) ---
drawGraph(humiHistory, GRAPH_Y, 20.0, 90.0, WHITE); // ช่วง 20-90%
// เส้นแบ่งกลาง (แยก Temp กับ Hum)
display.drawFastHLine(0, GRAPH_Y + GRAPH_HEIGHT/2, SCREEN_WIDTH, WHITE);
display.display();
delay(500); // อัปเดตทุก 2 วินาที
}
// ฟังก์ชันวาดกราฟเส้นเลื่อน
void drawGraph(float history[], int yOffset, float minVal, float maxVal, uint16_t color) {
int prevY = 0;
bool first = true;
for (int x = 0; x < SCREEN_WIDTH; x++) {
int idx = (dataIndex + x) % SCREEN_WIDTH;
float value = history[idx];
// แปลงค่าเป็นพิกเซล
int graphY = GRAPH_HEIGHT - (int)map(constrain(value, minVal, maxVal), minVal, maxVal, 0, GRAPH_HEIGHT);
// แบ่งครึ่งจอ: บน = อุณหภูมิ, ล่าง = ความชื้น
int plotY = yOffset + (color == WHITE && value >= 50 ? 0 : GRAPH_HEIGHT/2) + graphY / 2;
// วาดเส้นเชื่อม
if (!first) {
display.drawLine(x - 1, prevY, x, plotY, color);
} else {
first = false;
}
prevY = plotY;
}
}