Help me please

Hi everyone

I am using a Arduino Duemilanove and a Ultrasonic ranger to hold the altitude of an Quad-copter. I can use transmitter's switch to switch between altitude hold mode and manual throttle control mode. Once I switch to altitude mode, the Arduino will send a pwm to throttle dut to the range to the ground. It is working only when it connected to my computer. If it is not connect to computer, the manual control mode is good. If I switch to altitude hold mode, the motor will be out of control. Is there any problem in the software?

Test video: - YouTube
The test video just show you how it works. The arduino has been connected to the computer. So it works well.

here is my software:

#include <Servo.h>
Servo myservo;
const int echo = 12;
const int trig = 13;
const int sw = 3;
const int th = 4;

void setup()
{

pinMode(echo,INPUT);
pinMode(trig,OUTPUT);
int sensorValue = digitalRead(echo);
int swValue = digitalRead(sw);
int thValue = digitalRead(th);
myservo.attach(9);
}

void loop()
{
long duration, hold ,power;
hold = pulseIn(sw,HIGH);
if (hold>1500)
{
digitalWrite(trig,LOW);
delayMicroseconds(2);
digitalWrite(trig,HIGH);
delayMicroseconds(12);
digitalWrite(trig,LOW);
duration = pulseIn(echo,HIGH);
duration = map(duration, 0, 1000, 135, 45);
myservo.write(duration);
}
else {
power = pulseIn(th,HIGH);
power = map (power, 1000, 2000, 135, 45);
myservo.write(power);
delay(15);
}
}

Why do you do this:

 int sensorValue = digitalRead(echo);
  int swValue = digitalRead(sw);
  int thValue = digitalRead(th);

?

I think the ultrasonic sensor does not work, when I pull out the USB.

Maybe you don't have enough current to power it.

AWOL:
Maybe you don't have enough current to power it.

I agree, software should not change because of being powered via external power Vs USB power. It would be helpful if we could see a drawing of at least the power wiring between all the system components.

Lefty

Hello, Have you considered how wind will change the result, have you thought about using GPS instead, just a thought

have you thought about using GPS instead

to hold the altitude of an Quad-copter

It would have to be differential GPS, I think.

Hello, Have you considered how wind will change the result, have you thought about using GPS instead, just a thought

I don't think exact position matters, so long as it doesn't fly into the ground. As for flying into anything else, GPS would not likely help much there either.