在 arduino 中运行代码时不显示输出结果

No output result displayed when run the code in arduino

本文关键字:显示 输出 结果 代码 arduino 运行      更新时间:2023-10-16

我需要制作一个代码来移动机器人的单个手臂,该手臂包含基于特定给定(x,y)点的三个光束,并且theta0必须从0开始。然后xdyd应根据以下内容计算:

xd = x - L cos(theta)
yd = y - L cos(theta)

其中L是单臂的第一根梁,其中theta0开始,xy进入。 现在,根据计算出的xdyd,它们将用于计算theta1theta2。 这三个角度应发送到伺服电机。

但是,当我进入xy时,什么都没有显示!如果您知道一些可以帮助我解决此问题的有用链接,将不胜感激。

序列号为:

#include <Servo.h>
#include <String.h>
#include <math.h>

Servo motor;
String content = "";
char character;
int yindex;
char End ;
String x,y;
int xt, yt;
float L0=297;
float L1=198;
float L2=165;
float theta0=0;
float theta1, theta2;
float xd,yd;
float xc,yc;


void setup()
{
Serial.begin(9600);
motor.attach(9,660,2600);  
}
void loop() 
{
if (Serial.available ()>0)
{
while(Serial.available()) 
{
character = Serial.read();
content.concat(character);
content += character;
Serial.println (content);
End=content.length();
yindex= content.indexOf("y");
x=content.substring(1,yindex);
y=content.substring(yindex+1, End);
Serial.println (x);
Serial.println (y);

xt=x.toInt();
Serial.println(xt);
yt=y.toInt();
Serial.println(yt);

for ( theta0=0; theta0<180; theta0+=0.1)
{
xd= xt-L0*cos(theta0); 
yd= yt-L0*cos(theta0);
theta2 = acos((sq(xd)+sq(yd)- sq(L1)-sq(L2))/(2*L1*L2));
theta1 = asin((L2*sin(theta2))/sqrt(sq(xd)+sq(yd)))+atan(yd/xd);
Serial.println("The value of theta2 is : ");
Serial.println(theta2);

Serial.println("The value of theta1 is : ");
Serial.println(theta1);

xc = L0*cos(theta0) + L1*cos(theta1) + L2*cos(theta2);
yc= L0*sin(theta0) + L1*sin(theta1) + L2*sin(theta2);

Serial.println("The value of the calculated x is : ");
Serial.println(xc);
Serial.println("The value of the calculated y is : ");
Serial.println(yc);
Serial.println("The value of  theta0:");
Serial.println(theta0);
theta0=theta0*(180/3.14);
theta1=theta1*(180/3.14);
theta2=theta2*(180/3.14);
if (theta1<=-180 && theta1>=0 && theta2>=0 && theta2 <=-180)
{
break;
} 
}

}
}
content="";
}

这里有很多问题。您应该通过一次测试解决方案的每个步骤来解决此类问题,这样您就不会最终陷入混乱。首先,您需要确保正确读取字符串。

这部分代码无法正常工作,因为围绕while(Serial.available())循环的{}不在正确的位置。此外,您将同时使用+=concat附加新角色两次。下面是正确获取字符串的简单修复方法。延迟是为了让下一个字节可用,这样它就不会过早退出循环。

content="";
while (Serial.available() < 1) {}
while (Serial.available()) 
{
character = Serial.read();
content += character;
delay(10);
}
Serial.print("content = "); Serial.println (content);

接下来,您需要从字符串中解析 x 和 y 的值。这里也有几个问题。我认为您不想对 x 和 y 使用整数,因此您需要一种方法将字符串解释为浮点数。以下是将值解析为浮点数的方法。

End=content.length();
yindex= content.indexOf("y");
x=content.substring(1,yindex);
y=content.substring(yindex+1, End);
Serial.print("x = "); Serial.println (x);
Serial.print("y = "); Serial.println (y);
char xbuf[10] = "";
x.toCharArray(xbuf, 10);
xt = atof(xbuf);
Serial.print("xt = "); Serial.println(xt);
char ybuf[10] = "";
y.toCharArray(ybuf, 10);
yt = atof(ybuf);
Serial.print("yt = "); Serial.println(yt);

这应该足以帮助您继续前进。代码后面的数学中存在一些问题,但在您拥有工作打印语句后,这些问题应该更容易解决。注意 - 此代码期望从串行监视器获得的格式是x0.34y0.678格式,其中0.34x的值,0.678y的值。