Servos stop working after this code is uploaded to Arduino

It seems like all my servos start to malfunction after I upload this code to my Arduino Mega. I am still relatively new the Arduino platform. Before I try this code, I tried the example provided by IDE and that works.

The servo is supposed to rotate according to a value that is based on an output of a sensor, Myoware muscle sensor.

#include <Servo.h>

int pinNumber = A0;
int servoAttachAddend = 2;

const int NUMBEROFSERVOS = 2;

float maxDegrees = 180;
float maxSensorValue = 1023;
float sensorValue;

float sensorRatio;
float sensorAngle;

Servo servosToUse[NUMBEROFSERVOS];

void setup()
{ 
  Serial.begin(9600);
  sensorRatio = maxDegrees / maxSensorValue;
  sensorValue = analogRead(pinNumber);

  int currentServoAddend;

  for (int currentServo = 0; currentServo < NUMBEROFSERVOS; currentServo++)
  {
    currentServoAddend = currentServo + servoAttachAddend;
    servosToUse[currentServo].attach(currentServoAddend);

  }
}

void loop()
{
  sensorValue = analogRead(pinNumber);

  sensorAngle = sensorValue * sensorRatio;
  
  MotorController(servosToUse,
                  sensorAngle,
                  100);
}
void MotorController(Servo servosToUse[], float angleToUse, float delayTime)
{
  for (int currentAngle = 0; currentAngle <= angleToUse; currentAngle++)
  {
    for (int currentServo = 0; currentServo < NUMBEROFSERVOS; currentServo++)
    {
        servosToUse[currentServo].write(currentAngle);
       
        delay(delayTime);
    }
  }
}

Does this cause each servo to do a rotation?

The delay is Just for testing and after each write to a servo the servo needs to be given time to get there.

What does "start to malfunction" mean? Do the servos do anything? If so what?

Put some Serial.prints in to see what actual values you are getting for the important variables immediately before the write e.g. currentServo and currentAngle. If they're not what you expect you have something to work with. If they are what you expect then there's likely to be a problem with the wiring.

Steve

I doubt this is what you mean int pinNumber = A0; This code should not even compile. A0 is not an int. 0xA0 is, but not a valid pin number, I don't think, being equal to 160 decimal.

Run this code on a Mega.

int pinNumber = A0;

void setup()
{
    Serial.begin(115200);
    Serial.print("pinNumber = ");
    Serial.println(pinNumber);
}

void loop()
{    
}

You will find that pinNumber will equal 54. A0 is defined as pin 54, an analog input pin in the pins_arduino.h for the Mega.