Ultrasonic auto car. coding problems

Hello everyone, I am using Ultrasonic sensor HC-SR04. and L298N motor driver. But the code isn't working. Here is the code i want: when the sensor says the cm is less than 10 it rotates and if its more than 10 it goes forward but it's not working. Here is my code:


int ena = D8;
int in1 = D6;
int in2 = D7;
int in3 = D2; 
int in4 = D3;
int enb = D4;
const int trigPin = D0;
const int echoPin = D1;

//define sound velocity in cm/uS
#define SOUND_VELOCITY 0.034
#define CM_TO_INCH 0.393701

long duration;
float distanceCm;
float distanceInch;

void setup() {
  Serial.begin(115200); // Starts the serial communication
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  
  // Calculate the distance
  distanceCm = duration * SOUND_VELOCITY/2;
  
  // Convert to inches
  distanceInch = distanceCm * CM_TO_INCH;
  
  // Prints the distance on the Serial Monitor
  Serial.print("Distance (cm): ");
  Serial.println(distanceCm);
  Serial.print("Distance (inch): ");
  Serial.println(distanceInch);
      delay(500);
  if((10.00 > distanceCm)) {
    digitalWrite(in1,HIGH);
    digitalWrite(in2,LOW);
    digitalWrite(in3,LOW);
    digitalWrite(in4,HIGH);
    Serial.print("rotate");
  }
  
  else {
    digitalWrite(in1,LOW);
    digitalWrite(in2,HIGH);
    digitalWrite(in3,LOW);
    digitalWrite(in4,HIGH);
    Serial.print("forward");
  }
     analogWrite(ena, 250); 
     analogWrite(enb, 250);
    }

So what happens when you run the code ?

What do you see in the Serial monitor ?
Which Arduino board are you using ?
What voltage does it run at ?
Do you know for sure that the motor and your circuit work ?
How is the motor powered ?

I see the cm and inch of the ultrasonic sensor and if its forward or backward but the motor isn't even moving

I am not using arduino am using ESP8266
When I run the code It connects to the ESP8266 board.
The l298n run at 6v
Yes I am sure that the motor and my circuit work.
the motor (dc motor) is powered by l298n motor driver.
I think the problem is from the code.

Your posting style is similar to

my hair is red. When ist my birthday?

Can't say from the small information "my hair is red"

Some questions remain unanswered yet:

all users here don't have a magical glas-sphere to look in to see what causes your problems
you have to post all the details of your project

I answered his question. Yea... Your right I should've said more details at the beginning.

describe what did you do to really see the motor run forward / backward?

Post an image of the project.

Does the motor rotate when the car's wheels are lifted off the surface?

Does the motor rotate out of its mount in the car but not in the mount?

You are using one motor to drive how may wheels?

How is 6V being generated?

Firstly: I have made an esp8266 controlling the motor speed, rotation. I used the same board, The same batteries, I just added the ultrasonic sensor.
Here is an image of what my connections look like when i used to control its speed and direction wirelessly without the ultrasonic sensor.


and also in2 is to d2 it was a mistake

Here is what the base where all the parts are put looks like:


Here is what the robot looks like(representing a car):

Here are the wires that connect the motor(only 2 wires connect the motor (2negative and 2 positive)):

Nope. No move at all The problem is not from the power.
The motors aren't even moving.
L298N motor driver is controlling 2 small geared motors
I am using 4.8V for the motor driver. The problem is not from the power. It works perfect as if I run another code to control it's direction without the ultrasonic sensor.

1 Like

When you tried using the new ping library, NewPing - Arduino Reference, with the motor does the sr04 return numbers?

Have you tried using serial prints?

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  Serial.println( duration );

Such as if duration 0 then all the rest of the math is not well. You can add other serial prints, I hope, to help troubleshoot the issue. Remove them when the issue is resolved.

I'd test the system with NewPing to prove the sonic is working.

The battery has a little more power than a 9 volt smoke detector battery.

And is that 4.8 volts when fully charged?

D3 and D4 have internal pullup-resistors. D8 is pulled to ground

Does your other and working code use D3 and D4 the same way?

int ena = D8;
int in4 = D3;
int enb = D4;

Yes my other code uses the same pins.

post this other code that works

The ultrasonic serial prints. The ultrasonic sensor is working. But the motor will simply not move.

Here is the code (.ino):

#include "htmlpage1.h"
int ena = D8;
int in1 = D6;
int in2 = D7;
int in3 = D2;
int in4 = D3;
int enb = D4;
int sto = 1;
int speed1 = 0;
String accessName ="robot"; 
const int changeStep = 20;// 20 is 20% every time button is pushed
int outPutValue = 40;// variable holding the light output vlaue (initial value) 40 means 40%
const int motorMinimumSpeed=20;

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>



#ifndef STASSID
#define STASSID "my ssid"
#define STAPSK  "my ssid password"
#endif

const char *ssid = STASSID;
const char *password = STAPSK;

ESP8266WebServer server(80);

void handleRoot() {
String HTML_page = speed_control_page_part1; 
 
 HTML_page.concat(outPutValue);  
 HTML_page.concat(speed_control_page_part2);  
 HTML_page.concat(outPutValue);
 HTML_page.concat(speed_control_page_part3);

 
  server.send(200, "text/html", HTML_page);

}

void handleNotFound() {

  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";

  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }

  server.send(404, "text/plain", message);

}

void setup(void) {
  pinMode(ena, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(enb, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
  
  Serial.begin(115200);

    
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");
  
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin(accessName)) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);
  server.on("/speed", HTTP_GET, handleMotorSpeed);  
  server.on("/stop", HTTP_GET, handleMotorBrake);
  server.on("/direction", HTTP_GET, handleMotorDirection);
  server.on("/right", HTTP_GET, handleMotorRight);           
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP server started");

}

void loop(void) {
  
  server.handleClient();
  MDNS.update();
    speed1 = (outPutValue * 2.5);
  
    if((sto == 1)) {
     analogWrite(ena, speed1); 
     analogWrite(enb, speed1); 
     Serial.print(speed1);
  }

  delay(100);
  
}

void handleMotorSpeed() {                                                                 
  if(server.arg("do") == "slower")
  {
    outPutValue -=changeStep;
    
      if(outPutValue < motorMinimumSpeed)
      {
        outPutValue = motorMinimumSpeed;
      }
  }else{
    outPutValue +=changeStep;   
     
      if(outPutValue > 100)
      {
        outPutValue =100;
      } 
  }

  handleRoot();
}//



void handleMotorBrake() {
  if(server.arg("do") == "START")
  {  
        sto = 1;
  }else{
        sto = 0;
        digitalWrite(in1,LOW);
        digitalWrite(in2,LOW);
        digitalWrite(in3,LOW);
        digitalWrite(in4,LOW);
  }
  handleRoot();
}//
void handleMotorDirection() {
  if(server.arg("dir") == "CW")
  {  
    digitalWrite(in1,HIGH);
    digitalWrite(in2,LOW);
    digitalWrite(in3,HIGH);
    digitalWrite(in4,LOW);      
  }else{
    digitalWrite(in1,LOW);
    digitalWrite(in2,HIGH);
    digitalWrite(in3,LOW);
    digitalWrite(in4,HIGH); 
  }
  handleRoot();
}//
void handleMotorRight() {
  if(server.arg("move") == "right")
  {  
    digitalWrite(in1,HIGH);
    digitalWrite(in2,LOW);
    digitalWrite(in3,LOW);
    digitalWrite(in4,HIGH);
  }else{
    digitalWrite(in1,LOW);
    digitalWrite(in2,HIGH);
    digitalWrite(in3,HIGH);
    digitalWrite(in4,LOW);
  }
  handleRoot();
}//

Here is the (.h file) that contatins the html coding:

const char speed_control_page_part1[]  PROGMEM = R"robojaxSpeed1(
<!DOCTYPE html>
<html>
<head>
<title>Robot Control</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box}

.container {
  width: 100%;
  background-color: #ddd;
}

.skills {
  text-align: right;
  padding-top: 10px;
  padding-bottom: 10px;
  color: white;
}

.html {width: )robojaxSpeed1";




const char speed_control_page_part2[] PROGMEM = R"robojaxSpeed2(%; 
background-color: #f44336;}
.nextprev a.rj-right, .nextprev a.rj-left {
    background-color: #f44336;
    color: #ffffff;
    border-color: #f44336;
}
.nextprev a {
    font-size: 22px;
    border: 1px solid #cccccc;
}
.rj-right {
    float: right!important;
}
.rj-btn, .rj-button {
    border: none;
    display: inline-block;
    padding: 8px 16px;
    vertical-align: middle;
    overflow: hidden;
    text-decoration: none;
    color: inherit;
    background-color: inherit;
    text-align: center;
    cursor: pointer;
    white-space: nowrap;
}
</style>
</head>
<body>

<h1>Speed Control</h1>
<div class="container">
<div class="skills html">)robojaxSpeed2";



const char speed_control_page_part3[] PROGMEM = R"robojaxSpeed3(%</div>
</div>
<hr>
<div class="nextprev">
<a class="rj-left rj-btn" href="/speed?do=slower">< Slower</a>
<a class="rj-right rj-btn" href="/speed?do=faster">Faster ></a>
</div>

<hr>
<h2>Start/Stop</h2>
<div class="nextprev">
<a class="rj-left rj-btn" href="/stop?do=START">START</a>
<a class="rj-right rj-btn" href="/stop?do=STOP">STOP</a>
</div>

<hr>
<h2>Direction</h2>
<div class="nextprev">
<a class="rj-left rj-btn" href="/direction?dir=CW">BACKWARD</a>
<a class="rj-right rj-btn" href="/direction?dir=CCW">FORWARD</a>
</div>

<hr>
<h2>Right/left</h2>
<div class="nextprev">
<a class="rj-left rj-btn" href="/right?move=right">Right</a>
<a class="rj-right rj-btn" href="/right?move=left">Left</a>
</div>

</body>
</html>)robojaxSpeed3";

(i didn't do the code all by myself)

With your first postings you made the impression that you have a good amount of basic knowledge about programming.

So I did not check the most basic things.

In your ultrasonic code defining the IO-pins as outputs is missing
As soon as I looked through your working code I saw it

You have to add these lines to the setup-function of your ultrasonic code.

2 Likes

OMG! THANK YOU VERY VERY MUCH. IT WORKED. I AM VERY GLAD THAT SOMEONE HELPED ME! THANKSS. :clap: :clap: :clap: :people_hugging:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.