在 VEXcode Pro V5 中封裝基本機器人動作

The VEX Visual Studio Code Extension has replaced VEXcode Pro V5, which is now end-of-life.

VEXcode Blocks and VEXcode Text remain actively developed and supported for all VEX platforms.

主要目標是向您展示如何將一些基本運動代碼封裝到函數中,而不是用於編碼器計算和運動操作。

以下範例運動函數將幫助您編寫基本運動程式碼:

  • 更有條理
  • 更具可讀性
  • 不易出錯

首先,您需要定義以下基本變數:

浮輪=10.16;
浮動WB = 36.75; //基於V5 Clawbot配置

注意:如果變更齒輪比,則下列計算可能會根據齒輪比略有變化。

這將在另一篇關注電機編碼器的文章中討論:

浮動EncPerCm = 360/(輪* M_PI);
float EncPerDeg = WB/車輪;

此範例僅適用於旋轉。 例如 右馬達 = 100,左馬達 = -100,依此類推。

其次,當您查看以下範例時,建議您查找線上 API 參考以取得參數及其規格。 訪問:https://api.vexcode.cloud/v5/html/並蒐索,例如以熟悉參數。


範例1:封裝基於不同距離的直線運動

浮輪=10.16; 
浮動WB = 36.75; 
浮點數 EncPerCm = 360.0 / (車輪* 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();
	左電機.resetRotation();
	右邊馬達.resetPosition();
	RightMotor.resetRotation();
  	
	float TotalEnc = 距離 * EncPerCm;
	
	// 注意:「deg」來自 vex:: 命名空間。 因此,您不應該 
        // 建立另一個也命名為「deg」的變數。 

       LeftMotor.setVelocity(50.0, 百分比);
LeftMotor.spinToPosition(totalEnc, deg, false);

RightMotor.setVelocity(50.0, 百分比);
RightMotor.spinToPosition(totalEnc, deg, false); while (LeftMotor.isSpinning() || RightMotor.isSpinning() ) wait(50, 毫秒); 返回; } int main() { vexcodeInit(); 直行(100.0); Brain.Screen.printAt(5,60, "完成"); 報告運動值(左電機,30); 報告運動值(RightMotor, 60); }

範例2:根據不同度數封裝左轉

浮輪=10.16; 
浮動WB = 36.75; 
浮點數 EncPerCm = 360.0 / (車輪* M_PI); 
float EncPerDeg = WB / 輪;

void TurnRight( float Degrees){
	
	LeftMotor.resetPosition();
	LeftMotor.resetRotation();
	RightMotor.resetPosition();
	RightMotor.resetRotation();
  	
	float TotalEnc = 度 * EncPerDeg;
	
       // 注意:這個「deg」來自vex命名空間
       LeftMotor.setVelocity(100.0,%);
LeftMotor.spinToPosition(totalEnc, deg, false);

RightMotor.setVelocity(-100.0, 百分比);
RightMotor.spinToPosition(-totalEnc, deg, false); while(LeftMotor.isSpinning() || RightMotor.isSpinning() ) wait(50, 毫秒); 返回; } int main(){ ... 右轉(90.0); ... }

範例 3:將 Left 和 Right 封裝在一個函數中

void doTurning( float Degrees ) {
	// 與上面的turnRight 完全相同的程式碼
}

int main() {
...
   doTurning(90.0); // 右樞軸轉動
...
   doTurning(-90.0); // 左樞轉
}

對於更高級的編程,如果您想讓程式碼更具可讀性,您可以嘗試以下操作:

#define doLeftTurn(d) doTurning(d)
#define doRigtTurn(d) doTurning(-d)

int main() {
...
   左轉(90.0);  
   doRightTurning(90.0);
...
}

#define稱為預處理器巨集表達式。 將此表達式視為一個符號。 無論此符號出現在程式碼中的何處,它都將被表達式doTurning(指定的值)取代

預處理器巨集是一個不同的廣泛主題,本文不會討論。

For more information, help, and tips, check out the many resources at VEX Professional Development Plus

Last Updated: