RP2040의 PWM를 이용해 DC 모터 속도를 제어하는 방법을 다룹니다. H-브리지 드라이버(L9110S, TB6612FNG 등)와 결합해 방향 제어도 가능합니다.
하드웨어 구성:
- Pico 보드, 5V DC 모터, 모터 드라이버(TB6612FNG 예), 외부 전원(모터용)
- PWM 핀 예: GP14 (PWM 슬라이스 7 채널 A)
배선 예시(TB6612FNG):
- PWMA -> GP14(PWM), AIN1->GP16, AIN2->GP17, VM->모터전원, GND 공통
예제 코드 (C, Pico SDK):
#include "pico/stdlib.h"
#include "hardware/pwm.h"
#define PWM_PIN 14
#define IN1 16
#define IN2 17
void motor_dir(bool forward){
gpio_put(IN1, forward);
gpio_put(IN2, !forward);
}
int main(){
gpio_init(IN1); gpio_set_dir(IN1, GPIO_OUT);
gpio_init(IN2); gpio_set_dir(IN2, GPIO_OUT);
gpio_set_function(PWM_PIN, GPIO_FUNC_PWM);
uint slice = pwm_gpio_to_slice_num(PWM_PIN);
pwm_config cfg = pwm_get_default_config();
pwm_config_set_clkdiv(&cfg, 4.0f); // PWM 주파수 설정용
pwm_init(slice, &cfg, true);
while(true){
motor_dir(true);
for(int duty=0; duty<=255; duty++){
pwm_set_gpio_level(PWM_PIN, duty*257); // 16bit 스케일
sleep_ms(5);
}
sleep_ms(500);
motor_dir(false);
for(int duty=255; duty>=0; duty--){
pwm_set_gpio_level(PWM_PIN, duty*257);
sleep_ms(5);
}
sleep_ms(500);
}
}
설명: pwm_set_gpio_level은 16비트 레벨을 받으므로 8비트 듀티를 257배로 확장해 사용했습니다. 외부 전원과 GND 공통, 드라이버 최대 전류를 반드시 확인하세요.