Announcements

# PWM-SERVOMOTOR

## PWM-SERVOMOTOR

Level 2
Level 2
Hola Comunidad! Me podrían brindar datos de como programar un servomotor MG90 para PSoC6 CY8CPROTO-062-4343W, por HAL. Uso Eclipse IDE Modustoolbox 3.1
4 Replies

## Re: PWM-SERVOMOTOR

Moderator
Moderator

Hello @Ignacio ,

We can use TCPWM to create a pulse for the servo.
Refer to the datasheet of the servo

PWM signal produced should have a frequency of 50Hz that is the PWM period should be 20ms.
When the on-time is 1ms the motor will be in 0° and when 1.5ms the motor will be 90°, similarly when it is 2ms it will be 180°.

We can use HAL to produce the PWM signal by initialize the PWM:

``````cy_rslt_t result;
cyhal_pwm_t pwm_obj;
// Initialize PWM on the supplied pin and assign a new clock
result = cyhal_pwm_init(&pwm_obj, P6_0, NULL);
// Set a duty cycle of 0.05% ( 1 degree for servo)and frequency of 50Hz
result = cyhal_pwm_set_duty_cycle(&pwm_obj, 0.05f, 50);
// Start the PWM output
result = cyhal_pwm_start(&pwm_obj);
``````

And by calculate the duty cycle based on angle of servo,

``````// frequency is 50hz
// 0 degree = 1ms, 90 degree = 1.5ms, and 180 degree = 2ms
float angle2Duty(float angle)
{
float tm = 1000*( 1/50.f ); // in ms
printf("TM %f \n", tm);
float duty = 10.f;
if( angle <= 0 )
{
//	t_on should be 1ms from 20ms
duty = 100*( 1/tm );
}else if ( angle >= 180 )
{
//	t_on should be 2ms from 20ms
duty = 100*( 2/tm );
}
else
{
duty = 2*( angle/180 );
duty /= tm;
duty *= 100.f;
}
return duty;
}``````

We can call it in the loop, for example:

``````float angle=0;
for (;;)
{
cyhal_pwm_set_duty_cycle(&pwm_obj, angle2Duty(angle), 50);
cyhal_system_delay_ms(500);
angle+=5;
if(angle>=180)
angle = 0;
}``````

Warm regards
Andri

## Re: PWM-SERVOMOTOR

Level 2
Level 2

Hola  @ADSW  ! muchísimas gracias por tu ayuda y tu tiempo para responder. Me podrías brindar una ayuda, si lo quiero adaptar a un servo de 360°? cual seria la modificación, sabes que lo estuve intentando pero el eje del servo no m gira los 360°. El servo es un MG90S, con giro de 360°.

## Re: PWM-SERVOMOTOR

Moderator
Moderator

Hello @Ignacio ,

Actually the servo 360° will rotate continuously. We only can control the speed and direction.
The method to control the 360 servo almost same with the 180° servo,
The difference is the duty cycle to make the 180° servo move to 90°, if applied to the 180° servo it will stop.
And other duty cycle will change the direction and speed of servo.

Warm regards
Andri

## Re: PWM-SERVOMOTOR

Moderator
Moderator

Hi,

Thread was locked due to inactivity for long time, you can continue the discussion on the topic by opening a new thread with reference to the locked one.
The continuous discussion in an inactive thread may mostly be unattended by community users.

Thanks and Regards,