I am doing a project where I need to make the car go and then stop at a wall using ultrasonic sensors(Hc-SR04). I have uploaded the code but it just hums. Any advice, tips or fixes would be great thanks. Here is the code I found and have been modifying.
/*
- created by Rui Santos, http://randomnerdtutorials.com
- Complete Guide for Ultrasonic Sensor HC-SR04
Ultrasonic sensor Pins:
VCC: +5VDC
Trig : Trigger (INPUT) - Pin11
Echo: Echo (OUTPUT) - Pin 12
GND: GND
*/
#include <Servo.h>
#include<NewPing.h>
Servo myservo;
int Trig = 8; //Trig - green Jumper
int Echo = 9; //Echo - yellow Jumper
long duration, dur_cm, dur_inches;
#define ENA 5
#define ENB 6
#define IN1 2
#define IN2 3
#define IN3 4
#define IN4 7
#define carSpeed 250
void stop() {
digitalWrite(ENA, LOW);
digitalWrite(ENB, LOW);
Serial.println("Stop!");
}
void forward(){
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
Serial.println("Forward");
}
void setup() {
//Serial Port begin
Serial.begin (9600);
//Define inputs and outputs
pinMode(Echo, INPUT);
pinMode(Trig, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
stop();
}
void loop()
{
myservo.attach(3);
myservo.write(90);
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(Trig, LOW);
delayMicroseconds(5);
digitalWrite(Trig, HIGH);
delayMicroseconds(10);
digitalWrite(Trig, LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(Echo, INPUT);
duration = pulseIn(Echo, HIGH);
// convert the time into a distance
dur_cm = (duration/2) / 29.1;
dur_inches = (duration/2) / 74;
Serial.print(dur_inches);
Serial.print("in, ");
Serial.print(dur_cm);
Serial.print("cm");
Serial.println();
delay(250);
if (dur_cm <= 50){
stop();
} else {forward();
}
}