本文移植LetterShell,通过串口输入命令,与开发板交互。
Letter shell的项目地址:https://github.com/NevermindZZT/letter-shell
最新的版本是3.1.2,也正是本文移植的版本。
在移植之前首先要保证串口收发正常,本文使用串口轮询发送和中断接收。
1、串口相关代码
- void UartInit(void)
- {
- gpio_init_type gpio_init_struct;
- /* enable the uart and gpio clock */
- crm_periph_clock_enable(CRM_USART2_PERIPH_CLOCK, TRUE);
- crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE);
- gpio_default_para_init(&gpio_init_struct);
- /* configure the usart2 tx pin */
- gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
- gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
- gpio_init_struct.gpio_mode = GPIO_MODE_MUX;
- gpio_init_struct.gpio_pins = GPIO_PINS_2;
- gpio_init_struct.gpio_pull = GPIO_PULL_NONE;
- gpio_init(GPIOA, &gpio_init_struct);
-
- /* configure the usart2 rx pin */
- gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
- gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
- gpio_init_struct.gpio_mode = GPIO_MODE_INPUT;
- gpio_init_struct.gpio_pins = GPIO_PINS_3;
- gpio_init_struct.gpio_pull = GPIO_PULL_UP;
- gpio_init(GPIOA, &gpio_init_struct);
-
- /* configure uart param */
- usart_init(USART2, 115200, USART_DATA_8BITS, USART_STOP_1_BIT);
-
- usart_transmitter_enable(USART2, TRUE);
- usart_receiver_enable(USART2, TRUE);
-
- nvic_irq_enable(USART2_IRQn, 0, 0);
- usart_interrupt_enable(USART2, USART_RDBF_INT, TRUE);
- usart_enable(USART2, TRUE);
- }
- /* retarget the C library printf function to the USART */
- int fputc(int ch, FILE *f)
- {
- while(usart_flag_get(USART2, USART_TDC_FLAG) == RESET);
- usart_data_transmit(USART2, (uint8_t) ch);
-
- return ch;
- }
2、Letter shell接口
主要是shell_port.c文件中的userShellWrite和userShellRead,本文使用串口中断,可不比实现userShellRead。
2.1、userShellWrite
- /**
- * [url=home.php?mod=space&uid=247401]@brief[/url] 用户shell写
- *
- * @param data 数据
- * @param len 数据长度
- *
- * [url=home.php?mod=space&uid=266161]@return[/url] short 实际写入的数据长度
- */
- short userShellWrite(char *data, unsigned short len)
- {
- for(uint16_t i=0;i<len;i++)
- {
- while(usart_flag_get(USART2, USART_TDC_FLAG) == RESET);
- usart_data_transmit(USART2, data[i]);
- }
-
- return len;
- }
2.2、在串口中断接收中处理shell接收
- void USART2_IRQHandler(void)
- {
- uint8_t ch=0;
- if(usart_flag_get(USART2, USART_RDBF_FLAG) != RESET)
- {
- /* read one byte from the receive data register */
- ch = usart_data_receive(USART2);
- shellHandler(&shell, ch);
- }
- }
2.3、shell注册读写函数
- void userShellInit(void)
- {
- shell.write = userShellWrite;
- shellInit(&shell, shellBuffer, 512);
- }
2.4、定义shell对象和缓冲区
- Shell shell;
- char shellBuffer[512];
完成以上后,调用void userShellInit(void)函数,初始化即可,正常运行shell。
3、shell配置
shell_cfg.h文件中,主要是对shell进行配置的,可以配置用户名、密码等参数,可根据实际需要裁剪。
4、新增命令
本文新增了reboot命令,来进行测试
- /* 系统重启 */
- void reboot(int argc, char *agrv[])
- {
- NVIC_SystemReset();
- }
- SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_FUNC), reboot, reboot, reboot);
5、现象
本文使用CRT串口终端,
|