Frage

I am programming a robot with C# and using a digitial compass for direction. Problem I am having is when it goes into its turn loop, it doesnt come back out of it. The DragonBoard is my controller I am talking too. How this is supposed to work is given set heading and time, it turns left or right till heading is matched then drives forward for a set amount of time. Problem I am having is it will go forward but when it goes into the turn loop, it stays there, and doesnt return to for loop. Any help would be appreciated.

private void drive(int heading, int time)//going to start from kit
{
    int i;

    for (i = 0; i < time;i++ )
    {
        DragonBoard.Write("w");//go forward

        while (int.Parse(bearingTxt.Text) - 1 > heading)
        {
            DragonBoard.Write("a");//turn left
            break;
        }

        while (int.Parse(bearingTxt.Text) +1 < heading)
        {
            DragonBoard.Write("d");//turn right
            break;
        }
    }

    DragonBoard.Write(" ");

    if (listBox1.SelectedIndex < listBox1.Items.Count - 1)
    {
        listBox1.SelectedIndex = listBox1.SelectedIndex + 1;
        decision();
    }
War es hilfreich?

Lösung

It is because your break Exits the "While Loop" not the for loop...and im guessing your while loop only executes once? Why do you need while for that? Try this

 for (i = 0; i < time;i++ )
{
    DragonBoard.Write("w");//go forward

    if (int.Parse(bearingTxt.Text) - 1 > heading)
    {
        DragonBoard.Write("a");//turn left
        break;
    }

    else (int.Parse(bearingTxt.Text) +1 < heading)
    {
        DragonBoard.Write("d");//turn right
        break;
    }
}

Andere Tipps

I hope while loop is not needed there; And the break is also not needed incase of if conditions; Modify your code as the below, which should work:

for (i = 0; i < time;i++ )
    {
        DragonBoard.Write("w");//go forward

        if(int.Parse(bearingTxt.Text) - 1 > heading)
            DragonBoard.Write("a");//turn left
        else if(int.Parse(bearingTxt.Text) +1 < heading)
            DragonBoard.Write("d");//turn right
     }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top