Hi,
I'm newbie here. I'm making a tank robot with 2 motor dc, l298n, with 1 servo, 1 ultrasonic sensor, and lcd to display the distance. Here the code
#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Motor DC
const int ENA = 10;
const int IN1 = 7;
const int IN2 = 6;
const int ENB = 9;
const int IN3 = 5;
const int IN4 = 4;
// Servo
Servo myServo;
const int servoPin = 13;
// Ultrasonic
const int trigPin = 12; // Pin trig
const int echoPin = 11; // Pin echo
// LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Variabel distance
long duration;
int distance;
// Servo interval
unsigned long previousMillis = 0;
const long interval180 = 2000; // 2 s 180 degree
const long interval80 = 5000; // 5 s 80 degree
bool servoAt180 = true;
void setup() {
// Motor DC
pinMode(ENA, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(ENB, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
// Ultrasonic
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Servo
myServo.attach(servoPin);
myServo.write(180);
// LCD
lcd.begin(16, 2);
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Initializing...");
delay(2000);
lcd.clear();
// Serial Monitor
Serial.begin(9600);
}
void loop() {
distance = getDistance();
lcd.setCursor(0, 0);
lcd.print("Jarak: ");
lcd.print(distance);
lcd.print(" cm ");
lcd.setCursor(0, 1);
lcd.print(" ");
if (distance > 20) {
moveMotors(true);
moveServoWithDelay();
} else {
stopMotors();
myServo.write(80);
}
delay(100);
}
int getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
Serial.print("distance: ");
Serial.print(distance);
Serial.println(" cm");
return distance;
}
void moveMotors(bool forward) {
if (forward) {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
analogWrite(ENA, 200);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
analogWrite(ENB, 200);
}
}
void stopMotors() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
analogWrite(ENA, 0);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
analogWrite(ENB, 0);
}
void moveServoWithDelay() {
unsigned long currentMillis = millis();
if (servoAt180 && currentMillis - previousMillis >= interval180) {
previousMillis = currentMillis;
myServo.write(80);
servoAt180 = false;
} else if (!servoAt180 && currentMillis - previousMillis >= interval80) {
previousMillis = currentMillis;
myServo.write(180);
servoAt180 = true;
}
}
I am using 3x3,7 volt batteries for motor dc and arduino, and 2x3,7v batteries for servo, sensor and lcd. But it's not working
The DC motor and servo should move and will stop when the ultrasonic sensor detects an object at a distance of less than 20 cm. The lcd should display distance from ultrasonic sensor.
PLEASE HELP! THANKS
