Date
Author
U
UntitledDocumentation Type
Class
Beyond Possible
Class Section
Careers of the future
Getting Started
Below are 3 new algorithms you can try for your SEARCH code.
- Random: The robot will randomly turn left and right
- Step counter: The robot will count its steps and change direction every N steps
- Sub states: The robot will enter different search states called LOOKING and MOVING
Algorithm 1: Random
// Make a random choice: 0 or 1
long choice = random(2);
if (choice == 0) {
turnLeft();
delay(100);
} else {
turnRight();
delay(100);
}
Algorithm 2: Step counting
First, add a new variable before the loop()
function, at top of your code.
// Create a counter for our search pattern
int searchCounter = 0;
Now replace your SEARCH code with this:
searchCounter++; // Increment the counter each time we are in the SEARCH state
if (searchCounter < 100) {
// Step 1: Go forward for a bit
moveForward();
} else if (searchCounter < 150) {
// Step 2: Turn for a bit
turnLeft();
} else {
// Step 3: Reset the counter to start the pattern over
searchCounter = 0;
}
How it works:
- The
searchCounter
acts like a simple timer. Each time theloop
runs and the robot is in the "SEARCH" state, the counter goes up by one. - For the first 50 cycles, it moves forward.
- For the next 30 cycles (from 50 to 80), it turns left.
- Then it resets and starts the pattern again.
Algorithm 3: States within states
Did you know you can nest states inside of states? So while the robot is in its SEARCH state, it can have different types of searches: LOOKING and MOVING.
First add a new variable to the top of your code before loop()
:
// Create variables for our advanced search pattern
String searchSubState = "LOOKING"; // Can be "LOOKING" or "MOVING"
Now replace your SEARCH code with the following:
if(searchSubState == "LOOKING")
{
// In this sub-state, we turn in a circle
turnLeft();
searchCounter++;
// Turn for a while
if(searchCounter > 50) {
searchSubState = "MOVING"; // Switch to the next sub-state
searchCounter = 0; // Reset counter for the next state
}
}
else if (searchSubState == "MOVING")
{
// In this sub-state, we move forward to a new spot
moveForward();
searchCounter++;
// Move forward for a while
if (searchCounter > 50) {
searchSubState = "LOOKING"; // Go back to looking around
searchCounter = 0; // Reset counter
}
}