Created
August 5, 2026 11:12
-
-
Save N08-png/f49e94f54a066229593ed958806f96c1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include "DHT.h" | |
| #include <Wire.h> | |
| #include <LiquidCrystal_I2C.h> | |
| #define DHTPIN 4 | |
| #define DHTTYPE DHT11 | |
| DHT dht(DHTPIN, DHTTYPE); | |
| LiquidCrystal_I2C lcd(0x27, 16, 2); | |
| // ตัวแปรสำหรับเก็บตำแหน่งพิกัดการเคลื่อนที่ | |
| int posX_temp = -12; // ตำแหน่งเริ่มต้นของ Temp (เริ่มจากนอกจอด้านซ้าย) | |
| int posX_humid = 16; // ตำแหน่งเริ่มต้นของ Humid (เริ่มจากนอกจอด้านขวา) | |
| unsigned long previousMillis = 0; | |
| const long interval = 800; // ความเร็วในการขยับ (มิลลิวินาที) ยิ่งน้อยยิ่งวิ่งเร็ว | |
| float h = 0.0; | |
| float t = 0.0; | |
| void setup() { | |
| Serial.begin(115200); | |
| dht.begin(); | |
| lcd.init(); | |
| lcd.backlight(); | |
| lcd.clear(); | |
| } | |
| void loop() { | |
| // อ่านค่าจากเซนเซอร์ทุกๆ 1 วินาที | |
| static unsigned long lastDHTRead = 0; | |
| if (millis() - lastDHTRead >= 1000) { | |
| lastDHTRead = millis(); | |
| float newH = dht.readHumidity(); | |
| float newT = dht.readTemperature(); | |
| if (!isnan(newH) && !isnan(newT)) { | |
| h = newH; | |
| t = newT; | |
| } | |
| } | |
| // เคลื่อนที่ข้อความตามช่วงเวลา (interval) | |
| if (millis() - previousMillis >= interval) { | |
| previousMillis = millis(); | |
| // สร้างข้อความที่จะแสดง | |
| String tempStr = "Temp:" + String(t, 2) + (char)223 + "C"; | |
| String humidStr = "Humid:" + String(h, 2) + "%"; | |
| // เคลียร์หน้าจอเตรียมเขียนตำแหน่งใหม่ | |
| lcd.clear(); | |
| // --- บรรทัดที่ 1: Temp เลื่อนไปทางขวา ---> | |
| if (posX_temp < 16) { | |
| if (posX_temp >= 0) { | |
| lcd.setCursor(posX_temp, 0); | |
| lcd.print(tempStr); | |
| } else { | |
| // กรณีข้อความบางส่วนยังอยู่นอกจอฝั่งซ้าย | |
| lcd.setCursor(0, 0); | |
| lcd.print(tempStr.substring(-posX_temp)); | |
| } | |
| } | |
| // --- บรรทัดที่ 2: Humid เลื่อนไปทางซ้าย <--- | |
| if (posX_humid > -12) { | |
| if (posX_humid >= 0) { | |
| lcd.setCursor(posX_humid, 1); | |
| lcd.print(humidStr); | |
| } else { | |
| // กรณีข้อความบางส่วนหลุดออกไปทางซ้าย | |
| lcd.setCursor(0, 1); | |
| lcd.print(humidStr.substring(-posX_humid)); | |
| } | |
| } | |
| // คำนวณตำแหน่งถัดไป | |
| posX_temp++; // เลื่อนไปทางขวา (เพิ่มค่า X) | |
| posX_humid--; // เลื่อนไปทางซ้าย (ลดค่า X) | |
| // เมื่อข้อความวิ่งพ้นจอ ให้รีเซ็ตกลับไปเริ่มใหม่ | |
| if (posX_temp > 16) { | |
| posX_temp = -12; | |
| } | |
| if (posX_humid < -12) { | |
| posX_humid = 16; | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
807620832.911872.mp4