const int motor2Pin = 8; //back motor
const int motor3Pin = 11; //front motor
const int motor4Pin = 10; //front motor
const int enablePin = 7;
const int photocellPin = A0;
int photocellReading;
const int ledPin1 = 5;
const int ledPin2 = 3;
int LEDbrightness;
#define echoPin 13 // Echo Pin
#define trigPin 12 // Trigger Pin
long duration, distance; // Duration used to calculate distance
int minRange = 30; // min range before reverse
void setup() {
Serial.begin(9600);
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(motor3Pin, OUTPUT);
pinMode(motor4Pin, OUTPUT);
pinMode(enablePin, OUTPUT);
pinMode(photocellPin, INPUT);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
photocellReading = analogRead(photocellPin);
LEDbrightness = constrain(map(photocellReading, 500, 300, 0, 255), 0, 255);
analogWrite(ledPin1, LEDbrightness);
analogWrite(ledPin2, LEDbrightness);
// set enablePin high so that motor can turn on:
digitalWrite(enablePin, HIGH);
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
Serial.println(distance);
if (distance >= minRange){
fwd();
straight();
}
else {
bkwd();
right();
delay(2000);
}
delay(10);
}
void fwd() {
digitalWrite(motor1Pin, LOW);
digitalWrite(motor2Pin, HIGH);
}
void bkwd() {
digitalWrite(motor1Pin, HIGH);
digitalWrite(motor2Pin, LOW);
}
void left() {
digitalWrite(motor3Pin, LOW);
digitalWrite(motor4Pin, HIGH);
}
void right() {
digitalWrite(motor3Pin, HIGH);
digitalWrite(motor4Pin, LOW);
}
void straight() {
digitalWrite(motor3Pin, LOW);
digitalWrite(motor4Pin, LOW);
}