//values for positions of servo horn from left to right - 13,90,178
#include <Servo.h> //include the servo library
//define the enable lines
#define enable1 3
#define enable2 6
//define the inputs
#define input1 11
#define input2 12
#define input3 8
#define input4 7
//Create an object for servo
Servo sweepServo;
//set up variable for speed control,delay time, and reading value
int spControl = 200;
int del = 1000;
int servoAngle = 0;
//set up boolean of blackline
bool black = true;
bool check = false;
void setup() {
//set up motor control pins
pinMode(input1, OUTPUT);
pinMode(input2, OUTPUT);
pinMode(input3, OUTPUT);
pinMode(input4, OUTPUT);
//set up servo
sweepServo.attach(5);
//set up starting position of servo horn
sweepServo.write(110);
//used for printing values of photoresistor
Serial.begin(9600);
}
//function for moving forward
void forward() {
//set speed for the motor
analogWrite(enable1, spControl);
analogWrite(enable2, spControl);
//set directions of the motor
digitalWrite(input1, LOW);
digitalWrite(input2, HIGH);
digitalWrite(input3, HIGH);
digitalWrite(input4, LOW);
}
//function for turning to the right
void turnRight() {
//set speed for the motor
analogWrite(enable1, 255);
analogWrite(enable2, 255);
//set directions of the motor
digitalWrite(input1, HIGH);
digitalWrite(input2, LOW);
digitalWrite(input3, HIGH);
digitalWrite(input4, LOW);
}
//function for stopping
void motorStop() {
analogWrite(enable1, 0);
analogWrite(enable2, 0);
digitalWrite(input1, LOW);
digitalWrite(input2, LOW);
digitalWrite(input3, LOW);
digitalWrite(input4, LOW);
}
//function for turning left
void turnLeft() {
//set speed for the motor
analogWrite(enable1, 255);
analogWrite(enable2, 255);
//set directions of the motor
digitalWrite(input1, LOW);
digitalWrite(input2, HIGH);
digitalWrite(input3, LOW);
digitalWrite(input4, HIGH);
}
//function for checking the status of the sensor
boolean isBlack() {
if (analogRead(A0) >= 100) {
black = true;
} else {
black = false;
}
return black;
}
void loop() {
check = isBlack();
delay(500);
motorStop();
//sweep the servo to find the black line
for(int x = 180; x >=13; x--){
sweepServo.write(x);
delay(100);
check = isBlack();
delay(50);
if(check == true){
servoAngle = x;
x = 12;
}
}sweepServo.write(110);
delay(100);
check = isBlack();
delay(500);
if(check == true){
while(check == true){
forward();
delay(100);
motorStop();
delay(100);
check = isBlack();
delay(50);
}
}else{
if(servoAngle > 110){
while(check == false){
turnRight();
delay(100);
motorStop();
delay(100);
check = isBlack();
delay(50);
}
}else if (servoAngle < 110){
while(check == false){
turnLeft();
delay(100);
motorStop();
delay(100);
check = isBlack();
delay(50);
}
}
}
/*//This code below is used to record the measurements of the light sensor for the environment
Serial.println(analogRead(A0));
delay(1000);*/
}
Comments
Please log in or sign up to comment.