Arduino Robotics Assignment 6

The robot needs to go forward and backward depends on the two photoresistors: when one sensor senses more light, it goes forward, otherwise, it goes backward.

The schematics

The code:

const int in1 = 13;//motor1
const int in2 = 12;//moto1
const int in3 = 9;//motor2
const int in4 = 8;//motor2
const int enable = 11; //the output of motor1's speed
const int enable2=10;//the output of motor2's speed
int motorSpeed = 200;//the motor’s speed
int sensor1Mark =500;//a number between cover and uncover the sensor1
int sensor2Mark = 780;//a number between cover and uncover the sensor2
void setup() {
Serial.begin(9600);
pinMode(A2,OUTPUT);//the power(5V) for photoresistors
digitalWrite(A2,HIGH);//the power for photoresistors
pinMode(in1, OUTPUT);//motor1
pinMode(in2, OUTPUT); //motor1
pinMode(in3,OUTPUT);//motor2
pinMode(in4, OUTPUT);//motor2
pinMode(enable, OUTPUT);//to set the motor speed to motor1
analogWrite(enable, motorSpeed);
pinMode(enable2,OUTPUT);//to set the motor speed to motor2
analogWrite(enable2, motorSpeed);
}
void loop() {
int sensorValue1 = analogRead(A0); //to print out the sensor1's value in serial monitor
Serial.print(“Sensor 1 : “ );
Serial.print(sensorValue1);
delay(2);
int sensorValue2 = analogRead(A1);//to print out the sensor2's value in serial monitor
Serial.print(“\tSensor 2 : “);
Serial.println( sensorValue2);
delay(2);
if (sensorValue1<sensor1Mark && sensorValue2>sensor2Mark){ //to go backward
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3,HIGH);
digitalWrite(in4,LOW);
}
else if(sensorValue1>=sensor1Mark && sensorValue2<sensor2Mark) {//to go forward
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3,LOW);
digitalWrite(in4,HIGH);
}
else{//to stop
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3,LOW);
digitalWrite(in4,LOW);
}
}
Like what you read? Give Ying Liang a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.