i want to make a code where the ultrasonic sensor can adjust the speed of the DC motor according to the distance (the farther the faster and the closer the slower). But I don't know where to put the code or how. In my code I tried to use a potentiometer and it worked. I want to replace the potentiometer with an ultrasonic sensor. Anyone can help me?
int pinPot = A0;
int nMotor1;
int nMotor2;
int nPot;
int Motor1 = 6;
int Motor2 = 5;
int pinButton = 2;
int dir1 = 4;
int dir2 = 7;
int stat;
void setup()
{
pinMode(Motor1, OUTPUT);
pinMode(Motor2, OUTPUT);
pinMode(pinPot, INPUT);
pinMode(pinButton, INPUT);
pinMode(dir1, OUTPUT);
pinMode(dir2, OUTPUT);
}
void loop()
{
stat = digitalRead(pinButton);
if(stat == LOW)
{
digitalWrite(dir1, LOW);
digitalWrite(dir2, HIGH);
}
else
{
digitalWrite(dir1, HIGH);
digitalWrite(dir2, LOW);
}
nPot = analogRead(pinPot);
nMotor1 = map(nPot, 0, 1023, 0, 255);
nMotor2 = map(nPot, 0, 1023, 0, 255);
analogWrite(Motor1, nMotor1);
delay(1);
analogWrite(Motor2, nMotor2);
delay(1);
}