Hello everyone Started with arduino ,and the forum has been helpful.
I read a few posts on Obstacle avoidance using HCSR04 and it’s done (image attached)!
Works fine with basic obstacle avoidance but i have a few doubts :-
-
Battery dies out fast (used two 9V batteries,also code attached). Is there any low power mode(like msp430) which i can utilise ?
-
Any algorithm which is a bit more efficient ? or any suggestions with improvements for the code is highly appreciated.
Thank you
#include <NewPing.h>
#define TRIGGER_PIN 3 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 5 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
const int Motor2Pin1 = 6;
const int Motor2Pin2 = 9;
const int Motor1Pin1 = 10;
const int Motor1Pin2 = 11;
int a;
int b;
void setup()
{
pinMode(Motor1Pin1, OUTPUT);
pinMode(Motor1Pin2, OUTPUT);
pinMode(Motor2Pin1, OUTPUT);
pinMode(Motor2Pin2, OUTPUT);
Serial.begin(9600);
}
void loop()
{
a=sensor(b);
motor(a);
delay(100);
}
int sensor(int b)
{
unsigned int uS = sonar.ping();
b = (uS / US_ROUNDTRIP_CM);
return b;
}
int motor(int a)
{
int val=a;
if(val==0 || val>20)
GoForward();
else if(val<19&&val>14)
{
GoRight();
}
else if(val <14&&val>5)
{
GoLeft();
}
else if (val>0&&val<5)
{
GoBackward();
}
}
void GoForward()
{
digitalWrite(Motor1Pin2, HIGH);
digitalWrite(Motor1Pin1, LOW);
digitalWrite(Motor2Pin2, LOW);
digitalWrite(Motor2Pin1, HIGH);
delay(100);
}
void GoBackward(){
digitalWrite(Motor1Pin2, LOW);
digitalWrite(Motor1Pin1, HIGH);
digitalWrite(Motor2Pin2, HIGH);
digitalWrite(Motor2Pin1, LOW);
delay(100);
}
void GoRight(){
analogWrite(Motor1Pin2, 255);
analogWrite(Motor1Pin1, 0);
analogWrite(Motor2Pin2, 100);
analogWrite(Motor2Pin1, 0);
delay(100);
}
void GoLeft(){
analogWrite(Motor1Pin2, 0);
analogWrite(Motor1Pin1, 100);
analogWrite(Motor2Pin2, 0);
analogWrite(Motor2Pin1, 255);
delay(100);
}
final.zip (812 Bytes)