[英]Controlling a stepper motor using Arduino and serial
我想创建一个仅接收(通过串行)两个命令的 Arduino 程序:“1”和“2”。 通过这些命令,我希望 Arduino 像这样操作步进电机:
我已经写了一个只能半途而废的代码:
#include <Stepper.h>
const int stepsPerRevolution = 1500;
int incomingByte;
Stepper myStepper(stepsPerRevolution, 11, 9, 10, 8);
void setup() {
myStepper.setSpeed(20);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
Serial.print("I received: ");
Serial.println(incomingByte);
if (incomingByte = "1") {
Serial.println("Moving clockwise...");
myStepper.step(stepsPerRevolution);
delay(500);
}
if (incomingByte = "2") {
Serial.println("Moving counterclockwise...");
myStepper.step(-stepsPerRevolution);
delay(500);
}
}
}
激活时,程序等待串行端口上的命令并设法读取它们。 问题在于,在两种情况下(1 和 2),电机首先顺时针移动,然后逆时针移动,这不是我想要达到的结果。
你能帮我做这件事吗?
使用比较运算而不是像这样的赋值运算符。由于变量是int
数据类型,因此不需要 1 左右的双引号。 在第一个 if 语句之后使用else
命令,这样只有一个命令会运行。
const int stepsPerRevolution = 1500;
int incomingByte;
Stepper myStepper(stepsPerRevolution, 11, 9, 10, 8);
void setup() {
myStepper.setSpeed(20);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
Serial.print("I received: ");
Serial.println(incomingByte);
if (incomingByte == 49) {
Serial.println("Moving clockwise...");
myStepper.step(stepsPerRevolution);
delay(500);
}
else
if (incomingByte == 50) {
Serial.println("Moving counterclockwise...");
myStepper.step(-stepsPerRevolution);
delay(500);
}
}
}
好的,这是最终的代码; 一切正常!
#include <Stepper.h>
const int stepsPerRevolution = 1500;
int incomingByte;
Stepper myStepper(stepsPerRevolution, 11, 9, 10, 8);
void setup() {
myStepper.setSpeed(20);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
Serial.print("I received: ");
Serial.println(incomingByte);
if (incomingByte == 49) {
Serial.println("Moving clockwise...");
myStepper.step(stepsPerRevolution);
delay(500);
}
else
if (incomingByte == 50) {
Serial.println("Moving counterclockwise...");
myStepper.step(-stepsPerRevolution);
delay(500);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.