#include <Wire.h>
#include <U8g2lib.h>
#if defined(ESP32)
#define ANALOG_PIN 4
#elif defined(ESP8266)
#define ANALOG_PIN A0
#define SDA_PIN 4
#define SCL_PIN 5
#endif
// SSD1106/SH1106 จอ I2C
U8G2_SH1106_128X64_NONAME_F_HW_I2C display(U8G2_R0, U8X8_PIN_NONE);
int meterValue = 0;
void setup() {
#if defined(ESP8266)
Wire.begin(SDA_PIN, SCL_PIN);
#endif
display.begin();
}
void loop() {
int raw = analogRead(ANALOG_PIN);
#if defined(ESP8266)
meterValue = map(raw, 0, 1023, 0, 180);
#else
meterValue = map(raw, 0, 4095, 0, 180);
#endif
display.clearBuffer();
drawMeter(meterValue);
display.sendBuffer();
delay(100);
}
void drawMeter(int value) {
// วงกลมหน้าปัด (เหมือนโค้ดเดิม)
for (int r = 30; r > 28; r--) {
display.drawCircle(44, 48, r);
}
display.drawDisc(44, 48, 2); // จุดกลาง
// ลบส่วนล่างของหน้าปัด (เหมือนโค้ดเดิม)
display.setDrawColor(0);
display.drawBox(0, 55, 75, 10);
display.setDrawColor(1);
drawScale(); // วาดตัวเลข 0–180 แบบเดิม
// เข็ม
float angle = map(value, 0, 180, -180, 0);
float radian = angle * PI / 180;
int x1 = 44 + (22 * cos(radian));
int y1 = 48 + (22 * sin(radian));
display.drawLine(44, 48, x1, y1);
// แสดงค่า Value มุมขวาบน (เหมือนเดิม)
display.setFont(u8g2_font_5x8_tr);
display.setCursor(90, 11);
display.print("Value:");
display.setCursor(105, 23);
display.print(value);
}
void drawScale() {
display.setFont(u8g2_font_5x8_tr);
// ตัวเลขตำแหน่งเหมือนโค้ดเดิมทั้งหมด
display.setCursor(4, 48); display.print("0");
display.setCursor(3, 28); display.print("30");
display.setCursor(19, 11); display.print("60");
display.setCursor(40, 6); display.print("90");
display.setCursor(62, 11); display.print("120");
display.setCursor(75, 28); display.print("150");
display.setCursor(80, 48); display.print("180");
// ขีดสเกลย่อยทุก 15° เหมือนเดิม
for (int i = 0; i <= 12; i++) {
float angle = map(i * 15, 0, 180, -180, 0);
float radian = angle * PI / 180;
int x_start = 44 + (24 * cos(radian));
int y_start = 48 + (24 * sin(radian));
int x_end = 44 + (26 * cos(radian));
int y_end = 48 + (26 * sin(radian));
display.drawLine(x_start, y_start, x_end, y_end);
}
}