/*
 * 电位器 -> 舵机 + OLED · Arduino UNO R3
 *
 * ADC+OLED 部分跟已验证通过的版本一模一样。
 * Servo 只在角度变化时才 write()，其余时间不动。
 * 不用 detach/attach，不用花活。
 */

#include <Servo.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define POT_PIN A1
#define SERVO_PIN 9
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_ADDR 0x3C

const int DEADBAND = 4;
const int ANGLE_MIN = 10;
const int ANGLE_MAX = 170;

Servo sg90;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

void setup() {
  Serial.begin(115200);

  // 1. 先 init OLED（这时候 Servo 还没 attach，Timer1 干净）
  Serial.println(F("OLED init..."));
  if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
    Serial.println(F("OLED FAIL"));
    while (1);
  }
  display.setTextColor(SSD1306_WHITE);
  Serial.println(F("OLED OK"));

  // 2. OLED 好了再开舵机
  sg90.attach(SERVO_PIN, 500, 2400);
  sg90.write(90);
  Serial.println(F("Servo OK"));
  Serial.println(F("=== ready ==="));
}

void loop() {
  int raw = analogRead(POT_PIN);
  static int lastRaw = -999;
  static int angle = 90;

  if (abs(raw - lastRaw) > DEADBAND) {
    angle = map(raw, 0, 1023, ANGLE_MIN, ANGLE_MAX);
    angle = constrain(angle, ANGLE_MIN, ANGLE_MAX);
    sg90.write(angle);
    lastRaw = raw;

    // 只在角度变化时打串口
    Serial.print(F("A1="));
    Serial.print(raw);
    Serial.print(F(" ang="));
    Serial.println(angle);
  }

  // 刷屏（每一步都刷）
  display.clearDisplay();
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println(F("Pot -> Servo"));
  display.drawFastHLine(0, 10, SCREEN_WIDTH, SSD1306_WHITE);
  display.setTextSize(3);
  display.setCursor(28, 22);
  display.print(angle);
  display.setTextSize(1);
  display.setCursor(0, 56);
  display.print(F("A1:"));
  display.print(raw);
  display.print(F(" a:"));
  display.print(angle);
  display.display();

  delay(50);
}
