Loading...

Human following robot Arduino code


Hello everyone! Welcome to Arduino Geek. Today we will discuss about the Arduino code for human following robot. So let's get started. 

Human following robot Arduino code - 

Here's a sample code for a simple human following robot using an Arduino Uno and an ultrasonic sensor:

Arduino Code - 

// Define pins for ultrasonic sensor
#define trigPin 9
#define echoPin 10

// Define pins for motor driver
#define enA 5
#define in1 6
#define in2 7

// Define distance and speed thresholds
#define maxDist 50
#define minDist 20
#define maxSpeed 255

void setup() {
  // Initialize serial communication
  Serial.begin(9600);
  
  // Set pin modes for ultrasonic sensor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  // Set pin modes for motor driver
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  
  // Set initial motor speed to 0
  analogWrite(enA, 0);
}

void loop() {
  // Read distance from ultrasonic sensor
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration / 58;
  Serial.println(distance);
  
  // Determine direction and speed based on distance
  int speed = 0;
  if (distance > maxDist) {
    // If the person is too far away, stop the robot
    digitalWrite(in1, LOW);
    digitalWrite(in2, LOW);
  } else if (distance < minDist) {
    // If the person is too close, back away
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
    speed = maxSpeed;
  } else {
    // If the person is in range, follow them
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);
    speed = map(distance, minDist, maxDist, maxSpeed/2, maxSpeed);
  }
  analogWrite(enA, speed);
}

Arduino Code Description -

This is just a sample code and may need to be adjusted based on the specific hardware used and the requirements of the project. Additionally, this code assumes that the robot will be following a single person and may need to be modified for situations where there are multiple people or obstacles present.
 
close