Ultra Sonic Sensor
Ultra Sonic Sensor Code
int trigPin = 12; /* Trig pin of the sensor is connected to the 6th pin of Arduino */
int echoPin = 11; /* The echo pin of the sensor is connected to the 7th Pin of the Arduino */
long Duration; //Duration
long Distance; //Distance
int leftMotor_1=3; //motor 1 the first data entry is HIGH OR LOW
int leftMotor_2=2; //motor 1 the second data entry is HIGH OR LOW
int rightMotor_1=4; //motor 2 the first data entry is HIGH OR LOW
int rightMotor_2=5; //motor 2 the second data entry is HIGH OR LOW
int leftMotor_pwm=6; // motor 1 Speed control is done with pwm input for
// 0-255 analog PWM signal is sent in range
int rightMotor_pwm=9; // motor 2 Speed control is done with pwm input for
// 0-255 analog PWM signal is sent in range
void setup()
{
for(int i=2;i<=9;i++){
pinMode(i, OUTPUT);} //2-9 No ports are set as outputs
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
Serial.begin(9600); // local communication starting
}
void loop()
{
ObstacleDetection();
if(Distance<40){
Stop();
delay(10);
leftTurn();
delay(2000);}
else Forward();
Serial.print("Distance");
Serial.println(Distance);
}
//ObstacleDetection
long ObstacleDetection(){
digitalWrite(trigPin, LOW); /* sensor disabled */
delayMicroseconds(5);
digitalWrite(trigPin, HIGH); /* Commanded to generate the sensore sound wavei */
delayMicroseconds(10);
digitalWrite(trigPin, LOW); /* Trig pin moved to LOW position to avoid generating new wavesi */
Duration = pulseIn(echoPin, HIGH); /* The time it takes for the sound wave to return is measured */
Distance= Duration /29.1/2; /* measured time converts to distance */
if(Distance > 200)
Distance = 200;
return Distance;
}
//car going forward
void Forward(){
digitalWrite(leftMotor_1,HIGH);
digitalWrite(leftMotor_2,LOW);
analogWrite(leftMotor_pwm,150);
digitalWrite(rightMotor_1,HIGH);
digitalWrite(rightMotor_2,LOW);
analogWrite(rightMotor_pwm,150);
}
//back going back or reverce
void Back(){
digitalWrite(leftMotor_1,LOW);
digitalWrite(leftMotor_2,HIGH);
analogWrite(leftMotor_pwm,150);
digitalWrite(rightMotor_1,LOW);
digitalWrite(rightMotor_2,HIGH);
analogWrite(rightMotor_pwm,150);
}
//right turn of car
void Right(){
digitalWrite(leftMotor_1,HIGH);
digitalWrite(leftMotor_2,LOW);
analogWrite(leftMotor_pwm,150);
digitalWrite(rightMotor_1,HIGH);
digitalWrite(rightMotor_2,LOW);
analogWrite(rightMotor_pwm,0);
}
//left turn of car
void leftTurn(){
digitalWrite(leftMotor_1,HIGH);
digitalWrite(leftMotor_2,LOW);
analogWrite(leftMotor_pwm,0);
digitalWrite(rightMotor_1,HIGH);
digitalWrite(rightMotor_2,LOW);
analogWrite(rightMotor_pwm,150);
}
//stop Function
void Stop(){
digitalWrite(leftMotor_1,HIGH);
digitalWrite(leftMotor_2,LOW);
analogWrite(leftMotor_pwm,0);
digitalWrite(rightMotor_1,HIGH);
digitalWrite(rightMotor_2,LOW);
analogWrite(rightMotor_pwm,0);
}
Comments
Post a Comment