Ultrasonic sensor

Hello, relatively new in all of this so I am stuck with combining ultrasonic HC-SR04 into my code. Basically I am making Bluetooth remote car (which is working) and now I need to write code which will not allow me to go forward when sensor detects distance less then 30cm for example.

We can't see the code you're trying to combine.

#include <AFMotor.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(A4, A5);

//initial motors pin
AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(2, MOTOR12_1KHZ);

char command;

void setup()
{
  mySerial.begin(9600); 
}

void loop(){
  if(mySerial.available() > 0){
    command = mySerial.read();
    Stop(); 
    switch(command){
    case 'F':
      forward();
      break;
    case 'B':
       back();
      break;
    case 'L':
      left();
      break;
    case 'R':
      right();
      break;
    }
  }
}

void forward()
{
  motor1.setSpeed(255); 
  motor1.run(BACKWARD); 
  motor2.setSpeed(255); 
  motor2.run(BACKWARD); 
}

void back()
{
  motor1.setSpeed(255); 
  motor1.run(FORWARD); 
  motor2.setSpeed(255); 
  motor2.run(FORWARD); 
}

void left()
{
  motor1.setSpeed(255); 
  motor1.run(BACKWARD);
  motor2.setSpeed(255); 
  motor2.run(FORWARD);  
}

void right()
{
  motor1.setSpeed(255);
  motor1.run(FORWARD); 
  motor2.setSpeed(255); 
  motor2.run(BACKWARD); 
}

void Stop()
{
  motor1.setSpeed(0); 
  motor1.run(RELEASE);
  motor2.setSpeed(0); 
  motor2.run(RELEASE); 

}

This is the code without any parts for ultrasonic which works without problem, I just don't know how to write ultrasonic part. Never worked with it so yeah. Anything helps

A common mistake is to take range readings too frequently.
You should try not to exceed more than about 20 to 30 readings per second.

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