Dear: LMR
I am trying to make my robot obstacle avoid and it keeps rotating counterclockwise instead of only doing that if something is in the way. I think the problem is interference in the hcsr04 sensor. Can I have some help? Thanks!!!
From: Noah
#include <NewPing.h>
NewPing sonar(7, 6, 200);
const int ENA = 13;
const int IN1 = 12;
const int IN2 = 11;
const int IN3 = 10;
const int IN4 = 9;
const int ENB = 8;
const int trigPin = 7;
const int echoPin = 6;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedl
if(sonar.ping_cm() > 30)
{
Forward(255);
delay(20);
}
if(sonar.ping_cm() <= 30)
{
CCW(255);
delay(20);
}
}
void Forward(int Speed)
{
digitalWrite(ENA, HIGH);
digitalWrite(ENB, HIGH);
analogWrite(IN2, Speed);
analogWrite(IN4, Speed);
digitalWrite(IN1, LOW);
digitalWrite(IN3, LOW);
}
void Backward(int Speed)
{
digitalWrite(ENA, HIGH);
digitalWrite(ENB, HIGH);
analogWrite(IN2, Speed);
analogWrite(IN4, Speed);
digitalWrite(IN1, LOW);
digitalWrite(IN3, LOW);
}
void CCW(int Speed)
{
digitalWrite(ENA, HIGH);
digitalWrite(ENB, HIGH);
analogWrite(IN1, Speed);
analogWrite(IN4, Speed);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
}
void CW(int Speed)
{
digitalWrite(ENA, HIGH);
digitalWrite(ENB, HIGH);
analogWrite(IN3, Speed);
analogWrite(IN2, Speed);
digitalWrite(IN1, LOW);
digitalWrite(IN4, LOW);
}
void Stop()
{
digitalWrite(ENA, LOW);
digitalWrite(ENB, LOW);
}