// STATE 4: RETURN TO START int returntostart(){ digitalWrite(LEDPIN, true);…
- User
// STATE 4: RETURN TO START int return_to_start(){ digitalWrite(LED_PIN, true); kinematics.update(); // need to keep updating position each loop!
code// calculate theta home -> angle to return to start in a straight line. if(kinematics.Theta_Home == 0){ kinematics.Theta_Home = 3.14159 + atan(kinematics.Y_pos/kinematics.X_pos); Serial.println(kinematics.Theta_Home); if(kinematics.Theta_Home > 3.14){ // Conditions to keep theta home -180 < theta_home < 180 kinematics.Theta_Home = kinematics.Theta_Home - (2*3.14159); } if(kinematics.Theta_Home < -3.14){ kinematics.Theta_Home = kinematics.Theta_Home + (2*3.14159); } } // if theta does not equal theta home (within some error), slowly rotate. if (kinematics.Theta > kinematics.Theta_Home + 0.20){ // rotate until theta within about degrees of theta home (0.2 rads) - 12 degree leighway combats the overshoot. motors.setMotorPower(21,-21); // slowly rotate in -ve direction return(4); // keep spinnin' } if (kinematics.Theta < kinematics.Theta_Home - 0.20){ // rotate until theta within about degrees of theta home (0.2 rads) - 12 degree leighway combats the overshoot. motors.setMotorPower(-21,22); // slowly rotate in +ve direction return(4); // keep spinnin' } else{ // Robot lined up, now head home speed_pid_left.reset(); speed_pid_right.reset(); unsigned long time_to_home = millis() + 15000; // takes about 15 seconds to get home unsigned long current_time = millis(); while(current_time < time_to_home){ current_time = millis(); // update current time update_state(4); // need to keep updating average speeds! kinematics.update(); // need to keep updating position each loop! motors.setMotorPower(pwm_left,pwm_right); // go in a straight line. } Serial.println("HOME!"); // Once you're home, stop. motors.setMotorPower(0, 0); return(5); // our home state } }这是什么意思 - Assistant
这段代码是一个函数,函数名为return_to_start()。该函数的作用是将机器人返回到起始位置。
首先,LED_PIN的引脚被设置为高电平,点亮LED灯。
然后,通过调用kinematics.update()函数来更新机器人的位置。
接下来,计算从当前位置直线返回到起始位置所需的角度theta_home。计算公式为:theta_home = 3.14159 + atan(Y_pos/X_pos),其中X_pos和Y_pos分别表示机器人当前的x和y坐标。
如果theta_home大于3.14,则将其减去23.14159;如果theta_home小于-3.14,则将其加上23.14159,以保证theta_home的取值范围在-180到180之间。
然后,通过比较当前角度theta和theta_home,判断是否需要进行慢速旋转。
如果theta大于theta_home+0.20,表示当前角度偏离起始角度较多,则以负方向慢速旋转;如果theta小于theta_home-0.20,表示当前角度偏离起始角度较多,则以正方向慢速旋转。返回值为4,表示继续执行return_to_start()函数。
当theta接近theta_home时,停止旋转,机器人对准起始位置。初始化左右电机的速度PID控制器,并设置机器人返回起始位置所需要的时间为15秒。
在返回过程中,不断更新当前时间,并调用update_state()函数来更新平均速度和状态。
在每次循环中,更新机器人的位置,并调用setMotorPower()函数设置左右电机的功率,以直线行驶。
当当前时间超过设定的返回时间时,表示机器人回到了起始位置。程序通过串口打印"HOME!",然后停止左右电机的运动。
函数的返回值为5,表示机器人进入到了“回到起始位置”状态。
- User
将注释翻译成中文
- Assistant
// STATE 4: RETURN TO START int return_to_start(){ digitalWrite(LED_PIN, true); // 点亮LED灯
code