Pin 9 output stops working if attaching a servo to Pin 10 or 11

Hi all,

I've got a strange problem with a Nano. I'm using pins 3, 5, 6 and 9 to drive a dual hbridge (L298N breakout board). If I attach a servo to pins 10 or 11, then pin 9 stops working. Hopefully I've posted this to the right place, not sure if it is a problem with my code (noob) or not.

Here is my code, I've commented out the servo parts, it works fine like this but as soon as I uncomment HeadServo.attach(10); then Pin 9 stops working...

Thanks for your help!

/*
Motor control test
*/

#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"
#include <Servo.h>
#include <Serial.h>

//Pins to HBridge Motor Driver L298N
#define M1Pin1  3
#define M1Pin2  5
#define M2Pin1  6
#define M2Pin2  9

#define M1PotPin  A0
#define M2PotPin  A1
#define Servo1PotPin A2

#define BatVoltPin A3

Servo HeadServo;

void setup()
{
  Serial.begin(9600);
  //HeadServo.attach(10);
}

void loop()
{
  //Motor 1 command - Read motor 1 pot and map value to pin 1 if above middle point, map to pin 2 if below middle point
  int M1PotVal = analogRead(M1PotPin);
  if(M1PotVal > 511.5)
  {
    analogWrite(M1Pin1, map(M1PotVal, 511.5, 1023, 0, 255));
    analogWrite(M1Pin2, 0);
  }
  else
  {
    analogWrite(M1Pin2, map(M1PotVal, 511.5, 0, 0, 255));
    analogWrite(M1Pin1, 0);
  }
  
  //Motor 2 command - Read motor 2 pot and map value to pin 1 if above middle point, map to pin 2 if below middle point
  int M2PotVal = analogRead(M2PotPin);
  if(M2PotVal > 511.5)
  {
    analogWrite(M2Pin1, map(M2PotVal, 511.5, 1023, 0, 255));
    analogWrite(M2Pin2, 0);
  }
  else
  {
    analogWrite(M2Pin2, map(M2PotVal, 511.5, 0, 0, 255));
    analogWrite(M2Pin1, 0);
  }
  //Head servo command
//  int Servo1PotVal = analogRead(Servo1PotPin);
//  int Servo1Cmd = map(Servo1PotVal, 180, 840, 58, 90);
//  HeadServo.write(Servo1Cmd);

}

The Servo library takes over timer1, which means you can't use PWM on pins 9
or 10.

If I attach a servo to pins 10 or 11, then pin 9 stops working

PWM needs timers (one per pair of pins). Servos need timers. Which function do you really need?

There is a ServoTimer2 library that might be useful.

I wasn't aware of these timers, guess I need to do some research.

Thanks for the quick replies!

Is there a good reference to read that explains the timers? I checked the analogWrite reference and I didn't see anything about the timers.

Thanks again

The chip datasheet is definitive, a few people have some info and tutorials including me:

http://sphinx.mythic-beasts.com/~markt/ATmega-timers.html

Thanks for the link, great tutorial.

I switched to pins 5, 6, 3 and 11 for the Hbridge and pin 9 for the servo. Works great, Thanks!