Serial port Arduino Serial.read()未显示正确的输出
我正在为arduino编写一个程序来控制一对步进电机。我从序列中读取所有数据并将其放入数组中。现在,这对风扇非常有效,但是当我在case语句中输入一个等于第二个值的值时,它会呕吐。其他的都行Serial port Arduino Serial.read()未显示正确的输出,serial-port,arduino,switch-statement,Serial Port,Arduino,Switch Statement,我正在为arduino编写一个程序来控制一对步进电机。我从序列中读取所有数据并将其放入数组中。现在,这对风扇非常有效,但是当我在case语句中输入一个等于第二个值的值时,它会呕吐。其他的都行 i.e.)from serial input: "F" output: "F" and the fan turns on/off but input: "a100" output: "a1" and noth
i.e.)from serial input: "F"
output: "F" and the fan turns on/off
but input: "a100"
output: "a1" and nothing the serial com freezes
Aduino Mega 2500 R3:
Arduino IDE 1.0.6
#include <Stepper.h>
#define FAN_PIN 9 // the fan is hooked up to pin 9
const int stepsPerRevolution = 200; // change this to fit the number of steps per
revolution for your motor
const int RPM = 30; // much over thirty is too fast to respond to
int step_mode = 4; // 4 = full, 8 = half
int yPosition = 0; // number of steps the motor has taken
byte byte_step; // serial only reads in bytes
long previous = stepsPerRevolution/2; // This may come in handy eventually idk
char dataIn[20];
char data;
int step_size[20];
int count = 0;
int count_new;
int i;
int num_steps = 0;
boolean neg = false; // Default to positive steps
boolean FAN = false; // Default to fan off
// initialize the stepper library on pins :
Stepper myStepper(stepsPerRevolution, 60,61,56,57, step_mode);
//Stepper(number_of_steps, motor_pin_1, motor_pin_2, motor_pin_3, motor_pin_4)
void loop() {
if (Serial.available()>0){
command = Serial.read();
while(data != 13) {
data = Serial.read();
if(data == '-') neg = true; // case you receive a negative, defaults to false (positive)
else{
dataIn[count] = data;
Serial.println(count);
count++; // count is NOT!!!!! equal to the number of relevant elements within the array
delay(1);
}
}
switch(command){
case 'F': // case to turn the fan on/off
if (FAN == false){
FAN = true;
analogWrite(FAN_PIN,90);
} // WRITE(FAN_PIN, HIGH); PWM because we have a 5V fan on a 12V pin
else if(FAN == true){
FAN = false;
digitalWrite(FAN_PIN,LOW); // turn the fan off
}
break;
case 'G': // the case of motor "a"
for(i=2; count-1; i++){
num_steps = num_steps *10 + ; //convert it to a base 10 number
}
break;
}
if(neg == true){
num_steps = num_steps*-1; // Make it negative then default it back to positive
neg = false;
}
myStepper.step(num_steps);
yPosition = yPosition + num_steps;
Serial.println(yPosition);
for(i=0; i<20; i++){ //clear out the data
dataIn[i] = 0;
}
count = 0;
num_steps = 0;
}
}时间延迟是一种非常不可靠的同步方式!消除延迟并收集等待可用性的字符,直到获得最终终止条件(可能是换行符)。然后解析。我从来没有意识到这样做是错误的。读一篇关于它的文章。我将有问题的代码更改为:`void loop{whileSerial.available>0&&data!='\n'{data=Serial.read;dataIn[count]=data;count++;}`但是问题仍然存在。@Chris Stratton没有可用数据时不退出,等待它,只退出到真正的换行符上进行分析。啊,gottcha。我尝试了这个'void loop{if Serial.available>0{data=Serial.read;dataIn[count]=data;count++;whiledata!='\n'{dataIn[count++]=data;count++;//count现在等于数组中相关元素的数量}}}'不,这仍然是混淆的,不起作用-您将用接收到的第一个非换行符无限填充内存。