我是Arduino编程的新手,并且花了几天时间才开始这么做,但似乎无法弄清楚为什么这段代码无效。
我正在尝试使用业余级遥控器RX / TX来控制步进电机。
我有一个RC接收器向我的Arduino发送1000到2000的模拟值。如果该信号为1000,我想在步进器上制作1000 = -360度,在步进器上制作2000 = +360度。
我从接收器接收到正确的信号并将它们打印到串行监视器,但我似乎无法用这个值控制步进电机。这个电机只是在第一个while循环中卡住,并继续沿1个方向旋转。
int ch1 = 0; // RC Reciever Channel Value
int ch1previous = 0; // RC Receiver Channel Previous Value
int PUL=7; //define Pulse pin of stepper driver
int DIR=6; //define Direction pin of stepper driver
int ENA=5; //define Enable Pin of stepper driver
void setup() {
pinMode (PUL, OUTPUT); // Stepper Driver Pulse Pin
pinMode (DIR, OUTPUT); // Stepper Driver Direction Pin
pinMode (ENA, OUTPUT); // Stepper Driver Enable Pin
pinMode(3, INPUT); // RC Reciever Pin Input
Serial.begin(9600);
}
void loop() {
ch1 = pulseIn(3, HIGH, 50000); // Read RC Reciever Channel Value
while ( ch1 > ch1previous) { // If CH1 is greater than CH1Previous run the differance
for ( int i = ch1; i < ch1previous; i++);{ // in steps to maintain the setpoint value in forwared position
digitalWrite(DIR,HIGH);
digitalWrite(ENA,HIGH); // pulsing stepper motor in forward motion
digitalWrite(PUL,HIGH);
delayMicroseconds(50);
digitalWrite(PUL,LOW);
delayMicroseconds(50);
}
}
while ( ch1 < ch1previous) { // if CH1 is less than CH1Previous run the differance
for ( int i = ch1; i<ch1previous; i--);{ // in steps to maintain the setpoint value in reverse motion
digitalWrite(DIR,LOW);
digitalWrite(ENA,HIGH); // pulsing stepper motor in reverse motion
digitalWrite(PUL,HIGH);
delayMicroseconds(50);
digitalWrite(PUL,LOW);
delayMicroseconds(50);
}
}
Serial.print ("Channel 1: "); // print text to the serial monitor
Serial.println(ch1); // print ch1 value to the serial monitor and end line
Serial.print("CH1 Previous: "); // print text to the serial monitor
Serial.println(ch1previous); // print ch1previous value to the serial monitor and end line
ch1previous = ch1; // remember the previous value from ch1
delay(500); // just to clean up the serial monitor
}
答案 0 :(得分:1)
能
ch1 = pulseIn(3, HIGH, 50000)
曾经是一个负面的价值?如果没有,那么当你考虑这个陈述时,这可以解释这种行为:
while ( ch1 > ch1previous) {
和ch1previous
初始化为零。
答案 1 :(得分:1)
如果while
条件一旦启动,它们将无限期地继续运行。正如您在评论If CH1 is greater than CH1Previous run the difference
中所做的那样,这些条件必须由if statements
替换。也就是说,将它们设为if(ch1 > ch1previous)
和else if(ch1 < ch1previous)
。并且for循环的条件也应该颠倒,根据if条件限制它们。
完成这些更改后,您的代码将变为类似
void loop() {
ch1 = pulseIn(3, HIGH, 50000);
if ( ch1 > ch1previous) {
for ( int i = ch1; i > ch1previous; i--){
//code
}
}
else if ( ch1 < ch1previous) {
for ( int i = ch1; i<ch1previous; i++){
//code
}
}
...
}