ArduinoGeneral

Some confusions about using a sensor to control a DC motor

userHead Account cancelled 2017-04-28 00:20:44 1993 Views1 Replies
Hello, First, thank you for taking the time to read my post. I'm not very professional.So , please give me some time to explain my questions .

I am attempting to use an ultrasonic sensor to control a DC motor using the PWM output of an arduino. Fairly simple, I know, but I'm just a beginner.

Here's my code, with an explanation of my theory and my error afterwards.

define trigPin 7
define echoPin 2
define motorPin 9
void setup(){ Serial.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(motorPin, OUTPUT); }

void loop(){ int duration, distance; digitalWrite(trigPin, HIGH); delayMicroseconds(1000); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/2) /29.1; if (distance <5) { analogWrite(motorPin, 0); } else if(5 <= distance <15) { analogWrite(motorPin, 50); } else if(15 <= distance <25) { analogWrite(motorPin, 100); } else if(25 <= distance < 35) { analogWrite(motorPin, 150); } else if(35 <= distance < 45) { analogWrite(motorPin, 200); } else if(45 <= distance) { analogWrite(motorPin, 255); } else; { analogWrite(motorPin, 0); } Serial.print (distance); Serial.println (" cm"); delay(500); }

So, this is incredibly simple. I haven't yet begun differential drive nor braking, and soon I want to learn to change out the ultrasonic sensor programming with the NewPing library for more sensors and less delay.

Right now, I am hoping to have the arduino interpret the ultrasonic ping as a distance in centimeters and based of that distance set the DC motor to a defined speed. The PWM output goes to a 210 Ohm resistor connected to the base pin of a transistor, on the collector/emitter is the 18V circuit connected to the DC motor. On a separate circuit is the arduino and ultrasonic sensor. I was wondering if the component ( http://www.kynix.com/Detail/1128849/PMD9002D.html ) datasheets/part numbers would be helpful for you to solve my doubt.

The circuit successfully gives me accurate distances in the serial monitor window. However, the motor only goes at 100% speed. It does not throttle its speed regardless of the distance variable's value.

It startles me that the default motor speed for this setup is 100%, it makes me think the speed is acting digitally. I tried deleting the final elseif conditional for the distance being greater than 45 cm set speed at 100% and the circuit still powered the motor at 100%.

Any help would be greatly appreciated! Regards,
2017-05-03 22:39:56 What kind of motor are you using? Is its speed controllable or it's just an on-off motor userHeadPic robert.chen