HC-SR04 Problems.

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

 

101_0463.jpg

#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);
}

Arduino PWM

The Arduino only supports PWM on pins 3,5,6,7,10,11. You are using pin 12.

That doesn’t make sense?

That doesn’t make sense because the robot seems to be able to move fine and Idk why. Why is the robot moving fine? Thanks!!!

PWM pins

Hi Noah

I had 1 PWM pin connected to pin 9 and the robot would always drive in a arc like the motor was slipping  when i changed it it drove straight

 

peter

Oh!!!

That makes sense because the robot wants to lean towards one direction. Thanks!!!

PWM

You can configure motor speed control to use PWM on 1 pin and a forward/reverse control signal on another pin. To operate in reverse you need to invert the ON/OFF time in software prior. Not doing the math will give odd results. For exactly a half speed forward/reverse would be similar.