Motor interacting with ultrasonic motion sensor code problems. Please help!

thanks Paul!

You are correct in your diagnoses. The trick is that the Arduino supports PWM. This means that you set a pin to a level and you are done. There is no need to worry about the timing within your main loop.

Read about an Arduino library for this here: http://www.arduino.cc/en/Reference/Servo

And just google "PWM" for a wikipedia article that describes it well.

if(distance<500)
{
int motor_speed=255*0; // must be >0 and <= 255
analogWrite( motorpin1, motor_speed);
}
else if(distance>=500)
{
int motor_speed=100; // must be >0 and <= 255
analogWrite( motorpin1, motor_speed);
}
else
{
delay(5000);
}

Crappy indentation aside, under what circumstances will the else block ever be executed?

I don’t understand leaving lots of white space between lines and then jamming everything together on the lines you do have. Spaces before and after the = sign, for instance, make the code a lot easier to read.

The Tools + Auto Format menu item will fix the crappy indenting, too.

PaulS:

if(distance<500)

{
int motor_speed=255*0; // must be >0 and <= 255
analogWrite( motorpin1, motor_speed);
}
else if(distance>=500)
{
int motor_speed=100; // must be >0 and <= 255
analogWrite( motorpin1, motor_speed);
}
else
{
delay(5000);
}



Crappy indentation aside, under what circumstances will the else block ever be executed?

I don't understand leaving lots of white space between lines and then jamming everything together on the lines you do have. Spaces before and after the = sign, for instance, make the code a lot easier to read.

The Tools + Auto Format menu item will fix the crappy indenting, too.

Sorry bout the crappy indentation. I tried using the Tools + Auto Format you had mentioned and it didn’t fixing the indentation as you mentioned. Anyways, I meant to input another motor speed function for the else block similarly to the else if function. I was just wondering if I should rewrite everything that was digital and convert it to analog so that the 0 disappear?

I was just wondering if I should rewrite everything that was digital and convert it to analog so that the 0 disappear?

No idea what that means. What 0?

Below is an image of what I meant. Image seems to be broken, heres a link to the photo via dropbox. https://www.dropbox.com/s/zu0ckligcpbj1px/serialmonitor.jpg

Serial.println(distance);
Serial.print(cm);
Serial.print("cm");
Serial.println();

You, too, need to understand the difference between Serial.print() and Serial.println(). You are printing two values on separate lines, and then complaining when you get two lines of output. Stop printing the bogus value.

Thank you Paul! You just pin pointed out my problem! :)