Skip to content

Instantly share code, notes, and snippets.

@Mackaber
Created November 7, 2025 04:31
Show Gist options
  • Select an option

  • Save Mackaber/142b0a306db05d8b9c21f94fe1adff6e to your computer and use it in GitHub Desktop.

Select an option

Save Mackaber/142b0a306db05d8b9c21f94fe1adff6e to your computer and use it in GitHub Desktop.
// Include the Servo library
#include <Servo.h>
// --- Pin Definitions (as variables) ---
// L298N Motor Driver Pins
const int enA = 7; // Enable A (Left Motor Speed)
const int leftMotorIn1 = 6; // IN1 (Left Motor)
const int leftMotorIn2 = 5; // IN2 (Left Motor)
const int rightMotorIn1 = 4; // IN3 (Right Motor)
const int rightMotorIn2 = 3; // IN4 (Right Motor)
const int enB = 2; // Enable B (Right Motor Speed)
// Ultrasonic Sensor Pins
const int trigPin = 9;
const int echoPin = 8;
// Servo Motor Pin
const int servoPin = 10;
// --- STUDENT CALIBRATION VARIABLES ---
int motorSpeed = 180; // General speed for forward/turning (0-255)
int stopDistance = 20; // How close to get to a wall before stopping (cm).
int turnDelay = 450; // How long to run motors for a 90-degree turn (ms)
int servoWaitDelay = 400; // How long to wait for servo to move (ms)
int servoLeftAngle = 130;
int servoCenterAngle = 90;
int servoRightAngle = 50;
// Create our servo object
Servo headServo;
void setup() {
Serial.begin(9600);
// Set all motor pins as OUTPUTs
pinMode(enA, OUTPUT);
pinMode(leftMotorIn1, OUTPUT);
pinMode(leftMotorIn2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(rightMotorIn1, OUTPUT);
pinMode(rightMotorIn2, OUTPUT);
// Set sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Attach the servo
headServo.attach(servoPin);
headServo.write(servoCenterAngle); // Start facing center
Serial.println("Procedural Reactive Avoider - Ready.");
Serial.println("Ensure calibration variables are set!");
delay(1000);
}
void loop() {
getDistance();
// IF: The path in front is clear
if (frontDistance > stopDistance) {
moveForward();
}
else {
stop();
getDistance();
// 2c. Make the decision
if (leftDistance > rightDistance) {
turnLeft();
} else {
turnRight();
}
stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment