STM32串口通信程序编译错误及解决方法
STM32串口通信程序编译错误及解决方法
在编译STM32串口通信程序时,遇到了一些错误和警告。本文将分析这些问题并提供解决方案。
编译错误信息:
make -j8 all
arm-none-eabi-gcc "../Core/Src/main.c" -mcpu=cortex-m3 -std=gnu11 -g3 -DDEBUG -DUSE_HAL_DRIVER -DSTM32F103xB -c -I../Core/Inc -I../Drivers/STM32F1xx_HAL_Driver/Inc -I../Drivers/STM32F1xx_HAL_Driver/Inc/Legacy -I../Drivers/CMSIS/Device/ST/STM32F1xx/Include -I../Drivers/CMSIS/Include -O0 -ffunction-sections -fdata-sections -Wall -fstack-usage -fcyclomatic-complexity -MMD -MP -MF"Core/Src/main.d" -MT"Core/Src/main.o" --specs=nano.specs -mfloat-abi=soft -mthumb -o "Core/Src/main.o"
...
make: *** [Core/Src/subdir.mk:34: Core/Src/main.o] Error 1
"make -j8 all" terminated with exit code 2. Build might be incomplete.
23:25:03 Build Failed. 7 errors, 25 warnings. (took 449ms)
错误分析:
根据编译器输出的错误信息,主要问题包括:
malloc函数未声明:在splitString函数中使用malloc函数分配内存,但未包含头文件<stdlib.h>进行声明。HAL_UART_Receive参数类型不匹配:recognizeColor函数中调用HAL_UART_Receive函数时,第二个参数color的类型为int,而函数要求的类型为uint8_t*。- 其他警告:代码中存在一些未使用的变量和函数,以及函数定义的存储类错误等问题。
解决方法:
- 包含
<stdlib.h>头文件:在代码中添加#include <stdlib.h>以声明malloc函数。 - 修改
color变量类型:将recognizeColor函数中color变量的类型改为uint8_t,并将其作为指针传递给HAL_UART_Receive函数。 - 处理其他警告:删除或注释掉未使用的变量和函数,修正函数定义的存储类错误。
优化后的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void splitString(const char* input, char* output[], int* count) {
*count = strlen(input);
for (int i = 0; i < *count; i++) {
output[i] = malloc(2);
snprintf(output[i], 2, "%c", input[i]);
}
}
void recognizeColor(uint8_t* color, uint8_t expectedColor) {
while (1) {
if (*color == expectedColor) {
// 假设 print 函数已经正确定义
print(1);
break;
} else {
// 识别程序
HAL_UART_Transmit(&huart2, (uint8_t*)message7, strlen(message7), 100);
HAL_UART_Receive(&huart2, color, 1, HAL_MAX_DELAY);
}
}
}
int main(void) {
uint8_t receiveData[7];
uint8_t receiveDatacolor;
int a, b, c, d, e, f;
char* ste[7];
// 接收串口数据
HAL_UART_Receive(&huart2, receiveData, 7, HAL_MAX_DELAY);
// 对接收的数据进行分割
splitString((const char*)receiveData, ste, &f);
a = atoi(ste[0]);
b = atoi(ste[1]);
c = atoi(ste[2]);
d = atoi(ste[4]);
e = atoi(ste[5]);
f = atoi(ste[6]);
// 第一次识别
HAL_UART_Transmit(&huart2, (uint8_t*)message7, strlen(message7), 100);
HAL_UART_Receive(&huart2, &receiveDatacolor, 1, HAL_MAX_DELAY);
recognizeColor(&receiveDatacolor, a);
// 第二次识别
HAL_Delay(1000);
HAL_UART_Transmit(&huart2, (uint8_t*)message7, strlen(message7), 100);
HAL_UART_Receive(&huart2, &receiveDatacolor, 1, HAL_MAX_DELAY);
recognizeColor(&receiveDatacolor, b);
// 第三次识别
HAL_Delay(1000);
HAL_UART_Transmit(&huart2, (uint8_t*)message7, strlen(message7), 100);
HAL_UART_Receive(&huart2, &receiveDatacolor, 1, HAL_MAX_DELAY);
recognizeColor(&receiveDatacolor, c);
// 添加剩余的代码
return 0;
}
请根据实际情况修改代码并进行测试。
原文地址: https://www.cveoy.top/t/topic/hCa 著作权归作者所有。请勿转载和采集!