Raspberry Pi Pico + ローテーションサーボモータSG-90HV + C言語
はじめに
表題の通り、Raspberry Pi PicoとC言語でローテーションサーボモータSG-90HVを回してみました。
PWM周波数とパルス幅の指定で回せられればよいのですが、それができないのと、デューティ比の計算にシステムクロックが係ってきているのが面倒です。
ますはCソースコードです。
pwm01.c
#include "pico/stdlib.h" #include "hardware/pwm.h" int main() { /// \tag::setup_pwm[] // Tell GPIO 0 and 1 they are allocated to the PWM gpio_set_function(0, GPIO_FUNC_PWM); gpio_set_function(1, GPIO_FUNC_PWM); // Find out which PWM slice is connected to GPIO 0 (it's slice 0) uint slice_num = pwm_gpio_to_slice_num(0); // Set period of 0.02s pwm_set_wrap(slice_num, 24999); pwm_set_clkdiv(slice_num, 100.0); // Set channel A Duty pwm_set_chan_level(slice_num, PWM_CHAN_A, 2315); // Set initial B Duty pwm_set_chan_level(slice_num, PWM_CHAN_B, 1330); // Set the PWM running pwm_set_enabled(slice_num, true); /// \end::setup_pwm[] //Start ESC Calibration sleep_ms(2000); pwm_set_chan_level(slice_num, PWM_CHAN_A, 1330); sleep_ms(5000); //End Start ESC Calibration while(true){ // Duty cycle = (1500 us / 20000 us) * (wrap + 1) = 0.075 * 25000 = 1875 pwm_set_chan_level(slice_num, PWM_CHAN_A, 1875); sleep_ms(2000); // Duty cycle = (2000 us / 20000 us) * (wrap + 1) = 0.1 * 25000 = 2500 pwm_set_chan_level(slice_num, PWM_CHAN_A, 2500); sleep_ms(2000); // Duty cycle = (1500 us / 20000 us) * (wrap + 1) = 0.075 * 25000 = 1875 pwm_set_chan_level(slice_num, PWM_CHAN_A, 1875); sleep_ms(2000); // Duty cycle = (1000 us / 20000 us) * (wrap + 1) = 0.05 * 25000 = 1250 pwm_set_chan_level(slice_num, PWM_CHAN_A, 1250); sleep_ms(2000); } }
CMakeLists.txt
続いて、CMakeLists.txtです。
#Set the mimum required version of CMake cmake_minimum_required(VERSION 3.12) #Pull in SDK (must be before project) include(pico_sdk_import.cmake) #Set the project name, the programming language project(pwm01 C CXX ASM) set(CMAKE_C_STANDARD 11) set(CMAKE_CXX_STANDARD 17) #Initialize the SDK pico_sdk_init() #Add an executable target to be build from the source files add_executable(pwm01 pwm01.c) #Pull in our pico_stdlib which aggregates commonly used features target_link_libraries(pwm01 pico_stdlib) target_link_libraries(pwm01 hardware_pwm) #Create map/bin/hex/uf2 file etc. pico_add_extra_outputs(pwm01)
ランキングに参加しています。下記バナーをクリックしていただけるとありがたいです。