I am very new to writing code and would be grateful for any help with the following.
I am building an object avoidance car. I have an Adafruit Motor Shield, two motors for my wheels, and an HCSR04 Ultrasonic Sensor. So far I have successfully been able to run the motors and the sensors on separate occasions using the two codes below.
My question is how do I combine the two sketches and write an if statement to stop the motors when the car gets too close to an object. If I could get some guidance just making it stop, I can continue to build the code to stop, backup, and turn.
First Code
#include <AFMotor.h>
AF_DCMotor motor2(2);
AF_DCMotor motor4(4);
void setup() {
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("Dual Motor test!");
// turn on motor
motor2.setSpeed(200);
motor4.setSpeed(200);
motor2.run(RELEASE);
motor4.run(RELEASE);
}
void loop() {
uint8_t i;
motor2.run(FORWARD);
motor4.run(BACKWARD);
for (i=0; i<255; i++)
{
motor2.setSpeed(i);
motor4.setSpeed(i);
delay(10);
}
for (i=255; i!=0; i--)
{
motor2.setSpeed(i);
motor4.setSpeed(i);
delay(10);
}
}
Second Code
#include <NewPing.h>
#define TRIGGER_PIN 5 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 6 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
int cm = sonar.ping_cm(); // Send out the ping, get the results in centimeters.
Serial.print("Ping: ");
Serial.print(cm); // Print the result (0 = outside the set distance range, no ping echo)
Serial.println("cm");
}