getting ultrasonic sensor to change its direction from previous

When the ultrasonic sensor detects a wall it turns left and then when it detects another wall this time it turns right. How would you do that? Only one ultrasonic sensor.

Have a variable that you set whenever you make a turn. Look at that variable to see which way you turned last time and do the opposite.

Steve

What would that look like?

Use a variable to store the latest turn direction, then upon performing the turn change it to the other direction. As you have only two options, a boolean works just fine.

bool direction;

void loop() {
  if (haveObstacle) {
    if (direction == true) {
      turnRight();
      direction = false;
    }
    else {
      turnLeft();
      direction = true;
    }
  }
}

Not quite getting this. I understand the last part but how, and what do you you store in a variable?

Variables store a value. In this case the value true or false (basically 1 or 0).