1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
int pinI1=8;//define I1 interface
int pinI2=11;//define I2 interface
int speedpinA=9;//enable motor A
int pinI3=12;//define I3 interface
int pinI4=13;//define I4 interface
int speedpinB=10;//enable motor B
int speed =1000;//define the spead of motor
const int pingPin=7;//defines pin number of sensor's output. let it be noted that const means constant
void setup()
{
Serial.begin(9600); //initializes serial communication
pinMode(pinI1,OUTPUT);
pinMode(pinI2,OUTPUT);
pinMode(speedpinA,OUTPUT);
pinMode(pinI3,OUTPUT);
pinMode(pinI4,OUTPUT);
pinMode(speedpinB,OUTPUT);
}
void forward()
{
analogWrite(speedpinA,speed);//input a simulation value to set the speed
analogWrite(speedpinB,speed);
digitalWrite(pinI4,HIGH);//turn DC Motor B move clockwise
digitalWrite(pinI3,LOW);
digitalWrite(pinI2,HIGH);//anticlockwise
digitalWrite(pinI1,LOW);
}
void backward()//
{
analogWrite(speedpinA,speed);//input a simulation value to set the speed
analogWrite(speedpinB,speed);
digitalWrite(pinI4,LOW);//turn DC Motor B move anticlockwise
digitalWrite(pinI3,HIGH);
digitalWrite(pinI2,LOW);//turn DC Motor A move clockwise
digitalWrite(pinI1,HIGH);
}
void left()//
{
analogWrite(speedpinA,speed);//input a simulation value to set the speed
analogWrite(speedpinB,speed/2);
digitalWrite(pinI4,HIGH);//turn DC Motor B move clockwise
digitalWrite(pinI3,LOW);
digitalWrite(pinI2,HIGH);//turn DC Motor A move clockwise
digitalWrite(pinI1,LOW);
}
void stop()//
{
digitalWrite(speedpinA,LOW);// Unenble the pin, to stop the motor. this should be done to avid damaging the motor.
digitalWrite(speedpinB,LOW);
delay(1000);
}
void Sensor_loop()//this funtion is going to need to be played with
{
long microseconds, inches;//establishes variables: duration(microseconds) and distance(inches)
//the next little bit is to initiate Pulse(HIGH) for 2 or more microseconds. Sends LOW pulse beforehand to ensure a clean HIGH pulse
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
microseconds=pulseIn(pingPin, HIGH);
//code to convert time to distance
inches= long (microseconds/74/2);
//code to print distance values
Serial.print(inches);
Serial.print("in, ");
delay(100);
}
void loop()//Main program
{
Sensor_loop();
{
long (inches);
if (inches>6)
{
forward();
delay(2000);
}
else if (inches<=6)
{
stop();
backward();
delay(2000);
stop();
left();
delay(2000);
stop();
}
}
}
|