All projects
05Live
Servo Sweep
Position a servo by angle using hardware PWM.
PWM
01
What you learn
Generating real hardware PWM and controlling angle via pulse width. Within a 20 ms period, the pulse width sets the angle.
02
Parts you need
03
Wiring
| Module | Board | Note |
|---|---|---|
| GND (kahverengi) | GND | — |
| VCC (kırmızı) | VBUS (5V) | Servo power; not the signal. |
| Signal (turuncu) | PB6 | PWM output (M0PWM0) |
04
Code
main.c
1#include <stdint.h>2#include <stdbool.h>3#include "inc/hw_memmap.h"4#include "driverlib/sysctl.h"5#include "driverlib/gpio.h"6#include "driverlib/pin_map.h"7#include "driverlib/pwm.h"8 9#define PWM_PERIOD 15625u // 20 ms at 781.25 kHz -> 50 Hz10#define PULSE_0DEG 781u // ~1.0 ms11#define PULSE_180DEG 1562u // ~2.0 ms12 13static void delayMs(uint32_t ms) { SysCtlDelay((SysCtlClockGet() / 3000) * ms); }14 15// Set servo angle 0..180 -> map to pulse width counts16static void servoWrite(uint32_t deg) {17 if (deg > 180) deg = 180;18 uint32_t pulse = PULSE_0DEG + ((PULSE_180DEG - PULSE_0DEG) * deg) / 180;19 PWMPulseWidthSet(PWM0_BASE, PWM_OUT_0, pulse);20}21 22int main(void) {23 SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL |24 SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);25 SysCtlPWMClockSet(SYSCTL_PWMDIV_64); // PWM clock = sysclk / 6426 27 SysCtlPeripheralEnable(SYSCTL_PERIPH_PWM0);28 SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);29 while (!SysCtlPeripheralReady(SYSCTL_PERIPH_PWM0)) {}30 while (!SysCtlPeripheralReady(SYSCTL_PERIPH_GPIOB)) {}31 32 GPIOPinConfigure(GPIO_PB6_M0PWM0); // route PB6 to PWM33 GPIOPinTypePWM(GPIO_PORTB_BASE, GPIO_PIN_6);34 35 PWMGenConfigure(PWM0_BASE, PWM_GEN_0,36 PWM_GEN_MODE_DOWN | PWM_GEN_MODE_NO_SYNC);37 PWMGenPeriodSet(PWM0_BASE, PWM_GEN_0, PWM_PERIOD);38 39 servoWrite(90); // start centered40 PWMOutputState(PWM0_BASE, PWM_OUT_0_BIT, true);41 PWMGenEnable(PWM0_BASE, PWM_GEN_0);42 43 while (1) {44 uint32_t d;45 for (d = 0; d <= 180; d += 2) { servoWrite(d); delayMs(15); } // 0 -> 18046 delayMs(300);47 for (d = 180; d > 0; d -= 2) { servoWrite(d); delayMs(15); } // 180 -> 048 delayMs(300);49 }50}05
Output
The simulation below runs in your browser — it mimics the real board.
- angle
- 90°
- pulse
- 1.50 ms
- period
- 20 ms (50 Hz)