[英]Arduino stepper motor loop weird behaviour
I am using a stepper motor with my Arduino and to turn it clockwise i made a function that turns the voltage of the wires on one at a time. 我在我的Arduino上使用了步进电机,并顺时针旋转它,所以我做了一个功能,可以一次打开一根电线的电压。 This works, however when i put the function in a loop it does not work.
这有效,但是当我将函数放入循环中时不起作用。
The code is: 代码是:
void setup() {
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
}
void turnRight(int delayTime) {
for(int i; i<=4; i++){
digitalWrite(9+i, LOW);
digitalWrite(10+i, HIGH);
delay(delayTime);
}
}
void turnLeft(int delayTime) {
for(int i; i<=4; i++){
digitalWrite(14-i, LOW);
digitalWrite(13-i, HIGH);
delay(delayTime);
}
}
void loop() {
int p=0;
while(p<=100){
turnRight(25);
p++;
}
}
The code makes the motor stutter, it goes left and right very quickly in kind of a vibrating motion, meaning the wires are probably turned on in the wrong order. 该代码使电动机停顿,并以一种振动的方式非常快速地左右移动,这意味着电线可能以错误的顺序接通。 However when i run this code:
但是,当我运行此代码:
void setup() {
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
}
void turnRight(int delayTime) {
for(int i; i<=4; i++){
digitalWrite(9+i, LOW);
digitalWrite(10+i, HIGH);
delay(delayTime);
}
}
void turnLeft(int delayTime) {
for(int i; i<=4; i++){
digitalWrite(14-i, LOW);
digitalWrite(13-i, HIGH);
delay(delayTime);
}
}
void loop() {
int p=0;
while(p<=100){
turnRight(25);
}
}
It does work, the motor runs smoothly and it does not stutter, the only difference is that i don't increment p in this code. 它确实可以工作,电动机运行平稳,并且不会卡死,唯一的区别是我没有在此代码中增加p。 Using a for-loop gives the same effect, incrementing the for-loop value makes the motor stutter.
使用for环会产生相同的效果,增加for环的值会使电机停顿。
在函数turnRight
和turnLeft
,for循环尚未使用int i=0
类的特定值初始化。我认为这是引起问题的部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.