Need help writing code for project after using AI bots didn't work

I have an Elegoo Uno R3, two ultrasonic sensors, and a stepper motor with a driver. I think the wiring was done correctly because each component functions fine on its' own. I have been trying to debug chat GPT's and Gemini's code but haven't quite gotten the results I am looking for. I think there must be some issue with the code.

This is how I want it to work:

  • Continuously check the sensor readings.
  • If either sensor is triggered for at least 3 seconds, the motor starts moving in direction 1 (for a set duration of time).
  • During this initial movement in direction 1, the sensors do not need to monitor but can
  • Once the initial movement is complete, the sensors begin to monitor for any activity within 1.5 feet.
  • The motor will not move in direction 2 (opposite dir.) for the same set amount of time until the path is clear for at least 3 seconds.
  • While the motor is moving in direction 2:
  • Continuously monitor the sensors.
  • If the sensors detect an object within 1.5 feet, stop the motor and reverse direction back to direction 1.
  • Move in direction 1 for the same amount of time it was moving in direction 2
  • Once the movement back to direction 1 is complete, monitor the sensors again.
  • If no activity is detected for at least 3 seconds, the motor will attempt to move in direction 2 again.

TIA for any input/ code

Before asking questions:


If your sketch was generated with an AI like ChatGPT or by someone else tell us in your post.


  • Questioners know what their hardware and software looks like but the volunteers here do not; you need to fully explain what’s not working, and how it is supposed to work.
  • Please read all the posting guidelines before asking your questions; follow these guidelines in your post.

Hardware

  • As always, show us a good schematic of your proposed circuit. Hand drawn schematics are acceptable.
  • Show us good images of your ‘actual’ wiring.
  • Give WEB links to your major components.

Software

  • For readability, place { and } on separate lines by themselves, place each line of code on a separate line.
  • In the Arduino IDE, use Ctrl T or CMD T to format your code, then copy the complete sketch.
  • Use the < CODE / > icon from the ‘posting menu’ to attach your copied sketch.


  • When you follow the posting guidelines, volunteers can be more effective.

  • More volunteers will help if you properly post your questions. (77)

Maybe it is trying to use the same physical resource more than once.

Who knows without seeing the undoubted mess AI would have inevitably made.

Let's step through your ideas, one at a time...

Using a pushbutton to simulate a sensor can help with your first bullet... see the LED light when the "sensor" is pressed.

// Continuously check the sensor readings.
byte sensorPin   =  2; // a button pin for this sketch

void setup() {
  pinMode(sensorPin, INPUT_PULLUP); // wire the button: sensorPin >> N.O. button pins >> ground
}

void loop() {
  if (!digitalRead(sensorPin)) // button NOT pressed is LOW, button PRESSED is HIGH
    digitalWrite(LED_BUILTIN, HIGH); // set LED_BUILTIN pin 13 HIGH
  else
    digitalWrite(LED_BUILTIN, LOW); // set LED_BUILTIN pin 13 LOW
}

1

Below is the following:

--- how the code should work according to chat gpt (I learned just because it perfectly understands how it should work doesn't mean it can generate perfectly working code)

--- the code

--- initial issues with the code

--- Also, any tips for using AI to generate better code is appreciated.

Here is how the code should work as explained back to me by Chat GPT:

Initialization

  1. Setup the Pins: Configure the pins for the ultrasonic sensors (echo and trigger pins) and the microstep driver (PUL and DIR pins).
  2. Variables Initialization: Initialize necessary variables to track sensor states, motor states, and timing.

Continuous Monitoring Phase

  1. Monitor Sensors Continuously: Continuously monitor the readings from both ultrasonic sensors.
  2. Check for Continuous Triggering:
  • If either sensor detects an object within 1.5 feet (45 cm) for at least 3 seconds continuously, prepare to start the motor in direction 1.

Motor Movement Direction 1 (Initial Movement)

  1. Start Motor Movement (Direction 1):
  • Move the motor in direction 1 for a set duration of 11 seconds.
  • During this movement, monitoring the sensors is optional but allowed.

Post-Movement Monitoring

  1. Post-Movement Monitoring:
  • After the initial 11-second movement (from Position 1 to Position 2), resume monitoring the sensors for any activity within 1.5 feet.
  • Ensure the Path is Clear: Check that no object is detected by either sensor for a continuous period of 3 seconds. This ensures the motor won't move into a potentially obstructed path.

Motor Movement Direction 2 (Reset and Full Movement)

  1. Start Motor Movement in Direction 2:
  • Move the motor in direction 2 while continuously monitoring the sensors.
  • Immediate Reversal on Detection: If either sensor detects an object within 1.5 feet during this movement, stop the motor immediately and reverse direction back to direction 1.

Motor Reversal to Direction 1

  1. Reverse Motor Movement:
  • Move the motor back in direction 1 for the appropriate time to return to position 2 after any detection. This could be less than 11 seconds and needs to be timed accurately.

Full Movement in Direction 2 to Reset

  1. Complete Full Movement in Direction 2:
  • Once the motor has returned to position 2 after reversing, continue monitoring the sensors.
  • The motor must move in direction 2 for a full 11 seconds with a clear path (no object detected within 1.5 feet) to reset the instructions to the start.

Continuous Loop

  1. Resume Monitoring:
  • Once the full 11-second movement in direction 2 is complete and the path is clear, resume sensor monitoring.
  • Path is Clear: Ensure no object is detected for at least 3 seconds continuously before attempting to move in direction 1 again from Position 1.

Summary

  • Sensor Monitoring: Always monitor sensors except during the initial movement in direction 1.

  • Trigger Time: Ensure an object is continuously detected for 3 seconds before starting or stopping motor actions, except for immediate reversal in step 7.

  • Motor Actions:

    • Move in direction 1 for 11 seconds after initial trigger.
    • Move in direction 2 while ensuring a clear path, stopping immediately and reversing to direction 1 if an object is detected.
    • Reverse direction to move back in direction 1 for the appropriate time to return to position 2 after any detection.
    • Ensure the motor completes a full 11-second movement in direction 2 with no obstruction to reset instructions.
  • Timing and Distance Constants:

    • stepDelay is 50 ms.
    • detectionDistance is 45 cm.
    • sensorTriggerTime is 3 seconds.
    • motorMoveTime is 11 seconds for both movements in directions 1 and 2.

Here is the code I have right now, generated from Chat GPT

// Define constants
const int echoPin1 = 4;   // Echo pin of sensor 1
const int trigPin1 = 5;   // Trigger pin of sensor 1
const int echoPin2 = 6;   // Echo pin of sensor 2
const int trigPin2 = 7;   // Trigger pin of sensor 2
const int PUL_PIN = 2;    // PUL- pin of microstep driver
const int DIR_PIN = 3;    // DIR- pin of microstep driver
const int stepDelay = 50;  // Delay between steps (in ms)
const int detectionDistance = 45;  // Distance in cm for detection (1.5 feet = 45.72 cm)
const unsigned long sensorTriggerTime = 3000;  // Time to detect object continuously (3 seconds)
const unsigned long motorMoveTime = 11000;  // Time to move the motor in milliseconds (11 seconds)

// Variables for motor control and state
bool motorMoving = false;
bool direction1 = true; // true for direction 1, false for direction 2
unsigned long motorStartTime = 0;
unsigned long sensorStartTime = 0;
unsigned long lastPrintTime = 0; // Variable to track last print time

// Distance variables
int distance1 = 0;
int distance2 = 0;

void setup() {
  // Initialize serial communication for debugging
  Serial.begin(9600);
  
  // Initialize pin modes
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(PUL_PIN, OUTPUT);
  pinMode(DIR_PIN, OUTPUT);
}

void loop() {
  // Step 3: Continuously monitor sensors
  int objectDetected = checkSensors();
  
  // Print distances and messages once every half second
  if (millis() - lastPrintTime > 500) {
    Serial.print("Distance 1: ");
    Serial.print(distance1);
    Serial.print(" cm, Distance 2: ");
    Serial.print(distance2);
    Serial.println(" cm");
    
    // Update last print time
    lastPrintTime = millis();
  }
  
  // Step 4: Check for continuous triggering
  if (objectDetected > 0 && millis() - sensorStartTime > sensorTriggerTime && !motorMoving) {
    // Start motor in direction 1
    startMotor(direction1);
  }
  
  // Step 6: Post-movement monitoring
  if (motorMoving && millis() - motorStartTime > motorMoveTime) {
    motorMoving = false;
    direction1 = !direction1; // Toggle direction after completion of movement
    Serial.println("Motor stopped after 11 seconds.");
    sensorStartTime = millis(); // Start monitoring sensors again
  }
  
  // Step 7: Motor movement in direction 2 with immediate reversal on detection
  if (motorMoving && !direction1) {
    if (objectDetected > 0) {
      // Immediate reversal
      stopMotor();
      delay(100); // Small delay for stability
      startMotor(true); // Start moving back in direction 1
    }
  }
}

// Function to check sensors and return 1 if object detected, 0 if not
int checkSensors() {
  long duration1, duration2;
  int distance1_temp, distance2_temp; // Declare temporary distance variables
  
  // Sensor 1
  digitalWrite(trigPin1, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1_temp = duration1 * 0.034 / 2;

  // Sensor 2
  digitalWrite(trigPin2, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin2, LOW);
  duration2 = pulseIn(echoPin2, HIGH);
  distance2_temp = duration2 * 0.034 / 2;

  // Assign values to distance variables after validity checks
  if (distance1_temp >= 0 && distance1_temp <= 400) {
    distance1 = distance1_temp;
  }
  
  if (distance2_temp >= 0 && distance2_temp <= 400) {
    distance2 = distance2_temp;
  }

  // Check if object detected within detectionDistance cm
  if (distance1 <= detectionDistance || distance2 <= detectionDistance) {
    return 1;
  } else {
    return 0;
  }
}

// Function to start the motor
void startMotor(bool dir) {
  digitalWrite(DIR_PIN, dir ? HIGH : LOW); // Set direction
  digitalWrite(PUL_PIN, HIGH); // Step pulse
  delay(stepDelay);
  digitalWrite(PUL_PIN, LOW);
  delay(stepDelay);
  
  motorMoving = true;
  motorStartTime = millis(); // Record start time
  Serial.println(dir ? "Motor started in direction 1." : "Motor started in direction 2.");
}

// Function to stop the motor
void stopMotor() {
  digitalWrite(PUL_PIN, LOW);
  motorMoving = false;
}

Initial issues:

  1. Motor isn't moving or is pulsing although a 50 ms stepdelay has worked before

Take a look at the example sketch newPingEventTimer in the NewPing library by Tim Eckel.
https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home

So I see a whole lot of effort put in by chatGPT but nothing from you. Maybe if we knew what you asked ChatGPT for in the first place, it would help us mere humans to see if the problem wasn't in the response by ChatGPT, but in your initial project goal and how you thought ChatGPT should write it for you.
What I mean is,

How do you want what to work? What is the device trying to accomplish in the first place?

@captkirk151
Sounds like you are trying to make an obstacle avoiding robot using an Arduino
There are dozens of examples on the internet, that actually work.
Why don't you try one.

actually a sensor activated sliding cat door with a lead screw attached to a stepper motor.

A sliding cat door with a lead screw/ nut mechanism. But that is kind of irrelevant. I just need the code to do what it's supposed to do.

Poor cat :slight_smile:
The 40kHz ultrasonic pulses must sound like a machine-gun to a cat.
An optical proximity sensor seems more appropriate.
Leo..

They are silent haha

I know what it's supposed to do as it is explained in my above post.

What's important is figuring out how to write code that can allow the components (motor and sensors) to perform as needed as explained above. What the sensors and motor are used for is not needed to figure out how to write working code but I can understand how it would be interesting to people to know the application.

So what those components do (outside of responding to the code) is kind of irrelevant.

Again, I wrote a detailed step by step explanation on what I would like the code to do and need to figure out how to write it/ debug Chat GPT's code.

One particular issue that arose was the Arduino wasn't able to print sensor values (distances to nearest object) to the serial monitor while the stepper motor was running for some reason. This is needed to prevent the door from closing while my cat is still within range.

I'll return to this post with more specific questions once I can pinpoint more specifically where the problems may lie in the code.

okay the sensors are not silent but are registering like 45 dB max haha

the main problem is figuring out why the arduino won't transmit signals from the sensors while the stepper motor is running. Sensors and motor have different power supply but share the same gnd.

Disagree since you're the one asking random people for assistance. I for one can't look at where you're at and make sense of it without knowing what it is you're trying to do.

Now that I can visualize the contraption, I can visualize the problem. But I'm working in another thread at the minute, will check back later.

that's fair its probably helpful information to know.

So there is a common ground between the motor and two sensors and they are wired in parallel. The sensors are powered by 5v arduino and the motor is powered with a 12v adapter so they are using their recommended voltage supply.

Here is an explanation of the schematic but I can make a hand sketch if that is easier.

Motor Driver:

Pins VCC, GND, A+, A-, B+, B-, PUL+, PUL-, DIR+, DIR- are connected to corresponding components.
VCC and GND are connected to the external 12V power supply.
PUL+ and PUL- are connected to 5V on the Elegoo.

Stepper Motor:

Connections A+, A-, B+, and B- are connected to the motor driver outputs.

Ultrasonic Sensors:

Each sensor has VCC and GND connected to 5V and GND on the Elegoo, respectively.
Trig and Echo pins are connected to designated digital pins on the Elegoo.

Elegoo Microcontroller:

The Elegoo is connected to all components:
    Digital pins for Trig and Echo of both sensors.
    Digital pins for PUL+ and DIR+ of the motor driver.
    Ground (GND) is common with the motor driver and sensors.

I'd approach the code as multiple task-functions inside of void loop() and not a monolithic do-everything block. Would I care what the AI did? Probably not. I also don't use int for pin numbers but do use bits for states and state machines to step through processes. I tend to use less code that way, less to debug.

Why fix AI code? If it was good, it'd work.

When I used an ultrasonic sensor on a fuzzy wool field shirt, it didn't get good returns. If the cat's a longhair, how well does does the Ping sense it? Would reflective IR or IR blocking sense work any better or make a complementary sensor? There is also capacitive sensing that could be used to be more complete, that's DIY and uses 1 or 2 pins.