小试一下
串口的功能网上有很多,但是处理串口的数据需要一些小手段,但是str的函数有点才长,不适用长的数据接收,所以给310搞一个接收数据的轻量级API的小玩意。
开发环境
- Keil-MDK 5.34
- Windows10
- 固件库-GD32F3x0_Firmware_Library_V2.2.0
新建工程就不赘述,看这个 here
启动串口
void uart_init(void)
{
//使能时钟
rcu_periph_clock_enable(RCU_GPIOA);
rcu_periph_clock_enable(RCU_USART0);
//Tx PA9 复用推挽输出
gpio_mode_set(GPIOA,GPIO_MODE_AF,GPIO_PUPD_PULLUP,GPIO_PIN_9);
gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);
//Rx PA10
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);
nvic_irq_enable(USART0_IRQn,0,0);
gpio_af_set(GPIOA,GPIO_AF_1,GPIO_PIN_9|GPIO_PIN_10);
/*USART 设置*/
usart_deinit(USART0);
usart_baudrate_set(USART0,115200);
usart_word_length_set(USART0,USART_WL_8BIT);
usart_stop_bit_set(USART0,USART_STB_1BIT);
usart_parity_config(USART0,USART_PM_NONE);
usart_hardware_flow_rts_config(USART0,USART_RTS_DISABLE);
usart_hardware_flow_cts_config(USART0,USART_CTS_DISABLE);
usart_receive_config(USART0,USART_RECEIVE_ENABLE);
usart_transmit_config(USART0,USART_TRANSMIT_ENABLE);
usart_enable(USART0);
usart_interrupt_enable(USART0,USART_INT_RBNE);
usart_interrupt_enable(USART0, USART_INT_IDLE); /* 使能USART0空闲中断 */
}
//串口中断配置
uint16_t t=0;
void USART0_IRQHandler(void)
{
if(RESET!=usart_interrupt_flag_get(USART0,USART_INT_FLAG_RBNE))
{
gd_led_toggle();
t=usart_data_receive(USART0);//接收数据
usart_data_transmit(USART0,USART_RX[t]);
usart_interrupt_disable(USART0,USART_INT_RBNE);
usart_data_transmit(USART0,t);
}else if(RESET!=usart_interrupt_flag_get(USART0,USART_INT_FLAG_IDLE))
{
usart_interrupt_disable(USART0,USART_INT_IDLE);
}
}
数据处理API
struct _Chang_Num
{
char *Source;
char Sign[8];
float NUM[8];
char flag;
};
char Data_Chang_NUM (struct _Chang_Num *Item)
{
char Data_Array[12] = {0}; //数字的str数
char str[36]; //装source数据到这个缓存区,这个缓存区是要变的
char Data;
char n,m = 0;
char i,flag = 1; //i是当前找的是 第几个 Sign
char Find_Time = strlen(Item->Sign); //要找多少个
char Length = strlen(Item->Source); //源的长度
strcpy(str,Item->Source);
if(Length > 36)
Length = 36;
for (i = 0; i < Find_Time; i++)
{
flag = 0;
for(n = 0;n < Length;n++)
{
Data = str[n];
if(str[n] == Item->Sign[i]) //找到标志
{
str[n] = 0;
flag = 1; //开始识别str
m = 0;
}
if(flag)
{
if((str[n] <= '9' && str[n] >= '0') || str[n] == '.' || str[n] == '-')
{
Data_Array[m] = str[n]; //把数字相关str的装起来
m++; //m是数字在str的长度
}
else
{
if(m > 0) //数字部分结束
{
if(Data_Array[m-1] == '.' || Data_Array[m-1] == '-') //不让最后一位为 '.' and '-'
Data_Array[m-1] = '\0';
else
Data_Array[m] = '\0';
break;
}
}
}
}
Item->NUM[i] = atof(Data_Array);
// Data_Replace ("123",Data_Array,0,sizeof(Data_Array));
}
return Item->flag;
}
配置好你想要的参数在结构体中,然后将串口的缓冲区放入这个函数即可。
将printf函数映射到串口,看这里here
struct _Chang_Num Item_n = {
.Source = "a:3.14......,b:3322..,c:-9.0..-",
.Sign = {':',':',':'},
};
int main (void)
{
printf("sign :%s",Item_n.Sign);
Data_Chang_NUM (&Item_n);
for (char i = 0; i < 3; i++)
{
printf("num %d :%.2f \n",i,Item_n.NUM[i]);
}
while(1);
}
API效果