IntroRoboticsLab2/roomba/main/main.ino

53 lines
1.3 KiB
C++

#include "Arduino.h"
#include "Wire.h"
#include "MeMCore.h"
// Declare 1 variable of type MeUltrasonicSensor at PORT_3
MeUltrasonicSensor sensor(PORT_3);
int speed = 100;
MeDCMotor _leftMotor(9);
MeDCMotor _rightMotor(10);
bool goagain = false;
// Define the number of iterations required to turn for 30 degrees
// This value may need to be adjusted based on the specific motor and robot configuration
#define TURN_ITERATIONS 50
void setup() {
// Initialize the serial port at 9600 baud
Serial.begin(9600);
// put your setup code here, to run once:
_leftMotor.run(0);
_rightMotor.run(0);
}
void loop() {
float distance = sensor.distanceCm();
// Use parentheses to enclose the condition
if (distance <= 15 or goagain == true) {
goagain = false;
// Add a for loop to turn for 30 degrees
for (int i = 0; i < TURN_ITERATIONS; i++) {
_leftMotor.run(speed);
_rightMotor.run(speed);
delay(10);
}
// Stop the motors after turning
_leftMotor.run(0);
_rightMotor.run(0);
// Check the distance again
distance = sensor.distanceCm();
if (distance < 90) {
goagain = true;
}
} else {
_leftMotor.run(-speed);
_rightMotor.run(speed);
}
// Add a small delay to avoid continuous motor changes
delay(10);
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}