我很高兴使用nXc编码我的NXT 2.0机器人,我需要它来跟随其他机器人并同时检查障碍物。然而,这两项任务有时会相互冲突,当我遇到一个障碍时,它会将其视为一个对象并继续前进而不是停止。
我的项目目标:跟随领导机器人,遇到障碍物时停下来,在障碍物清除后,继续跟随前方的领导机器人。
以下是我的代码:
#define NEAR 50
#define TURNTIME 540
#define MOVETIME 1000
mutex moveMutex;
//check for robot in front of it
task check_robot(void)
{
while(true)
{
if (SensorUS(IN_2)<=NEAR)
{
Acquire(moveMutex);
OnFwd(OUT_BC,50); //if it is within range of 50cm, move
Release(moveMutex);
}
if (SensorUS(IN_2)>NEAR)
{
Acquire(moveMutex); //this section allows the robot to turn
OnFwd(OUT_C,50); //left and right to look for the
Wait(TURNTIME); //leader
OnRev(OUT_B,50);
Wait(TURNTIME);
OnRev(OUT_C,50);
Wait(TURNTIME);
OnFwd(OUT_B,50);
Wait(TURNTIME);
if (SensorUS(IN_2)<=NEAR)
{
Acquire(moveMutex);
OnFwd(OUT_BC,50); //if it finds the leader, it moves
Release(moveMutex);
}
else
{
Acquire(moveMutex);
OnFwd(OUT_C,50); //repeats the search process
Wait(TURNTIME);
OnRev(OUT_B,50);
Wait(TURNTIME);
OnRev(OUT_C,50);
Wait(TURNTIME);
OnFwd(OUT_B,50);
Wait(TURNTIME);
Release(moveMutex);
}
}
Release(moveMutex);
}
}
task check_obstacles(void)
{
Acquire(moveMutex);
until(((SENSOR_1)==1)||((SENSOR_3)==1)); //when any one of the
OnRev(OUT_BC,50); //touch sensors are
Wait(1000); //pressed, it is supposed
Off(OUT_BC); //to stop until both
until(((SENSOR_1)==0)&&((SENSOR_3)==0)); //are released, then
OnFwd(OUT_BC,50); //continue moving
Release(moveMutex);
}
task main(void)
{
SetSensorTouch(IN_1);
SetSensorUltrasonic(IN_2);
SetSensorTouch(IN_3);
SetSensorColorFull(IN_4);
while(true)
{
Precedes(check_robot,check_obstacles);
}
}
有关如何改善这一点的任何想法?使用子程序而不是任务会更好吗?使用子程序或任务有什么好处?