串口接收处理--非中断方式

2023-05-16

最近使用的一个传感器,在上电后1s内可以读id,之后就会自动转为持续检测模式。因此在初始化时对传感器进行获取ID的操作。获取id时接收选择轮询模式

接收函数:

 int recv_cmd(uint32_t usart_periph,uint8_t *buf,uint8_t size)
{
	uint32_t rcvdelay = 50000;
	if (NULL == buf)
	{
		vDebugPrintf(printf_ERR,"{%s} buf point is null\r\n",__func__);
		return -1;
	}
	for(int i=0; i<size; i++)
	{
		while (usart_flag_get(usart_periph, USART_FLAG_RBNE) == RESET)
		{
			delay_us(1);
			if (--rcvdelay)
			{
				continue;
			}
			else 
			{
				vDebugPrintf(printf_ERR,"{%s} can not receive value\r\n",__func__);
				return -1;
			}
		}
		rcvdelay = 50000;
		buf[i] = usart_data_receive(usart_periph);
	}
	
	return 0;
}

当计数器由50000减到0时,接收寄存器RBNE还没有数据就return出来

发送函数:

 int set_cmd(uint32_t usart_periph,uint8_t index)
{
	uint8_t cmd_step[MATERIAL_LOC_CMD_MAX][MATERIAL_CMD_TOTAL_SIZE]={
		{0x55, 0xAA, 0x0D, 0x0C},/*single detect*/
		{0x55, 0xAA, 0x0C, 0x0B},/*continue detect*/
		{0x55, 0xAA, 0x0B, 0x0A},/*stop detect*/
		{0x55, 0xAA, 0xFF, 0xFF},/*reset*/
		{0x55, 0xAA, 0xEE, 0xEE}/*get id*/
	};
	
	if (index >= MATERIAL_LOC_CMD_MAX)
	{
		vDebugPrintf(printf_ERR, "%s:CMD step is too large\r\n",__func__);
		return -1;
	}
	/*set data by step*/
	uint8_t sendbuf[MATERIAL_CMD_TOTAL_SIZE]; 
	memcpy(sendbuf,&cmd_step[index][0],MATERIAL_CMD_TOTAL_SIZE);
	for (int i=0;i<sizeof(sendbuf);i++)
    {
    	while(RESET == usart_flag_get(usart_periph, USART_FLAG_TBE));
		usart_data_transmit(usart_periph, sendbuf[i]);
	}
	return 0;
}

获取id函数:

int get_version(uint32_t usart_periph)
{
	uint8_t version_info[14] = {0};
	uint8_t id[14] = {0x5A, 0x00, 0x43, 0x51, 0x2D, 0x55, 0x4C, 0x2D, 0x4D, 0x44, 0x2D, 0x30, 0x31, 0x08};
	if (0 == material_loc_set_cmd(usart_periph,4))
	{
		if (0 == material_loc_recv_cmd(usart_periph,version_info,sizeof(version_info)))
		{
			if (memcmp(id,version_info,sizeof(version_info)))
			{
				vDebugPrintf(printf_BSP,"{%s} error1 [%x %x]\r\n",__func__,version_info[2],version_info[3]);
				return -1;
			}
			return 0;
		}
		else
		{
			vDebugPrintf(printf_BSP,"{%s} error2 [%x %x]\r\n",__func__,version_info[2],version_info[3]);
			return -1;
		}
	}
	else
	{
		vDebugPrintf(printf_BSP,"{%s} error3 [%x %x]\r\n",__func__,version_info[2],version_info[3]);
		return -1;
	}
}

之后持续监测的数据使用串口空闲中断+DMA的方式去获取和解析

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

串口接收处理--非中断方式 的相关文章

随机推荐