Hi guys, I am new to this.
when i made this circuit, it is not working. I put object infront of the ultrasonic sensor and the dc motor is not working. this is the code:
// C++ code
//
int distance = 0;
int motorPin = 5; // Assuming the motor is connected to digital pin 5
unsigned long motorActivationTime = 0;
int motorSpeed = 128; // Set the motor speed to 128 (adjust as needed)
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void setup()
{
Serial.begin(9600);
pinMode(motorPin, OUTPUT);
}
void loop()
{
Serial.println(0.01723 * readUltrasonicDistance(3, 2));
distance = 0.01723 * readUltrasonicDistance(3, 2);
if (distance < 20) {
analogWrite(motorPin, motorSpeed); // Spin the motor at the specified speed
// Set the motor activation time
motorActivationTime = millis();
} else {
// Check if 15 seconds have passed since motor activation
if (millis() - motorActivationTime > 15000) {
digitalWrite(motorPin, LOW); // Turn off the motor after 15 seconds
}
}
delay(10); // Delay a little bit to improve simulation performance
}`
[quote="system, post:1, topic:226563, full:true"]
Hi guys,
I'm new to this and still there's still so much that I can learn. What I'm trying to do is I'm trying to control a 5v DC motor with an ultrasonic sensor. Basically what I want is that the distance determines the speed of the motor, whereas an object that's further away speeds up the motor, and when the object is close it'll slow down the motor. So far no luck, even though I know for a fact that the sensors are working because of the serial print thingy
So far I have this: (I'm a big noob and don't know if this is correct) and any help would be highly appreciated
#define trigPin 13
#define echoPin 12
#define motorPin 8
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motorPin, INPUT);
}
void loop () {
int duration, distance;
digitalWrite (trigPin, HIGH);
delayMicroseconds (1000);
digitalWrite (trigPin, LOW);
duration = pulseIn (echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 20) { // Distance from sensor
digitalWrite (motorPin, HIGH); // When in range, motor should start high
}
else {
digitalWrite(motorPin, LOW);
}
if (distance > 20) { // Distance from sensor
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}