|
xdm,我最近在做一个小车的项目,小车是由4个步进电机控制的,使用的是麦克纳姆轮。所以我需要在arduino里面写一段程序来控制步进电机走一段固定的距离。刚开始我写了一段程序想要实现小车的基本移动,设想的是通过控制步进电机使小车先向前再向后,然后向左,最后向右移动回到起点。最后实验下来的结果是,如果不加上左右的运动,小车只能前后运动,如果加上左右运动,理论上应该可以实现前后左右的运动了,但是结果是只能左右移动。想了很长时间,我觉得可能是步数的原因,但是不知道怎么去修改,所以向大佬们请教,希望大佬们能指出错误和不足的地方。代码如下:
#include <AccelStepper.h>
//定义电机控制用常量
const int enablePin = 8;
const int x_Step_Pin = 2;
const int x_Dir_Pin = 5;
const int y_Step_Pin = 3;
const int y_Dir_Pin = 6;
const int z_Step_Pin = 4;
const int z_Dir_Pin = 7;
const int a_Step_Pin = 12;
const int a_Dir_Pin = 13;
//定义走多少步
const int moveSteps = 1600;
//定义一个时间
const int delayTime = 200;
int Speed = 100;
//定义电机对象
AccelStepper stepperx(1, x_Step_Pin, x_Dir_Pin);
AccelStepper steppery(1, y_Step_Pin, y_Dir_Pin);
AccelStepper stepperz(1, z_Step_Pin, z_Dir_Pin);
AccelStepper steppera(1, a_Step_Pin, a_Dir_Pin);
void setup() {
pinMode(x_Step_Pin, OUTPUT);
pinMode(x_Dir_Pin, OUTPUT);
pinMode(y_Step_Pin, OUTPUT);
pinMode(y_Dir_Pin, OUTPUT);
pinMode(z_Step_Pin, OUTPUT);
pinMode(z_Dir_Pin, OUTPUT);
pinMode(a_Step_Pin, OUTPUT);
pinMode(a_Dir_Pin, OUTPUT);
pinMode(enablePin, OUTPUT);
digitalWrite(enablePin, LOW);
//设置最大速度和加速度
stepperx.setMaxSpeed(1000);
stepperx.setAcceleration(200);
steppery.setMaxSpeed(1000);
steppery.setAcceleration(200);
stepperz.setMaxSpeed(1000);
stepperz.setAcceleration(200);
steppera.setMaxSpeed(1000);
steppera.setAcceleration(200);
}
void loop(){
MFord();
MBack();
MLeft();
MRight();
//电机运动
stepperx.run();
steppery.run();
stepperz.run();
steppera.run();
}
void MFord() { //向前移动
if (stepperx.currentPosition() == 0) {
stepperx.moveTo(moveSteps);
}
if (steppery.currentPosition() == 0) {
steppery.moveTo(-moveSteps);
}
if (stepperz.currentPosition() == 0) {
stepperz.moveTo(moveSteps);
}
if (steppera.currentPosition() == 0) {
steppera.moveTo(-moveSteps);
}
return 0;
}
void MBack() { //向后移动
if (stepperx.currentPosition() == moveSteps) {
stepperx.moveTo(0);
}
if (steppery.currentPosition() == -moveSteps) {
steppery.moveTo(0);
}
if (stepperz.currentPosition() == moveSteps) {
stepperz.moveTo(0);
}
if (steppera.currentPosition() == -moveSteps) {
steppera.moveTo(0);
}
return 0;
}
void MLeft() { //向左移动
if (stepperx.currentPosition() == 0) {
stepperx.moveTo(-moveSteps);
}
if (steppery.currentPosition() == 0) {
steppery.moveTo(-moveSteps);
}
if (stepperz.currentPosition() == 0) {
stepperz.moveTo(moveSteps);
}
if (steppera.currentPosition() == 0) {
steppera.moveTo(moveSteps);
}
return 0;
}
void MRight() { //向右移动
if (stepperx.currentPosition() == -moveSteps) {
stepperx.moveTo(0);
}
if (steppery.currentPosition() == -moveSteps) {
steppery.moveTo(0);
}
if (stepperz.currentPosition() == moveSteps) {
stepperz.moveTo(0);
}
if (steppera.currentPosition() == moveSteps) {
steppera.moveTo(0);
}
return 0;
}
}
另外我仍然对怎么去控制步进电机走固定的距离感到很迷茫,步进电机的原理,距离的计算公式我都查阅过相关的资料,也看过一些相关的视频,但是就是不知道怎么去写程序。想请教一下各位大佬,怎么去写这段程序?
|
|