You should use myservo.writeMicroseconds and not myservo.write.
When you attach a servo and do not define the range the PWM signal for 0 degrees is 544 microseconds and 180 degees is 2400 microseconds by default. RC controllers only have a range of around 1000 microseconds.
Also with your code you are setting the mid point @ 40 but the range for the servo is 0 to 180 so 90 is actually your mid point, 180 is your max. You also don’t need the delay in the void setup ()
Here is a bit of code I modified to move a servo back and forth at a fixed rate. (don’t forget to add the include servo at the beginning). I’m trying to learn to code without the use of Delay as that function stops the Ardunio from doing anything while it is active but I don’t have the time to change it right now.
Servo myservo; // create servo object to control a servo
double pos = 0; // variable to store the servo position
int delayTime = 15; // this variable sets the delay time between each step
void setup() {
myservo.attach(9, 1000, 2000); // attaches the servo on pin 9 to the servo object
myservo.writeMicroseconds(1500); // sets the servo to mid point
Serial.begin(9600);
}
void loop() {
for (pos = 1000; pos <= 2000; pos += 10) { // goes from 1000 microseconds to 2000 microseconds
// in steps of 10
myservo.writeMicroseconds(pos); // tell servo to go to position in variable ‘pos’
delay(delayTime); // delays the time before moving to the next position
Serial.println(pos);
}
for (pos = 2000; pos >= 1000; pos -= 10) { // goes from 180 degrees to 0 degrees
myservo.writeMicroseconds(pos); // tell servo to go to position in variable ‘pos’
delay(delayTime); // delays the time before moving to the next position
Serial.println(pos);
}
}