Project Code
Project Code
h>
#include <intrins.h>
// Define pin assignments for various components
sbit servo_pin = P2^0;
sbit trig = P3^0;
sbit echo = P3^1;
sbit m1p1 = P1^0;
sbit m1p2 = P1^1;
sbit m2p1 = P1^2;
sbit m2p2 = P1^3;
// Global variables to store distances and readings
int distance;
int distanceright = 0;
int distanceleft = 0;
// Function prototypes
int get_distance();
void Delay_servo(unsigned int);
void Delay_servo1(unsigned int);
void delay(unsigned int);
void forward();
void stop();
void backward();
void left();
void right();
void servo_return();
int scanright();
int scanleft();
// Function to generate microsecond delay
void delay(unsigned int time)
{
unsigned int i, j;
for (i = 0; i < time; i++)
{
for (j = 0; j < 1275; j++);
}
}
// Function to generate millisecond delay
void Delay_servo(unsigned int ms)
{
unsigned long int us = ms * 1000;
while (us--)
{
_nop_();
}
}
// Function to generate microsecond delay
void Delay_servo1(unsigned int us)
{
while (us--)
{
_nop_();
}}
// Function to move the robot forward
void forward()
{
m1p1 = 1;
m1p2 = 0;
m2p1 = 1;
m2p2 = 0;
}
// Function to stop the robot
void stop()
{
m1p1 = 0;
m1p2 = 0;
m2p1 = 0;
m2p2 = 0;
}
// Function to move the robot backward
void backward()
{
m1p1 = 0;
m1p2 = 1;
m2p1 = 0;
m2p2 = 1;
}
// Function to make the robot turn left
void left()
{
m1p1 = 0;
m1p2 = 1;
m2p1 = 1;
m2p2 = 0;
}
// Function to make the robot turn right
void right()
{
m1p1 = 1;
m1p2 = 0;
m2p1 = 0;
m2p2 = 1;
}
// Function to return the servo to its initial position
void servo_return()
{
servo_pin = 1;
Delay_servo1(115);
servo_pin = 0;
Delay_servo(2);
}
// Function to scan to the right and get the distance
int scanright()
{
servo_pin = 1;
Delay_servo1(50);
servo_pin = 0;
distance = get_distance();
Delay_servo(20);
Delay_servo1(115);
return distance;
}
// Function to scan to the left and get the distance
int scanleft()
{
servo_pin = 1;
Delay_servo1(170);
servo_pin = 0;
Delay_servo(20);
distance = get_distance();
Delay_servo1(115);
return distance;
}
// Function to get the distance from the ultrasonic sensor
int get_distance()
{
int distance;
trig = 1;
delay(2);
trig = 0;
while (!echo);
TH0 = 0x00;
TL0 = 0x00;
TR0 = 1;
while (echo);
TR0 = 0;
distance = (TH0 << 8) + TL0;
distance = distance / 58;
return distance;
}
// Main function
void main() {
while (1)
{
unsigned int distance;
TMOD = 0x01;
TH0 = 0;
TL0 = 0;
distance = get_distance();
// Check if an object is too close
if (distance <= 20){
stop();
delay(50);
backward();
delay(5);
stop();
delay(5);
distanceright = scanright();
delay(2);
distanceleft = scanleft();
delay(5);
// Determine whether to turn right or left based on distances
if (distance >= distanceleft)
{
right();
stop();
}
else
{
left();
stop();
}
}
else{
forward();
servo_return();
}}