第 1–26 行 · 自动门的接线、参数和四个状态
Servo.h 产生舵机控制脉冲。CLOSED_ANGLE = 0、OPEN_ANGLE = 90 是模型的目标角。开门距离 5 cm,离开距离 10 cm,保持 3000 ms,每隔 15 ms 走 1°。超声每 60000 μs 尝试一次,超时设 30000 μs。代码里 f 表示小数是浮点类型,UL 表示非负长整数。
DoorState 记录关、正在开、开、正在关,默认 CLOSED。角度也从 0 开始。lastServoStep 记上次改角时刻,lastPersonSeen 记最后检测到近物体的时刻,personPresent 存有人的判断结果。
展开原代码第 1–26 行
1 #include <Servo.h>
2
3 // Lab 4 - Match the wiring diagram provided by the student.
4 const byte TRIG_PIN = 8;
5 const byte ECHO_PIN = 7;
6 const byte SERVO_PIN = 9;
7
8 // Adjust these to suit the actual door mechanism.
9 const int CLOSED_ANGLE = 0;
10 const int OPEN_ANGLE = 90;
11 const float OPEN_DISTANCE_CM = 5.0f;
12 const float LEAVE_DISTANCE_CM = 10.0f; // Hysteresis
13 const unsigned long HOLD_OPEN_MS = 3000UL;
14 const unsigned long SERVO_STEP_MS = 15UL;
15 const unsigned long PING_PERIOD_US = 60000UL;
16 const unsigned long ECHO_TIMEOUT_US = 30000UL;
17
18 Servo doorServo;
19
20 enum DoorState { CLOSED, OPENING, OPEN, CLOSING };
21 DoorState doorState = CLOSED;
22 int currentAngle = CLOSED_ANGLE;
23 unsigned long lastServoStep = 0;
24 unsigned long lastPersonSeen = 0;
25 bool personPresent = false;
26