Robot sumo code, knock down cans

Hi, i need advice for programming code for a sumo that can konock down cans. But there are some details, that make code doesnt work.

#include <AFMotor.h>

AF_DCMotor motor1(1); // Motor derecho
AF_DCMotor motor2(2); // Motor izquierdo

#define IR_SENSOR_LEFT A0
#define IR_SENSOR_RIGHT A1
#define ULTRASONIC_TRIGGER_PIN 3
#define ULTRASONIC_ECHO_PIN 2
#define MOTOR_SPEED 150
#define DISTANCE_THRESHOLD 20

void setup() {
  Serial.begin(9600);
  pinMode(IR_SENSOR_LEFT, INPUT);
  pinMode(IR_SENSOR_RIGHT, INPUT);
  pinMode(ULTRASONIC_TRIGGER_PIN, OUTPUT);
  pinMode(ULTRASONIC_ECHO_PIN, INPUT);
}

void loop() {
  int leftSensorValue = digitalRead(IR_SENSOR_LEFT);
  int rightSensorValue = digitalRead(IR_SENSOR_RIGHT);

  if (leftSensorValue == LOW && rightSensorValue == LOW) {
    // Ambos sensores detectan negro, retrocede
    backward();
  } else if (leftSensorValue == LOW) {
    // Solo el sensor izquierdo detecta negro, gira a la derecha
    turnRight();
  } else if (rightSensorValue == LOW) {
    // Solo el sensor derecho detecta negro, gira a la izquierda
    turnLeft();
  } else {
    // Ambos sensores detectan blanco, busca latas
    findCans();
  }
}

void backward() {
  motor1.setSpeed(MOTOR_SPEED);
  motor2.setSpeed(MOTOR_SPEED);
  motor1.backward();
  motor2.backward();
  delay(500); // Ajusta el tiempo de retroceso según sea necesario
}

void turnRight() {
  motor1.setSpeed(MOTOR_SPEED);
  motor2.setSpeed(MOTOR_SPEED);
  motor1.backward();
  motor2.forward();
  delay(500); // Ajusta el tiempo de giro según sea necesario
}

void turnLeft() {
  motor1.setSpeed(MOTOR_SPEED);
  motor2.setSpeed(MOTOR_SPEED);
  motor1.forward();
  motor2.backward();
  delay(500); // Ajusta el tiempo de giro según sea necesario
}

void findCans() {
  // Mover hacia adelante
  motor1.setSpeed(MOTOR_SPEED);
  motor2.setSpeed(MOTOR_SPEED);
  motor1.forward();
  motor2.forward();

  // Medir distancia con el sensor ultrasónico
  long duration, distance;
  digitalWrite(ULTRASONIC_TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(ULTRASONIC_TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(ULTRASONIC_TRIGGER_PIN, LOW);
  duration = pulseIn(ULTRASONIC_ECHO_PIN, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance < DISTANCE_THRESHOLD) {
    // Lata detectada, realiza acciones necesarias
    // Puedes agregar código adicional para derribar la lata, etc.
    stopMotors();
  }
}

void stopMotors() {
  motor1.setSpeed(0);
  motor2.setSpeed(0);
}

i need to know what is wrong with this and what modifications need

Hello lem_humildeee

Welcome to the world's best Arduino forum ever.

You might provide more information to see how we can help.

Do you have a schematic, too?

Have a nice day and enjoy coding in C++.

@lem_humildeee - What works and what does not work?

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