using an ultrasonic sensor to change motor speed

as the object gets further away from the sensor, the speed of the motor is supposed to increase and if it out of the range of 10-30 it shouldn't be working at all. please please help i am so so so desparate this is what i have and once you are greater than 10cm away from the sensor, the sensor it goes at 100% speed. thank you!!!!!


This example shows how to fade an LED using the analogWrite() function.

The circuit:

  • LED attached from digital pin 9 to ground.

created 1 Nov 2008
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.


int trigPin = 11;
int echoPin = 6;
int ledPin = 10;
int speed

void setup() {
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
pinMode(ledPin, OUTPUT);

void loop() {
long duration, cm;
digitalWrite(trigPin, LOW);
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
cm = (duration/2)/29.1;

if (cm<10)
{Serial.println("invalid placement of object");
analogWrite(ledPin, 0);}

else if (cm>= 10 && cm <=12)
{analogWrite(ledPin, 0);}

else if (cm>=13 && cm<=17)
{analogWrite(ledPin, 64);}

else if (cm>=18 && cm<22)
{analogWrite(ledPin, 128);}

else if (cm>=23 && cm<=27)
{analogWrite(ledPin, 192);}

else if (cm>=28 && cm <=30)
{analogWrite(ledPin, 255);}

{Serial.println("invalid placement of object");}

if (cm>=10 && cm<=30)


void PrtSpeed(){
analogWrite(ledPin, 255);

I see an LEDPin, nothing about a motor.

I see that in the first if statement you do nothing for cm between 12 and 13, between 17 and 18, etc. That's probably not what you want.

That is followed by an if statement where if cm is between 10 and 30 you the analogWrite to 255. That doesn't make sense in light of the first if statement.

Also, do make sure you read the sticky so you know how to post code properly (between code tags), and the other information we need for an informed answer.