#include <Arduino.h>

// --- 硬件配置 ---
#define POLE_PAIRS 4
#define CURRENT_MAX 400
#define CURRENT_PIN A0

// 引脚寄存器快速映射
// SD_A = 8 (PB0), SD_B = 5 (PD5), SD_C = 6 (PD6)
// IN_A = 9 (OC1A), IN_B = 10 (OC1B), IN_C = 3 (OC2B)

// 预先计算好的快速端口掩码表 [step][0]=PORTB_MASK, [step][1]=PORTD_MASK
const uint8_t sd_portb_mask[6] = { 0x01, 0x01, 0x00, 0x01, 0x01, 0x00 };
const uint8_t sd_portd_mask[6] = { 0x20, 0x40, 0x60, 0x20, 0x40, 0x60 };

const byte hall_to_step[8]     = { 0, 0, 2, 1, 4, 5, 3, 0 };
const byte hall_to_step_rev[8] = { 0, 3, 5, 4, 1, 2, 0, 0 };

enum MotorState { STATE_IDLE, STATE_RUNNING, STATE_WAIT_REV };
MotorState m_state = STATE_IDLE;

// --- 中断与高速测速变量 (6拍滑动窗口) ---
volatile unsigned long dt_history[6] = {0};
volatile uint8_t dt_idx = 0;
volatile unsigned long dt_sum_6step = 0;
volatile unsigned long last_comm_time = 0;
volatile uint8_t last_hall_state = 0;
volatile bool motor_running = false;
volatile bool reverse = false;

// --- PID 控制器结构体 ---
struct PIDController {
  float Kp = 0.08;
  float Ki = 0.02;
  float Kd = 0.001;
  float integral = 0;
  float last_err = 0;
  float out_min = 5;
  float out_max = 180;

  float compute(float target, float current, float dt) {
    float err = target - current;
    integral += err * dt;
    // 抗积分饱和
    integral = constrain(integral, -50.0f, 50.0f);
    float derivative = (err - last_err) / dt;
    last_err = err;
    float output = (Kp * err) + (Ki * integral) + (Kd * derivative);
    return constrain(output, out_min, out_max);
  }

  void reset() {
    integral = 0;
    last_err = 0;
  }
} pid;

// 函数声明
void setPWMDuty(uint8_t d);
void writeCommFast(uint8_t s);
uint8_t readHallState();

// --- 极限性能 Hall 中断 ---
ISR(PCINT2_vect) {
  if (!motor_running) return;
  unsigned long now = micros();

  // 快速读取并解析 Hall (消除高位多重移位)
  uint8_t p = PIND;
  uint8_t state = 0;
  if (p & (1 << 4)) state |= 4; // PD4 -> Hall C
  if (p & (1 << 7)) state |= 2; // PD7 -> Hall B
  if (p & (1 << 2)) state |= 1; // PD2 -> Hall A

  if (state == last_hall_state || state == 0 || state > 6) return;

  // 极速换相输出
  uint8_t step = reverse ? hall_to_step_rev[state] : hall_to_step[state];
  writeCommFast(step);

  // 6 拍环形滑动窗口:每次中断都更新转速,响应速度提升 6 倍且不受安装不对称影响
  unsigned long dt = now - last_comm_time;
  if (dt > 30 && dt < 100000) {
    dt_sum_6step -= dt_history[dt_idx];
    dt_history[dt_idx] = dt;
    dt_sum_6step += dt;
    if (++dt_idx >= 6) dt_idx = 0;
  }

  last_comm_time = now;
  last_hall_state = state;
}

// 极速端口换相控制函数(替代原有慢速 digitalWrite)
inline void writeCommFast(uint8_t s) {
  // 1. 设置上桥臂 PWM 输出通道
  switch(s) {
    case 0: case 1: // A 相 PWM 开
      TCCR1A = (TCCR1A | (1 << COM1A1)) & ~(1 << COM1B1);
      TCCR2A &= ~(1 << COM2B1);
      break;
    case 2: case 3: // B 相 PWM 开
      TCCR1A = (TCCR1A | (1 << COM1B1)) & ~(1 << COM1A1);
      TCCR2A &= ~(1 << COM2B1);
      break;
    case 4: case 5: // C 相 PWM 开
      TCCR2A |= (1 << COM2B1);
      TCCR1A &= ~((1 << COM1A1) | (1 << COM1B1));
      break;
  }

  // 2. 快速设置下桥臂使能 SD 引脚 (单周期掩码操作)
  PORTB = (PORTB & ~0x01) | sd_portb_mask[s]; // SD_A -> Pin 8 (PB0)
  PORTD = (PORTD & ~0x60) | sd_portd_mask[s]; // SD_B (PD5), SD_C (PD6)
}

// 读取当前霍尔物理状态
inline uint8_t readHallState() {
  uint8_t p = PIND;
  uint8_t state = 0;
  if (p & (1 << 4)) state |= 4;
  if (p & (1 << 7)) state |= 2;
  if (p & (1 << 2)) state |= 1;
  return state;
}

// 获取瞬时平滑转速
float getFastRPM() {
  unsigned long dt_snapshot;
  unsigned long last_t;

  uint8_t sreg = SREG;
  noInterrupts();
  dt_snapshot = dt_sum_6step;
  last_t = last_comm_time;
  SREG = sreg;

  // 停转判断:超过 120ms 无换相判定为停转
  if (micros() - last_t > 120000 || dt_snapshot == 0) return 0;

  // RPM = 60 * 1,000,000 / ( (dt_sum_6step / 6) * 6 * POLE_PAIRS )
  // 约分后即为:
  return 60000000.0f / ((float)dt_snapshot * POLE_PAIRS);
}

// 启动电机(瞬时自定位起动,彻底告别盲步进)
void startMotor() {
  uint8_t state = readHallState();
  if (state >= 1 && state <= 6) {
    uint8_t step = reverse ? hall_to_step_rev[state] : hall_to_step[state];
    writeCommFast(step);
    last_comm_time = micros();
    last_hall_state = state;
    motor_running = true;
    m_state = STATE_RUNNING;
  }
}
回复主楼