void loop()
{
// These static variables will be initialized once, then remain valid
// through each iteration of the loop.
// Two loop timers; we have one loop that happens four times a second
// and one that happens ten times a second.
static unsigned long loopStart = millis();
static unsigned long loopStart2 = millis();
// We're doing a crude low-pass filter on the accelerometer; we want
// two consecutive high values so we don't trigger our surprise on
// transient events, only on a significant change in angle.
static int lastXAccel = xl.x;
// These two variables handle the current position and position
// change of the scanning servo motor.
static int angle = 0;
static int angleDelta = 5;
// Wait for the button to be pressed, then turn off the "bumped" flag
// so the motors can run. Also, clear the encoders, so we can track
// our motion.
if (digitalRead(BUTTON_PIN) == LOW)
{
bumped = false;
encoder.clearEnc(BOTH);
}
// Dump the current distance count on the right wheel to the serial
// port, just for something to do.
swsp.println(encoder.getTicks(RIGHT));
// If we pass 75 ticks on the right wheel, treat that the same as we
// would a bumper hit and stop moving.
if (encoder.getTicks(RIGHT) > 75) bumped = true;
// This is our ten-times-a-second loop. It's watching the accelerometer
// and, when the bot senses an incline, setting off our surprise.
if (loopStart2 + 100 < millis())
{
loopStart2 = millis();
lastXAccel = xl.x;
xl.read();
if (!bumped)
{
if (xl.x > 6000 && lastXAccel > 6000)
{
motors.brake();
horn();
motors.drive(255);
delay(5000);
motors.brake();
bumped = true;
}
}
}
// This is the four-times-a-second loop. It scans a servo from left to
// right and back again.
Page 17 of 19
Need help?
Do you have a question about the RedBot and is the answer not in the manual?