DC Motor with Encoder Not Turning on Tinkercad


Hi, I'm trying to code a DC Motor with Encoder to rotate when it senses a specific distance (150cm) on an Ultrasonic Distance Sensor. For some reason, if I start the simulation when above 150cm, it won't turn at all. If I start it below said distance, the motor turns, but the moment I go above then back down it won't start up again. My code and project are given, could anyone help me out with this issue?

#include <Encoder.h>
#define echoPin 12
#define trigPin 11

long duration;
int distance; 
Encoder myEnc(2, 3);

void setup() {
  Serial.begin(9600);
  Serial.println("Basic Encoder Test:");
  pinMode(11, OUTPUT);
  pinMode(12, INPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
}



void loop() {
int Position = 0;
  
  digitalWrite(trigPin, LOW);
  delayMicroseconds(200);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;
  
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  
  Position = myEnc.read();
 
 
 
  
  if(distance < 150 && Position < 80)
 {
  digitalWrite(5, HIGH);
  digitalWrite(6, HIGH);
  delay(1000);
     Serial.println(Position);
    }
  
  if(distance < 150 && Position > 80)
 {
  digitalWrite(5, LOW);
  digitalWrite(6, LOW);

  }
}

It looks like you are supplying power from the Arduino to the DC motor. The DC motor (by way of a motor controller) must have a separate power supply.

How does TinkerCad simulate a ping echo being received?

Move the green puck. Data is in the breadboard, below the cone.


Thank you for the response. Sorry for the rough wiring job, but everything should be connected and now the motor isn't moving at all even when below 150cm. Code is unchanged. Any ideas?

Did you wire the L293D correctly? Show the original schematic you are using. Name and number the pins on every device to make the tinkercad readable. Do not power the stepper with the Arduino. Use external power.

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