主要目标是向你展示如何将一些基本运动代码封装到函数中,而不是用于编码器计算和运动操控。
以下样例动作函数将帮助你生成基本动作代码:
- 更有条理
- 更具可读性
- 不易出错
首先,你需要定义以下基本变量:
float Wheel = 10.16; float WB = 36.75; //基于 V5 钳爪机器人配置
注意:如果你更改了齿轮比,以下计算可能会根据齿轮比略有变化。
这将在另一篇专注于电机编码器的文章中讨论:
float EncPerCm = 360/(wheel* M_PI); float EncPerDeg = WB/Wheel;
此样例仅用于枢轴转动。 例如。 right motor = 100, left motor = -100,依此类推。
其次,当你查看以下示例时,我们鼓励你查找有关参数及其规范的在线 API 参考。 访问:https://api.vexcode.cloud /v5/html/并搜索,例如,rotateTo
以让你自己熟悉参数。
样例 1:根据不同的距离来封装走直线运动
float Wheel = 10.16; float WB = 36.75; float EncPerCm = 360.0 / (Wheel* M_PI); void reportMotionValues(motor m, int line){ Brain.Screen.printAt(5,line, "%8.2lf%8.2lf%8.2f", m.position(rev), m.position(deg)); } // 距离是厘米单位 void goStraight( float distance ){ LeftMotor.resetPosition(); LeftMotor.resetRotation(); RightMotor.resetPosition(); RightMotor.resetRotation(); float totalEnc = distance * EncPerCm; // 注意: “deg” 来自于 vex:: namespace. 因此,你不应该 // 创建另一个名为“deg”的变量。 LeftMotor.setVelocity(50.0, percent);
LeftMotor.spinToPosition(totalEnc, deg, false);
RightMotor.setVelocity(50.0, percent);
RightMotor.spinToPosition(totalEnc, deg, false); while (LeftMotor.isSpinning() || RightMotor.isSpinning() ) wait(50, msec); return; } int main() { vexcodeInit(); goStraight(100.0); Brain.Screen.printAt(5,60, "Done"); reportMotionValues(LeftMotor, 30); reportMotionValues(RightMotor, 60); }
样例 2:根据不同角度封装左转动作
float Wheel = 10.16; float WB = 36.75; float EncPerCm = 360.0 / (Wheel* M_PI); float EncPerDeg = WB / Wheel; void turnRight( float degrees){ LeftMotor.resetPosition(); LeftMotor.resetRotation(); RightMotor.resetPosition(); RightMotor.resetRotation(); float totalEnc = degrees * EncPerDeg; // 注意: 这个“deg” 来自于 vex namespace LeftMotor.setVelocity(100.0, percent);
LeftMotor.spinToPosition(totalEnc, deg, false);
RightMotor.setVelocity(-100.0, percent);
RightMotor.spinToPosition(-totalEnc, deg, false); while(LeftMotor.isSpinning() || RightMotor.isSpinning() ) wait(50, msec); return; } int main(){ ... turnRight(90.0); ... }
样例 3:在一个单独函数中封装左和右
void doTurning( float degree ) { // 与上面的 turnRight 完全相同的代码 } int main() { ... doTurning(90.0); // 枢轴右转 ... doTurning(-90.0); // 枢轴左转 }
对于更高级的编程,如果你想让你的代码更具可读性,你可以尝试以下操作:
#define doLeftTurn(d) doTurning(d) #define doRigtTurn(d) doTurning(-d) int main( ) { ... doLeftTurn(90.0); doRightTurning(90.0); ... }
#define
被称为预处理器宏表达式。 将此表达式视为一个符号。 当这个符号在代码中任意地方出现时,它将被doTurning(指定值)
表达式替换。
预处理器宏是一个不同的宽泛的主题,将不会在本文中讨论。