1

enter image description hereI have a weird thing with my servo, I really dont know what is wrong with my code, I tried everything. Either it is my connection on arduino or my code. Please help me guys, this is my code.

#include <Servo.h>     

int servoPin = 9;     
Servo servo;          
int angle = 0;         
int photocellPin = 0;  

void setup() { 
  servo.attach(servoPin);  
} 

void loop() { 
  int reading = analogRead(photocellPin);     
  Serial.print("Reading = ");
  Serial.println(photocellPin);
  int newAngle = reading / 2;             
  servo.write(newAngle);  
  delay(80);                      
} 
  • Can you describe exactly what is weird with the servo? It just sits there and do nothing? – Ricardo May 29 '14 at 19:51
  • Maybe a good quality picture of your setup would help us help you. Also, it could help if you tested the photocell separated from the servo. For example, have you tried to feed a few hardcoded angles to the servo, say, 0, 90, 180, 90, 0, delaying a few seconds from each call? Also, what results do you get from the serial prints? – Ricardo May 29 '14 at 19:55
  • Thank you for answering. The servo acts weird in a way that it is moves and gives little shocks each time. Also my connection with my usb port doesnt work continue, I got the feeling their is a bad connection. I will make a picture of my setup, maybe it is just the wires. – user3688952 May 29 '14 at 19:59
  • You mean the servo doesn't move smoothly, but in quick steps, like it's quicking, is that it? Can you show us your circuit and tell us which servo it is. Maybe the servo is trying to use more current than the USB is able to provide and that's causing the suply voltage to drop and making the Arduino reset. – Ricardo May 29 '14 at 20:05
  • I added a photo :) It is a small servo. – user3688952 May 29 '14 at 20:09
3

Servos accept a signal from 0 to 180, with 90 being the center point on the servo. analogRead() will output a number from 0 to 1023. The arduino "map" function makes a conversion easy to do. just replace

int newAngle = reading / 2;

with

int newAngle = map(reading, 0, 1023, 0, 180);

you can read more about the map function here: http://arduino.cc/en/reference/map

It is hard to tell from the picture that everything else is wired correctly, but this should fix up your code.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.