最近在调试一款电机驱动板 使用的是CAN总线而且板子上只有一个CAN
想移植Easylogger到上面试试easylogger的效果,先实现pritnf的重定向功能来打印输出
只需要添加以下代码即可实现
代码
#include <stdarg.h>
uint8_t FDCAN_UserTxBuffer[512];
void FDCAN_printf(const char *format, ...)
{va_list args;uint32_t length;va_start(args, format);length = vsnprintf((char *)FDCAN_UserTxBuffer, 512, (char *)format, args);va_end(args);FDCAN_Send_Data(0x100,FDCAN_UserTxBuffer,length);
}
/* CAN 发送一帧数据 */
void FDCAN_Send_Message(uint32_t id, uint8_t *buf, uint8_t len)
{FDCAN_TxHeaderTypeDef TxHeader;/* 配置Tx缓冲区消息 */TxHeader.Identifier = id; /* 报文ID */TxHeader.IdType = FDCAN_EXTENDED_ID; /* 扩展ID模式 */TxHeader.TxFrameType = FDCAN_DATA_FRAME; /* 数据帧 */#if defined(CLASSIC_CAN)if (len >= 8)len = 8;uint32_t CAN_FRAME_DL = len ;
#elseuint32_t CAN_FRAME_DL = FDCAN_DLC_BYTES_64; /* FDCAN 默认使用64*/
#endifTxHeader.DataLength = CAN_FRAME_DL; /* 数据帧长度 */TxHeader.ErrorStateIndicator = FDCAN_ESI_ACTIVE; /*发送节点错误 */TxHeader.BitRateSwitch = FDCAN_BRS_OFF; /* 无波特率切换 */TxHeader.FDFormat = CAN_MODE; /* CAN模式*/TxHeader.TxEventFifoControl = FDCAN_STORE_TX_EVENTS;TxHeader.MessageMarker = 0x01;/* 发送缓冲区消息 */HAL_FDCAN_AddMessageToTxFifoQ(&hfdcan1, &TxHeader, buf);while (HAL_FDCAN_GetTxFifoFreeLevel(&hfdcan1) != 3); /*等待发送完成*/
}
/* CAN发送多帧数据 */
void FDCAN_Send_Data(uint32_t id, uint8_t *buf, uint32_t len)
{uint32_t transmission_times = 0; /* 发送次数 */uint32_t remian_bytes = 0; /* 剩余字节 */uint32_t frame_length = 0; /* 帧长度 */#if defined(CLASSIC_CAN)frame_length = 8;
#elseframe_length = 64;
#endiftransmission_times = len / frame_length;remian_bytes = len % frame_length;int i = 0;while (i < transmission_times){FDCAN_Send_Message(id, buf + i * frame_length, len);i++;}if (remian_bytes > 0){FDCAN_Send_Message(id, buf + transmission_times * frame_length, remian_bytes);}
}
定义了一个宏定义来实现log测试和应用的分离
/*** @brief 输出日志任务* @param argument */
void USER_LOG_Task(void *argument)
{for (;;){#ifdef USER_LOG_ENABLEFDCAN_printf("\n Hellow world!\n");#endifosDelay(1000);}
}
实验效果
参考文章
STM32 printf 重定向到USB-CDC