我在Arduino上制作了G代码阅读器,但它停止阅读。它有很多"休息;"我还有很多while循环和开关,所以我认为当我打开循环/切换时,它会破坏所有。
另一个想法是,它会出现某种循环,但我无法弄清楚循环的位置。
这是我的代码:
void Gcode(){
String yy,xx,gg;
char text[64];
int number=1;
while(number!=3){
while (Serial.available()>0) {
delay(3); //delay to allow buffer to fill
char c = Serial.read();
Serial.println(c);
switch(c){
case 'G':
//read_number()
while (Serial.available()>0) {
char k = Serial.read();
if(k==' ' || k=='\n'){
break;
}
else{
gg+=k;
}
}
switch(gg.toInt()){
case 1:
Serial.println(gg);
while (Serial.available()>0) {
c = Serial.read();
Serial.println(c);
switch(c){
case 'X':
while (Serial.available()>0) {
char k = Serial.read();
if(k==' ' || k=='\n'){
break;
}
else{
xx+=k;
}
}
char buf[xx.length()];
xx.toCharArray(buf,xx.length());
x2=atof(buf);
Serial.println(x2);
break;
case 'Y':
while (Serial.available()>0) {
char k = Serial.read();
if(k==' ' || k=='\n'){
break;
}
else{
yy+=k;
}
}
Serial.println(yy);
char buf2[yy.length()];
yy.toCharArray(buf2,yy.length());
y2=atof(buf2);
break;
case 'E':
break;
case 'F':
break;
default:
Serial.print("the end");
}
Serial.print("out of switch");
}
break;
case 2:
break;
default:
Serial.print("nothing");
}
break;
case '\n':
number=3;
break;
default:
Serial.print("default");
}
}
}
if(sizeof(yy)>0){
yy="";
xx="";
gg="";
}
Serial.print("quit");
}
当我发送G1 X10.00 Y-100.00时 \ n 仅打印: G 1 X 10.00 出了s
答案 0 :(得分:0)
你最大的问题之一就是当你被称为carachter时你的结束。这意味着如果你的循环消耗的缓冲区比写入的速度快(记住:9600波特表示960Byte / s,arduino即使很慢但可以计算16.000.000次操作......)。
另一个大问题可能是缺少ram,os你的输出被截断了。有一些函数来检查ram的实时使用情况,请参阅http://playground.arduino.cc/Code/AvailableMemory,停止使用String甚至char数组是一种更好的方法;代码并不难写!
所以电脑会发送" G1 X10.00 Y-100.00 \ n" 但是在时间X你的aruino得到" G1 X10.00",如果你现在读得非常快(比1/960秒快,arduino比这快!)
理想情况下,你应该改变你所有的条件,删除序列可用,而是把你在if中使用的条件放在休息时间;来自
的第一次while (Serial.available()>0)
成了
while ( (k=Serial.read()) != ' ' && k != '\n') //yes it is a bit weird like this
可能会好一点,检查k是否有效,并且超时
unsigned long timeout_ms = 1000; //timeout after 1 seconds from NOW!
unsigned long start_ms = millis();
int k=Serial.read();
while ( k != ' ' && millis()-start_ms < timeout_ms){// because here we expect "Gx ", why are you was also using k != '\n'? removed, feel free to add it back
if (k == -1){
k=Serial.read(); //read the next char
continue; //return to the beginning of the while
}
[... do thigs...]
k=Serial.read(); //read the next char
//here you may add "start_ms = millis();" if you want to reset the timeout
}