前回まででUSBCDC(コミュニケーションデバイスクラス)でVCP(VirtualCOMPort)の動作は確認できたので今回はこれにMicroShellを使える状態していく作業になります。
CDCのやり方はこの記事みてください。
gsmcustomeffects.hatenablog.com
やることは
- 1文字送受信APIの準備
- 受信バッファサイズの設定
受信バッファは1文字づつ処理してるので初期状態でも動くには動くが無駄
APIの準備
この3つを作成する必要があります。
送信側のAPIの準備
送信側はCDC_Transmit_FSというものがありますので簡単です。
実装の一例を示します。
void cdc_put(uint8_t c){ char buf[1]; buf[0] = c; CDC_Transmit_FS((uint8_t*)buf,1); HAL_Delay(1); }
void cdc_puts(char *str){ while(*str){ cdc_put(*str++); } }
受信側のAPIの準備
こちらが結構くせものというかブロッキング型じゃないのでMicroShellが要求するブロッキング型ぽく魅せる必要があります。
CDCレシーブの仕組みですが文字を受信するとコールバックされる関数があります。
CDC_Receive_FSというのがそれです。
そこで今回はそいつの中でフラグを操作してあげて文字が来ていることをcdc_getcに知らせてあげるという流れを取っていきます。
ちなみにこの方法は半ば回避策なのでもっといい方法がありそう。(レジスタに張り付いてそこを参照するとか)
volatile int flag_cdc_rx;
みたいな変数を用意しました。volatileなのは最適化で消されないようにするためです。
static int8_t CDC_Receive_FS (uint8_t* Buf, uint32_t *Len) { /* USER CODE BEGIN 6 */ flag_cdc_rx = 1; USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]); USBD_CDC_ReceivePacket(&hUsbDeviceFS); return (USBD_OK); /* USER CODE END 6 */ }
そしてこのようにcdc_getcを定義しました。
何もないときはNULL文字を返すようにしてだましだまし使う感じこれで無限にこの関数がポーリングされてもフラグが立たない限り影響がないはず。
uint8_t cdc_getc(){ if (flag_cdc_rx==1) { flag_cdc_rx=0; return UserRxBufferFS[0]; } else return '\0'; }
これで3つのAPIがそろったのでusbd_cdc_if.cの中に適当に配置してください
次にMain文で以下を追加
extern void cdc_puts(char *str); extern uint8_t cdc_getc(); extern void cdc_put(uint8_t c);
static void utx(char c) { cdc_put(c); } static char urx(void) { return cdc_getc(); } static void action_hook(MSCORE_ACTION action) { }
これでだいたい機能はそろったのでこの記事を参考にほかの部分を書いていってください
gsmcustomeffects.hatenablog.com
まとめ
USBCDC機能を使ってシェルが動いた。
UARTをつぶすことなくデバッグシステムを構成可能になった。
当方の作業環境はAliexpressのSTM32F103RBT6基板とJLINK。
基板の購入先は此方
ja.aliexpress.com
ちなみにこの作業はリアルテック先輩に付き合ってもらいました。この場をお借りしてお礼を言わせていただきます。
https://twitter.com/realteck_KYtwitter.com
最後におまけでMain.cを乗っけときます
Main.c
/** ****************************************************************************** * File Name : main.c * Description : Main program body ****************************************************************************** * This notice applies to any and all portions of this file * that are not between comment pairs USER CODE BEGIN and * USER CODE END. Other portions of this file, whether * inserted by the user or by software development tools * are owned by their respective copyright owners. * * Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f1xx_hal.h" #include "usb_device.h" /* USER CODE BEGIN Includes */ #include "lib/core/microshell.h" #include "lib/core/msconf.h" #include "lib/util/mscmd.h" #include"usbd_cdc_if.h" /* USER CODE END Includes */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); /* USER CODE BEGIN PFP */ /* Private function prototypes -----------------------------------------------*/ extern void cdc_puts(char *str); extern uint8_t cdc_getc(); extern void cdc_put(uint8_t c); /* USER CODE END PFP */ /* USER CODE BEGIN 0 */ typedef struct { void (*puts)(char *str); } USER_OBJECT; static MSCMD_USER_RESULT usrcmd_system(MSOPT *msopt, MSCMD_USER_OBJECT usrobj); static MSCMD_USER_RESULT usrcmd_config(MSOPT *msopt, MSCMD_USER_OBJECT usrobj); static MSCMD_USER_RESULT usrcmd_help(MSOPT *msopt, MSCMD_USER_OBJECT usrobj); static MSCMD_USER_RESULT usrcmd_led_toggle(MSOPT *msopt, MSCMD_USER_OBJECT usrobj); static MSCMD_COMMAND_TABLE table[] = { { "system", usrcmd_system }, { "config", usrcmd_config }, { "help", usrcmd_help }, { "?", usrcmd_help }, { "t_led",usrcmd_led_toggle}, }; static void utx(char c) { cdc_put(c); } static char urx(void) { return cdc_getc(); } static void action_hook(MSCORE_ACTION action) { } /* USER CODE END 0 */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration----------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_USB_DEVICE_Init(); /* USER CODE BEGIN 2 */ char buf[MSCONF_MAX_INPUT_LENGTH]; MICROSHELL ms; MSCMD mscmd; USER_OBJECT usrobj = { .puts = cdc_puts, }; microshell_init(&ms, utx, urx, action_hook); mscmd_init(&mscmd, table, sizeof(table) / sizeof(table[0]), &usrobj); HAL_Delay(500); cdc_puts("CDC Shell System Sample!\r\n"); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ MSCMD_USER_RESULT r; cdc_puts("shell>"); //HAL_Delay(50); microshell_getline(&ms, buf, sizeof(buf)); mscmd_execute(&mscmd, buf, &r); } /* USER CODE END 3 */ } /** System Clock Configuration */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct; RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_PeriphCLKInitTypeDef PeriphClkInit; /**Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /**Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /**Configure the Systick interrupt time */ HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); /**Configure the Systick */ HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); /* SysTick_IRQn interrupt configuration */ HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); } /** Configure pins as * Analog * Input * Output * EVENT_OUT * EXTI */ static void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_RESET); /*Configure GPIO pin : PC13 */ GPIO_InitStruct.Pin = GPIO_PIN_13; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); } /* USER CODE BEGIN 4 */ static MSCMD_USER_RESULT usrcmd_system(MSOPT *msopt, MSCMD_USER_OBJECT usrobj) { char buf[MSCONF_MAX_INPUT_LENGTH]; int argc; int i; cdc_puts("[SYSTEM]\r\n"); msopt_get_argc(msopt, &argc); for (i = 0; i < argc; i++) { msopt_get_argv(msopt, i, buf, sizeof(buf)); cdc_puts(" '"); cdc_puts(buf); cdc_puts("'\r\n"); } return 0; } static MSCMD_USER_RESULT usrcmd_config(MSOPT *msopt, MSCMD_USER_OBJECT usrobj) { char buf[MSCONF_MAX_INPUT_LENGTH]; int argc; int i; cdc_puts("[CONFIG]\r\n"); msopt_get_argc(msopt, &argc); for (i = 0; i < argc; i++) { msopt_get_argv(msopt, i, buf, sizeof(buf)); cdc_puts(" '"); cdc_puts(buf); cdc_puts("'\r\n"); } return 0; } static MSCMD_USER_RESULT usrcmd_help(MSOPT *msopt, MSCMD_USER_OBJECT usrobj) { USER_OBJECT *uo = (USER_OBJECT *)usrobj; uo->puts( "system : system command\r\n" "config : config command\r\n" "help : help command\r\n" "t_led : toggle PA5\r\n" ); return 0; } static MSCMD_USER_RESULT usrcmd_led_toggle(MSOPT *msopt, MSCMD_USER_OBJECT usrobj) { USER_OBJECT *uo = (USER_OBJECT *)usrobj; uo->puts( "LED TOGGLE COMMAND\r\n" ); HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_13); return 0; } /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @param None * @retval None */ void _Error_Handler(char * file, int line) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ while(1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/