Raspberry Pi Pico タイマ割り込みでLチカ(VSC + C言語)
CMakeLists.txtを変更
上述した通りsdioのprintfの出力先を設定する。 プロジェクト名が”my_project”の場合USB経由のprintf有効にする場合は下のように追加で記述する。
pico_enable_stdio_usb(my_project 1)
USB経由を有効にしたらUART経由は無効にする。それは下のように記述する。
pico_enable_stdio_uart(my_project 0)
CMakeLists.txtの全体は下のようになった。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cmake_minimum_required(VERSION 3.12) | |
include(pico_sdk_import.cmake) | |
project(my_project C CXX ASM) | |
set(PICO_EXAMPLES_PATH ${PROJECT_SOURCE_DIR}) | |
pico_sdk_init() | |
add_executable(my_project | |
main.c | |
) | |
target_link_libraries(my_project pico_stdlib) | |
pico_add_extra_outputs(my_project) | |
#stdioのprintfで出力する先の設定 USBをEnableにしてUARTをDisableにする。 | |
pico_enable_stdio_usb(my_project 1) | |
pico_enable_stdio_uart(my_project 0) |
ソースコード
今回はタイマ割り込み設定を2通り行った。
- add_alarm_in_ms()
- add_repeating_timer_ms()
add_alarm_in_ms() は一回だけタイマ割り込み関数を呼び出す設定を行う関数。
add_repeating_timer_ms()は繰り返しタイマ割り込み関数を呼び出す設定を行う関数。
今回はオンボードLEDを一回だけの割り込みでONして、外付けLED(GPIO15)を繰り返し関数でON/OFFを行う。
ソースコード全体は下のようになった。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "pico/stdlib.h" | |
#include "hardware/gpio.h" | |
#define ON_BORD_LED (25) | |
#define LED_1 (15) | |
/*一定周期で繰り返し割り込み*/ | |
bool repeating_timer_callback(struct repeating_timer *t){ | |
static int tick; | |
tick ^=1; | |
gpio_put(LED_1, tick); | |
return true; | |
} | |
/*add_alarmから指定時間後に割り込み*/ | |
int64_t alarm_callback(alarm_id_t id, void *user_data) { | |
static int tick; | |
tick ^=1; | |
gpio_put(ON_BORD_LED, tick); | |
return 0; | |
} | |
int main(){ | |
int timer0; | |
struct repeating_timer timer; | |
stdio_init_all(); | |
gpio_init(ON_BORD_LED); | |
gpio_init(LED_1); | |
gpio_set_dir(ON_BORD_LED, GPIO_OUT); | |
gpio_set_dir(LED_1, GPIO_OUT); | |
add_alarm_in_ms(2000, alarm_callback, NULL, false); //一度限りのタイマ割り込み関数の設定 | |
add_repeating_timer_ms(-500,repeating_timer_callback , NULL, &timer); //500msタイマ割り込み関数の設定&スタート | |
while(1){ | |
if(timer0++>999){ | |
timer0=0; | |
} | |
printf("Timer:%d\n",timer0); | |
sleep_ms(100); | |
} | |
return 0; | |
} |
動作
ブレッドボードのタクトスイッチはリセットスイッチで3V3_ENに接続されていてONするとGNDに電圧を落とす。これを付けると書込みのときラクで、これがないとUSBを毎回挿抜しないといけない。