Hi, I have a code that turns on/off a motor via a distance sensor. My problem is when it turns the motor off it just turns off at a random position, and I want the motor to stop at a specific spot every time it is turned off. This way the mirror that I have attached to the shaft of the motor is back in the original level position every time the motor stops spinning.
Here's the code I have that adjusts the PWM to the motor.
#include "Ultrasonic.h"
int LED1 = 9; // LED1 Pin
int TRIG = 2; // Trigger Pin
int ECHO = 3; // Echo Pin
int Range; // The range of the object from the HC-SR04 Ultarsonic Module
Ultrasonic ultrasonic(TRIG,ECHO); // Create and initialize the Ultrasonic object.
void setup() {
Serial.begin(9600);
pinMode(LED1, OUTPUT);
}
void loop() {
Range = ultrasonic.Ranging(CM); // Range is calculated in Centimeters.
// Range = ultrasonic.Ranging(INC); // Range is calculated in Inches.
Serial.print(Range);
Serial.println("cm");
if (Range != 0 && Range <= 100) {
digitalWrite(LED1, HIGH);
delay(14);
digitalWrite(LED1, LOW);
delay(50);
}
if (Range != 0 && Range <= 50) {
digitalWrite(LED1, HIGH);
delay(20);
digitalWrite(LED1, LOW);
delay(50);
}
}