How to program a Servo motor in KL25Z

Showing results for 
Search instead for 
Did you mean: 

How to program a Servo motor in KL25Z

Contributor I

I must program a Servomotor in freescale, I have this program but the servo can´t power on.
I need to make the servo go from 0° to 180°

Please help me!
Could you please explain me each part of the correct form to program a servo motor.

#include "MKL25Z4.h"

int main (void){
SIM->SCGC5 |= 0x1000; /* enable clock to Port D */

PORTD->PCR[2] = 0x0400; /* PTD1 used by TPM0 PIN DEL PRIMER SERVOMOTOR */
SIM->SCGC6 |= 0x01000000; /* enable clock to TPM0 */
SIM->SOPT2 |= 0x01000000; /* use MCGFLLCLK as timer counter clock */

TPM0->SC = 0; /* disable timer */
TPM0->CONTROLS[3].CnSC = 0x20 | 0x08; /* edge-aligned, pulse high */
TPM0->MOD = 43702; /* Set up modulo register for 60 kHz */
TPM0->CONTROLS[3].CnV = 437; /* Set up channel value for 1% dutycycle */
TPM0->SC = 0x0C; /* enable TPM0 with prescaler /16 */

void delayms(int n)
{int i;
int j;
for(i=0; i < n; i++)
for (j=0; j < 7000; j++){} }

0 Kudos
2 Replies

NXP Employee
NXP Employee

Hi Gerardo,

in addition to the reply from Robin, you might have a read at Tutorial: Arduino Motor/Stepper/Servo Shield – Part 1: Servos | MCU on Eclipse .

I hope this helps,


0 Kudos

NXP TechSupport
NXP TechSupport

Hi Gerardo,

Sorry for the late reply!

Please read 'Servo control interface in detail' and  'Introduction to Servomotor Programming' first.
The typical pulse period is around 20 ms, which corresponds to a frequency of 50 Hz. (But you have configure frequency of 60kHz which may too high.)

The pulse width is generally the most important part of the interface, and that is what we intentionally vary to change the command to the servo. The general idea is simple: a pulse width of 1.5 ms is what we consider “neutral”; increasing the pulse width will make the servo go one way, and decreasing the pulse width will make the servo go the other way.(But you have configure 1% dutycycle which may too small.)


I am not sure what type Servo Motor are you using. For different Servo Motor, the Pulse Width of Center Position maybe different.

Best Regards,



Note: If this post answers your question, please click the Correct Answer button. Thank you!

0 Kudos