Low memory code just to run one servo

Hi All,

[didn't think this was the motor forum as it's not high power/current/voltage - mods please move if it's better placed there.]

Deconstructed the Servo Library to run a single servo off a Nano.

The code below runs a single TowerPro Servo with minimal memory use. (812 bytes of flash memory as opposed to 2400-ish). Servo was a Chinese clone of a TowerPro 9G.

Just putting this up for reference.

Regards,

A

//datasheet http://www.ee.ic.ac.uk/pcheung/teaching/DE1_EE/stores/sg90_datasheet.pdf

#define servoPin 12  //Digital pin that the Servo Control Signal Wire is connected to

int servo_pos;

void setup() {
pinMode(servoPin,OUTPUT);
digitalWrite(servoPin,HIGH);delayMicroseconds(1485);//1485 microseconds = 90*
}

void loop() {
servo_pos=45;//<-- arbitrary position - set this with code
servo_pos=constrain(servo_pos,0,180); // constrain to semicircle
servo_pos=map(servo_pos,0,180,500,2470); //500, 2470 are delays in microsec corresponding to 0* & 180*
digitalWrite(servoPin,HIGH);delayMicroseconds(servo_pos); //send high pulse corresponding to servo position
digitalWrite(servoPin,LOW);delayMicroseconds(20000-servo_pos); //balance of 20000 microseconds = 50Hz
}
//I was going to use millis command to set cycles, but the above worked acceptably

Think about trying it a little differently..

unsigned int endTime;

setup() {

  doSetupThings();
  ...
  ...
 endTime = millis();
}


void loop(void) {
  
  if (millis()>endTime) {                       // If it's time for a pulse..
     servo_pos=constrain(servo_pos,0,180);      // constrain to semicircle
     servo_pos=map(servo_pos,0,180,500,2470);   //500, 2470 are delays in ms
     digitalWrite(servoPin,HIGH);               //send high pulse corresponding to servo position
     delayMicroseconds(servo_pos);              // Take a smoko..
     digitalWrite(servoPin,LOW);                // Pulse complete.
     endTime = millis()+18;                     // Set up for next pulse.
  }
}

now you have the lion's share of your time left over to see what the user wants. Possible check the serial input, look at some sensors..

-jim lee

I like your style, Jim.

Thanks,

A