Uploaded by ripankamila2002

CODE

advertisement
#include <Servo.h>
// Define the pins that the sensors are connected to.
const int le SensorPin = 7;
const int rightSensorPin = 8;
// Define the pins that the motors are connected to.
const int PWM1 = 11;
const int PWM2 = 3;
const int le MotorPin1 = 5;
const int le MotorPin2 = 6;
const int rightMotorPin1 = 10;
const int rightMotorPin2 = 9;
// Define the pin for the servo motor.
const int servoPin = 4;
// Create variables to store the sensor readings.
int le SensorReading;
int rightSensorReading;
// Create a servo object.
Servo servoMotor;
// The setup() func on runs once, when the Arduino starts up.
void setup() {
// Set the motor pins as outputs.
pinMode(le MotorPin1, OUTPUT);
pinMode(le MotorPin2, OUTPUT);
pinMode(rightMotorPin1, OUTPUT);
pinMode(rightMotorPin2, OUTPUT);
pinMode(PWM1, OUTPUT);
pinMode(PWM2, OUTPUT);
// Set the servo pin as an output.
pinMode(servoPin, OUTPUT);
// A ach the servo motor to the servo pin.
servoMotor.a ach(servoPin);
// Ini alize the serial port for debugging.
Serial.begin(9600);
}
// The loop() func on runs repeatedly, forever.
void loop() {
// Read the sensor readings.
le SensorReading = digitalRead(le SensorPin);
rightSensorReading = digitalRead(rightSensorPin);
analogWrite(PWM1, 230);
analogWrite(PWM2, 230);
// If both sensors detect a white line simultaneously, rotate the servo.
if (le SensorReading == LOW && rightSensorReading == LOW) {
servoMotor.write(0); // Set servo to 90 degrees
} else {
servoMotor.write(90); // Set servo to 0 degrees
}
// If the le sensor is over the line, turn le .
if (le SensorReading == LOW && rightSensorReading == HIGH) {
rightMotorForward();
le MotorBackward();
}
// If the right sensor is over the line, turn right.
else if (rightSensorReading == LOW && le SensorReading == HIGH) {
rightMotorBackward();
le MotorForward();
}
// If neither sensor is over the line, go straight.
else if (rightSensorReading == HIGH && le SensorReading == HIGH) {
le MotorForward();
rightMotorForward();
}
else
{
rest();
}
// Delay for a short amount of me.
delay(10);
}
void rest()
{
digitalWrite(le MotorPin1, LOW);
digitalWrite(le MotorPin2, LOW);
digitalWrite(rightMotorPin1, LOW);
digitalWrite(rightMotorPin2, LOW);
}
// This func on makes the le motor go forward.
void le MotorForward() {
digitalWrite(le MotorPin1, HIGH);
digitalWrite(le MotorPin2, LOW);
}
// This func on makes the le motor go backward.
void le MotorBackward() {
digitalWrite(le MotorPin1, LOW);
digitalWrite(le MotorPin2, HIGH);
}
// This func on makes the right motor go forward.
void rightMotorForward() {
digitalWrite(rightMotorPin1, HIGH);
digitalWrite(rightMotorPin2, LOW);
}
// This func on makes the right motor go backward.
void rightMotorBackward() {
digitalWrite(rightMotorPin1, LOW);
digitalWrite(rightMotorPin2, HIGH);
}
Download