增加个单限位开关
电机向零点方向移动,触碰限位开关。触碰后,控制器记录下“这是极限位置”,然后反向移动一个固定的距离(比如5mm),将这个位置设定为“软件零点”。
将限位开关安装在你想设置为“零点”的机械位置。例如,如果你的电机带动一个螺杆推动滑块,那么就把限位开关安装在滑块行程的最左端或最右端。
电气连接:
电机连接ULN2003驱动板,再连接到主控板。
限位开关的三根线(VCC, GND, 信号)连接到主控板。信号线连接到一个数字输入引脚,并启用上拉电阻。
对应的Arduino伪代码逻辑如下
// 引脚定义
const int motorPin1 = 8;
const int motorPin2 = 9;
const int motorPin3 = 10;
const int motorPin4 = 11;
const int limitSwitchPin = 2; // 限位开关接在2号引脚
// 电机步序
int stepSequence[8][4] = { ... }; // 标准的28BYJ-48半步序列
int stepsPerRevolution = 4096; // 32(步序数)* 64(减速比) / 4 = 4096 半步一圈
bool isHomed = false;
long currentPosition = 0; // 绝对位置,单位是“步”
void setup() {
// 初始化引脚
pinMode(limitSwitchPin, INPUT_PULLUP);
// ... 初始化电机引脚
Serial.begin(9600);
// 上电后首先执行回零
homeMotor();
}
void loop() {
if (!isHomed) {
// 如果没回零,什么都不做,或者等待回零
return;
}
// 这里是你的正常控制代码
// 例如:moveToPosition(20 * stepsPerRevolution); // 走20圈
}
// !!!核心回零函数!!!
void homeMotor() {
Serial.println("开始回零...");
// 1. 向零点方向移动,直到触发限位开关
// 注意:取决于你的安装,可能是顺时针或逆时针
while (digitalRead(limitSwitchPin) == HIGH) { // 假设开关常态高电平,触发时拉低
// 执行一步,向“回零方向”转动
stepMotor(-1); // -1 代表回零方向
delayMicroseconds(1000); // 控制速度,慢速回零
}
Serial.println("触碰到限位开关");
// 2. 碰到开关后,立即停止(这个循环已经跳出)
// 3. 反向移动一段固定距离,离开开关
// 假设反向移动50步(约0.7圈),这个距离要确保机构完全离开开关的触发区
int backupSteps = 50;
for (int i = 0; i < backupSteps; i++) {
stepMotor(1); // 1 代表离开零点的方向
delay(5);
}
Serial.println("反向离开限位开关");
// 4. !!!关键步骤:将当前位置设为绝对零点!!!
currentPosition = 0;
isHomed = true;
Serial.println("回零完成!当前位置已重置为0。");
}
// 控制电机走一步的函数
// direction: -1 是回零方向, 1 是离开零点方向
void stepMotor(int direction) {
static int currentStep = 0;
currentStep += direction;
if (currentStep >= 8) currentStep = 0;
if (currentStep < 0) currentStep = 7;
// 根据stepSequence[currentStep]设置电机引脚高低电平
// ... 具体驱动代码
// 更新绝对位置
currentPosition += direction;
}
// 基于绝对位置的移动函数(回零后才能用)
void moveToPosition(long targetSteps) {
long stepsToMove = targetSteps - currentPosition;
int direction = (stepsToMove > 0) ? 1 : -1;
stepsToMove = abs(stepsToMove);
for (long i = 0; i < stepsToMove; i++) {
stepMotor(direction);
delay(3); // 根据需要的速度调整
}
}
|