The ServoTimer2 problem

I'm working on the RC car project that uses both servo and 433HZ wireless control. What I noticed and learned from the internet is that both Servo.h and virtualwire.h libraries use the same timer which is the timer1. So I switched the Servo.h to a new library called ServoTimer2. To test if this new library work, I used it in a simple joystick control project but it doesn't work. Here is my code of the joystick code:

#include <ServoTimer2.h>

ServoTimer2 myServo;

const int SW_pin = 2; // digital pin connected to switch output
const int X_pin = 0; // analog pin connected to X output
const int Y_pin = 1; // analog pin connected to Y output

void setup() {
pinMode(SW_pin, INPUT);
digitalWrite(SW_pin, HIGH);
Serial.begin(9600);
pinMode(10, OUTPUT);
myServo.attach(9);
}

void loop() {
Serial.print("Switch: ");
Serial.print(digitalRead(SW_pin));
Serial.print("\n");
Serial.print("X-axis: ");
Serial.print(analogRead(X_pin));
Serial.print("\n");
Serial.print("Y-axis: ");
Serial.println(analogRead(Y_pin));
Serial.print("\n\n");
delay(200);
\

if(analogRead(X_pin) < 400)
{
myServo.write(25);
delay(20);
}

if(analogRead(X_pin) > 600)
{
myServo.write(155);
delay(20);
}

if(analogRead(Y_pin) > 750)
{
digitalWrite(10, HIGH);
}
if(analogRead(Y_pin) < 750)
digitalWrite(10, LOW);

if(analogRead(X_pin) > 450 && analogRead(X_pin) < 650 )
{
myServo.write(90);
delay(20);
}
}

Hi there!

If possible, could you post any error messages you get when you try to upload the code, and if the code does upload successfully, can you post a picture of the serial monitor to see what gets posted there as well as a description of what the servo is doing at each point?

Thanks.

I guess you haven't noticed that ServoTimer2.write() takes a pulse length in microseconds NOT the 0-180 angle that Servo.write() uses. The minimum pulse length is around 550 microseconds so all of your values are too low which is why nothing happens. If you change write(90) to write(1500) that should work.

Steve

1 Like