# Using a LSM303DLHCompass and Arduino Uno to move a servo

Some background, I am doing a senior Design project to build a 32 ft Spar buoy that will gather renewable energy (using solar panels and a wind turbine) that will power all the electronic on the buoy. My team and I are building and designing a light system that will always point to the west no matter the rotation of the buoy. I am new to programing and electronics in general so I am looking for help in programing. We have the Arduino Uno and LSM303DLH 3D Compass and Accelerometer
Carrier with Voltage Regulators. We saw the code online for reading the compass and having been learning it, but we are having issues with using the compass heading to direct our servo. I have seen the video of it done but i am having issues on how to start writing the code. Thanks for any help

Hello.

What video are you talking about? Your question seems very broad; can you narrow it down to something specific that’s confusing you? I think there is a lot of example code out there for controlling servos with an Arduino. Have you looked at that yet?

By the way, most standard RC hobby servos only have a range of approximately 180 degrees. Are you using a special servo with a wider range? If not, it seems like it will not be possible to point the light west for all possible orientations of the buoy.

- Ben

The you tube video is

They are using the non tilt compensated version of our compass and getting the servo to turn.

We are having an issue with our servo and it having a floating zero with every new angle presented. As soon as I download a new code the zero on the servo changes. We are wondering how to set a hard zero for the servo.

We are wondering if this is also the reason we are having issue that when we tell our servo to go to an angle over 180 it doesn’t turn the angle it over shoots it.

We are playing with a sample code from the Arduino site to see if we can fix it before we continue with working it with the compass.

``````#include <Servo.h>

Servo myservo;

int pos = 0;
//int pos2 = 45;
//int pos3 = 90;
//int pos4 = 180;
//int pos5 = 270;
//int pos6 = 360;
void setup()
{
myservo.attach(9);
Serial.begin(9600);
}

void loop()
{
//  myservo.write(pos);
//  delay(80);
for(pos = 0; pos < 90; pos += 1)
{
myservo.write(pos);
Serial.print(" pos = ");
Serial.print(pos, DEC);
delay(80);
}
}
``````

Your post makes it sound like you don’t really understand too much about the servo you’re working with. Jan has made some recent blog posts about servos that I think might prove helpful. I suggest you take a few minutes and read through them, starting with the introduction to servos.

- Ben