如何使我的代码循环(与arduino)
How to make my code loop (With arduino)
我已经在一个项目上工作了很长一段时间了,但是在它的最后阶段,我被我的代码循环所困。它运行一次,从那以后它就不让马达动了。我已经尝试了while
和if
语句,但每次我要求它移动时,它仍然不移动。
代码应该做的是接收来自websockets画布的信息,并使用该信息来查看直流电机是否向前或向后。
希望能找到解决办法!:)
#include <AFMotor.h>
int x = -10;
int y = -10;
int b = 0;
AF_DCMotor motor_shoulderx(1);
AF_DCMotor motor_shouldery(2);
AF_DCMotor motor_elbow(3);
AF_DCMotor motor_wrist(4);
void setup() {
motor_shoulderx.run(RELEASE);
motor_shouldery.run(RELEASE);
motor_elbow.run(RELEASE);
motor_wrist.run(RELEASE);
Serial.begin(9600);
}
void loop() {
uint8_t i;
while(Serial.available()) {
if (b == 0) {
x = Serial.read();
b =1;
}
else {
y = Serial.read();
b = 0;
}
if (x != -10) {
Serial.println("x is:");
Serial.println(x);
if(x > 200) {
motor_shoulderx.run(FORWARD);
for (i=0; i<255; i++) {
motor_shoulderx.setSpeed(i);
}
}
else {
motor_shoulderx.run(BACKWARD);
for (i=255; i!=0; i--) {
motor_shoulderx.setSpeed(i);
}
}
}
if (y != -10) {
Serial.println ("y is:");
Serial.println (y);
if (y > 200) {
motor_shouldery.run(FORWARD);
for (i=0; i<255; i++) {
motor_shouldery.setSpeed(i);
}
motor_elbow.run(FORWARD);
for (i=0; i<255; i++) {
motor_elbow.setSpeed(i);
}
motor_wrist.run(FORWARD);
for (i=0; i<255; i++) {
motor_wrist.setSpeed(i);
}
}
else {
motor_shouldery.run(BACKWARD);
for (i=255; i!=0; i--) {
motor_shouldery.setSpeed(i);
}
motor_elbow.run(BACKWARD);
for (i=255; i!=0; i--) {
motor_elbow.setSpeed(i);
}
motor_wrist.run(BACKWARD);
for (i=255; i!=0; i--) {
motor_wrist.setSpeed(i);
}
}
}
}
}
您必须使用另一个结构。目前,主循环由许多单独的for循环组成,它们依次执行。为了实现并行执行(我认为这是你想要的),你需要这样做:
int i;
void setup() {
i=255;
//...
}
void loop() {
i--;
motor_shoulderx.setSpeed(i);
motor_elbow.setSpeed(i);
if(i==0)i=255;
}
如果你需要更复杂的逻辑,你可以很容易地实现条件。如果需要延迟,则必须使用时间比较代码模式,如下所示:
unsigned long interval=1000; // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.
void setup() {
//...
}
void loop() {
if ((unsigned long)(millis() - previousMillis) >= interval) {
previousMillis = millis();
// ...
}
}
//...
总之,我认为重要的是主循环不应该被单个for语句延迟。
相关文章:
- 如何循环打印顶点结构
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- For 循环不会停止在 C++ Arduino
- 如何在Arduino中打破循环?
- 如何制作 arduino 串行循环(连续接收数字)
- Arduino无限循环
- Arduino 循环混淆
- 当条件处于活动状态时停止 arduino 循环
- 对于循环:LED 在 Arduino 上无法正确显示
- 串行读取字节 - Arduino 循环
- 如何调试为什么Arduino会中断while循环
- Arduino循环一次
- Arduino:极简主义循环状态机的问题
- Arduino UNO在执行更复杂的程序时意外循环Serial
- Arduino Lily Pad mp3,循环中循环与定时
- 函数不能正确循环与NeoPixels的Arduino
- Arduino循环/设置问题
- 如何使我的代码循环(与arduino)