Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int motorForward = 9; //Motor control pin
- int motorBackward = 10; //Motor control pin
- float duration; //Variable
- float distance; //Variable
- int echoPin = 8; //Echo pin of HC-SR04
- int triggerPin = 7; //Trigger pin of HC-SR04
- float maxDistance=200;
- void setup() {
- pinMode(echoPin,INPUT);
- pinMode(triggerPin,OUTPUT);
- pinMode(motorForward,OUTPUT);
- pinMode(motorBackward,OUTPUT);
- Serial.begin(9600); //Enable serial monitor
- }
- void move_forward() //Function to move motor 'forward'
- {analogWrite(motorForward,maxDistance-255+distance);
- digitalWrite(motorBackward,LOW);
- }
- void move_backward() //Function to move motor 'backward'
- {analogWrite(motorBackward,50+distance);
- digitalWrite(motorForward,LOW);
- }
- void move_stop() //Function to stop the motor
- {digitalWrite(motorForward,LOW);
- digitalWrite(motorBackward,LOW);
- }
- void loop() {
- digitalWrite(triggerPin,LOW); //Ensure the sensor is not ON at start of loop
- delayMicroseconds(2);
- digitalWrite(triggerPin,HIGH); //Trigger the sensor to send a high frequency pulse
- delayMicroseconds(10);
- digitalWrite(triggerPin,LOW);
- duration = pulseIn(echoPin,HIGH); //Calculate time taken to receive the reflected signal
- distance = (duration/2)*0.0344; //Compute distance of object (in cm) from the sensor face
- if (distance >= maxDistance || distance <= 2){ //Display the distance, change the condition for your range
- Serial.print("Distance = ");
- Serial.println("Out of range");
- }
- else {
- Serial.print("Distance = ");
- Serial.print(distance);
- Serial.println(" cm");
- }
- if(distance<=20) //If object is at a distance less than 20 cm, move 'forward'
- {move_backward();
- }
- if(distance>=30) //If object is at a distance greater than 30 cm, move 'backward'
- {move_forward();
- }
- if(distance>20 and distance<30) //If object is between 20 and 30 cm from the sensor, stop the motor
- {move_stop();
- }
- delay(500); //Run every half second
- }
Add Comment
Please, Sign In to add comment