Hi, I am a total noob when it comes to coding and I am having a lot of difficulty with this project I am working on. I am trying to build an autonomous toy car that simply has to run until it comes in contact with an obstacle and then stop. I have all components (motor and sensor) hooked up to the arduino properly and have the code for the ultrasonic sensor running perfectly. The car runs and the sensor measures distances (through the serial monitor), however I don't know how to code it so that when the ultrasonic sensor detects a object 15cm or closer, to cut the motor. please help!
here is the code so far (the motor is running directly off of pin 13 for simplicity):
#define trigPin 3
#define echoPin 2
#define MAX_DISTANCE 200
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
Serial.print(distance);
Serial.println(" cm");
delay(250);
}