Uploaded by aahilirfan2011

code

advertisement
// Pins for IR sensors
#define IR1 A8
#define IR2 A9
#define IR3 A10
#define IR4 A11
#define IR5 A12
// Pins for motor control
#define enA 5
#define in1 6
#define in2 7
#define enB 9
#define in3 10
#define in4 11
// Motor speed
int motorSpeed = 150;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set sensor pins as inputs
pinMode(IR1, INPUT);
pinMode(IR2, INPUT);
pinMode(IR3, INPUT);
pinMode(IR4, INPUT);
pinMode(IR5, INPUT);
}
// Set motor control pins as outputs
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
void loop() {
// Read sensor values
int sensor1 = analogRead(IR1);
int sensor2 = analogRead(IR2);
int sensor3 = analogRead(IR3);
int sensor4 = analogRead(IR4);
int sensor5 = analogRead(IR5);
// Debug output
Serial.print("Sensor Values: ");
Serial.print(sensor1);
Serial.print(" ");
Serial.print(sensor2);
Serial.print(" ");
Serial.print(sensor3);
Serial.print(" ");
Serial.print(sensor4);
Serial.print(" ");
Serial.println(sensor5);
// Line-following logic
if (sensor3 > 800) {
// Move forward
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
}
else if (sensor1 > 800 && sensor5 < 800) {
// Turn slightly right
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
}
else if (sensor5 > 800 && sensor1 < 800) {
// Turn slightly left
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
}
else if (sensor2 > 800) {
// Turn right
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, HIGH);
}
else if (sensor4 > 800) {
// Turn left
digitalWrite(in1, HIGH);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
}
else {
// Stop
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
}
// Set motor speed
analogWrite(enA, motorSpeed);
analogWrite(enB, motorSpeed);
}
```
In this code, the IR sensor inputs are read and the line-following logic is
implemented based on the sensor values. Depending on the sensor readings,
appropriate motor control signals are generated to make the robot follow the
line. The sensor values are also printed to the serial monitor for debugging
purposes.
Make sure to connect the IR sensor outputs to the specified Arduino analog
input pins (A0 to A4) and the motor control signals to the respective digital
output pins (6, 7, 9, 10, 11). Additionally, connect the enable pins (enA and enB)
to the PWM-enabled pins on the Arduino, as these will control the speed of the
motors. Adjust the `motorSpeed` variable to set the desired motor speed.
Download