//柔性数组
typedef struct _SoftArray
{
int len;
char array[];
} SoftArray;
void TTL_CAN_SetBaudrate(uint32_t baudrate){ //baudrate的取值范围是4800~921600
int i = 0;
SoftArray BaudrateBITS = {0};
char TTL_CAN_AT_Instruct[] = "AT+AT\r\n"; //AT模式
char TTL_CAN_CG_Instruct[] = "AT+CG\r\n"; //CG模式即配置模式
// char TTL_CAN_USART_PARAM_Instruct[] = "AT+USART_PARAM=921600,0,0,0\r\n"; //配置TTL_CAN串口3的波特率为参数baudrate,0:8个数据位,0:1个停止位,0:没有校验位
char USART_PARAM_Instruct1[] = "AT+USART_PARAM=";
char USART_PARAM_Instruct3[] = ",0,0,0\r\n";
// usb_printf("baudrate = %d\r\n",baudrate);
for(i=TTL_CAN_DEFAULT_BAUDRATE_BITS;i>0;i--){
// usb_printf("baudrate length = %d\r\n",BaudrateBITS.len);
if(baudrate/(pow(10,i)) > 0){
BaudrateBITS.len = i+1;
// usb_printf("baudrate length = %d\r\n",BaudrateBITS.len);
break;
}
}
//开辟柔性数组的内存
SoftArray *pSoftArray = (SoftArray*)malloc(sizeof(SoftArray)+BaudrateBITS.len*sizeof(char));
//将波特率赋值给柔性数组
for(i=0;i<BaudrateBITS.len;i++){
int powValue = 0,divisorValue = 0,remainderValue = 0;
powValue = pow(10,(BaudrateBITS.len-1-i)); //这里减1是为了得到正确的10的指数,因为上面加1了
divisorValue = baudrate/powValue;
remainderValue = divisorValue%10;
itoa(remainderValue,&pSoftArray->array[i],10);
// usb_printf("pSoftArray->array[%d] = %s\r\n",i,pSoftArray->array[i]); //打印出来的数据,显示是乱码
}
//开辟设置TTL_CAN波特率指令的空间
char *USART_PARAM_Instruct = (char*)malloc(strlen(USART_PARAM_Instruct1)+BaudrateBITS.len*sizeof(char)+strlen(USART_PARAM_Instruct3));
//拼接串口波特率指令
strcpy(USART_PARAM_Instruct,USART_PARAM_Instruct1);
strcat(USART_PARAM_Instruct,pSoftArray->array);
strcat(USART_PARAM_Instruct,USART_PARAM_Instruct3);
}
从串口获取不定长字符串时使用柔性数组以及拼接字符串的方法
最新推荐文章于 2023-01-30 15:59:25 发布