|
【common.c】 #include <gd32f4xx.h> #include <stdio.h> #include <stdlib.h> #include "common.h"
#ifdef __MICROLIB #warning "Please do NOT use MicroLib" #endif
#pragma import(__use_no_semihosting) // 禁用半主机模式 (不然调用printf就会进HardFault)
FILE __stdout = {1}; FILE __stderr = {2}; static uint32_t sys_ticks;
/* main函数返回时执行的函数 */ void _sys_exit(int returncode) { printf("Exited! returncode=%d\n", returncode); while (1); }
void _ttywrch(int ch) { if (ch == '\n') { while (usart_flag_get(USART0, USART_FLAG_TBE) == RESET); // 等待前一字符发送完毕 usart_data_transmit(USART0, '\r'); } while (usart_flag_get(USART0, USART_FLAG_TBE) == RESET); usart_data_transmit(USART0, ch); }
/* 等待串口发送端空闲 */ // LWIP_ASSERT会调用此函数 int fflush(FILE *stream) { switch (stream->handle) { case 1: case 2: while (usart_flag_get(USART0, USART_FLAG_TC) == RESET); return 0; default: return -1; } }
/* printf和perror重定向到串口 */ int fputc(int ch, FILE *fp) { if (fp->handle == 1 || fp->handle == 2) { _ttywrch(ch); return ch; } return EOF; }
/* 延时n毫秒 (不精确) */ // 实际延迟的时间t: nms<t<=nms+1 void delay(uint16_t nms) { uint32_t diff, start; start = sys_now(); do { diff = sys_now() - start; } while (diff <= nms); }
/* 显示数据内容 */ void dump_data(const void *data, int len) { const uint8_t *p = data; while (len--) printf("%02X", *p++); printf("\n"); }
/* 获取系统时间毫秒数 (lwip协议栈要求实现的函数) */ // 该函数必须保证: 除非定时器溢出, 否则后获取的时间必须大于先获取的时间 uint32_t sys_now(void) { return sys_ticks; }
/* 初始化系统时间毫秒计数器 */ void sys_now_init(void) { SysTick_Config(SystemCoreClock / 1000); }
/* 初始化串口 */ void usart_init(int baud_rate) { rcu_periph_clock_enable(RCU_GPIOA); rcu_periph_clock_enable(RCU_USART0); // 串口发送引脚PA9设为复用推挽输出, 串口接收引脚PA10保持默认的浮空输入 gpio_af_set(GPIOA, GPIO_AF_7, GPIO_PIN_9); gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_9); gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9); gpio_af_set(GPIOA, GPIO_AF_7, GPIO_PIN_10); gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_10); gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_10); usart_baudrate_set(USART0, baud_rate); usart_stop_bit_set(USART0, USART_STB_1BIT); usart_word_length_set(USART0, USART_WL_8BIT); usart_parity_config(USART0, USART_PM_NONE); usart_transmit_config(USART0, USART_TRANSMIT_ENABLE); usart_receive_config(USART0, USART_RECEIVE_ENABLE); usart_enable(USART0); }
void HardFault_Handler(void) { printf("Hard Error!\n"); while (1); }
void SysTick_Handler(void) { sys_ticks++; }
【common.h】 #ifndef _COMMON_H #define _COMMON_H
struct __FILE { int handle; };
void delay(uint16_t nms); void dump_data(const void *data, int len); uint32_t sys_now(void); void sys_now_init(void); void usart_init(int baud_rate);
#endif
|