flexcan
FlexCAN 模块是 CAN 协议的一个高完成度版本,带有动态数据率(Flexible Data rate,CAN FD)协议和 CAN 2.0 B 版本协议,支持标准和拓展数据帧和长达 64 字节的数据传输,频率最大可达到 8Mbps。数据缓冲器存在于中一个嵌入FlexCAN的 RAM 中。
参考例程
烧入该程序后使用can会出现以下情况:
该程序的位时序计算有点小bug,相位缓冲区1和2等参数不需要改变,把波特率从1M改成500k即可正常使用500k,其他需求请另外计算
一.时钟,引脚,串口通讯初始化
二.CAN1配置
void app_flexcan_init(void)
{
FLEXCAN_TimConf_Type flexcan_tim_conf;
flexcan_tim_conf.EnableExtendedTime = true;
flexcan_tim_conf.PhaSegLen1 = 2u;
flexcan_tim_conf.PhaSegLen2 = 1u;
flexcan_tim_conf.PropSegLen = 1u;
flexcan_tim_conf.JumpWidth = 1u;
FLEXCAN_Init_Type flexcan_init;
flexcan_init.MaxXferNum = APP_FLEXCAN_XFER_MaxNum;
flexcan_init.ClockSource = FLEXCAN_ClockSource_Periph;
flexcan_init.BaudRate = APP_FLEXCAN_XFER_BAUDRATE;
flexcan_init.ClockFreqHz = BOARD_FLEXCAN_CLOCK_FREQ;
flexcan_init.SelfWakeUp = FLEXCAN_SelfWakeUp_BypassFilter;
flexcan_init.WorkMode = FLEXCAN_WorkMode_Normal;
flexcan_init.Mask = FLEXCAN_Mask_Global;
flexcan_init.EnableSelfReception = false;
flexcan_init.EnableTimerSync = true;
flexcan_init.TimConf = &flexcan_tim_conf;
FLEXCAN_Init(BOARD_FLEXCAN_PORT, &flexcan_init);
FLEXCAN_ResetMb(BOARD_FLEXCAN_PORT, BOARD_FLEXCAN_TX_MB_CH);
FLEXCAN_SetMbCode(BOARD_FLEXCAN_PORT, BOARD_FLEXCAN_TX_MB_CH, FLEXCAN_MbCode_TxInactive);
FLEXCAN_EnableMbInterrupts(BOARD_FLEXCAN_PORT, BOARD_FLEXCAN_TX_MB_INT, true);
NVIC_EnableIRQ(BOARD_FLEXCAN_IRQn);
}
三.can1发送函数
void app_flexcan_tx(uint8_t * tx_buf)
{
FLEXCAN_Mb_Type mb;
mb.ID = APP_FLEXCAN_XFER_ID;
mb.TYPE = FLEXCAN_MbType_Data;
mb.FORMAT = FLEXCAN_MbFormat_Standard;
mb.PRIORITY = APP_FLEXCAN_XFER_PRIORITY;
mb.BYTE0 = tx_buf[0];
mb.BYTE1 = tx_buf[1];
mb.BYTE2 = tx_buf[2];
mb.BYTE3 = tx_buf[3];
mb.BYTE4 = tx_buf[4];
mb.BYTE5 = tx_buf[5];
mb.BYTE6 = tx_buf[6];
mb.BYTE7 = tx_buf[7];
mb.LENGTH = APP_FLEXCAN_XFER_BUF_LEN;
FLEXCAN_WriteTxMb(BOARD_FLEXCAN_PORT, BOARD_FLEXCAN_TX_MB_CH, &mb);
FLEXCAN_SetMbCode(BOARD_FLEXCAN_PORT, BOARD_FLEXCAN_TX_MB_CH, FLEXCAN_MbCode_TxDataOrRemote);
}
四.main函数
int main(void)
{
BOARD_Init();
printf("
flexcan_b2b_tx example.
");
/* Setup the flexcan module.*/
app_flexcan_init();
printf("press any key to send frame with id %u
", (unsigned)APP_FLEXCAN_XFER_ID);
while (1)
{
/* Send a message through flexcan. */
for(uint8_t i = 0u;i<8;i++)
{
app_flexcan_tx_buf[i]=0; //发送数据随意修改
printf("%u ", (unsigned)app_flexcan_tx_buf[i]);
}
printf("app_flexcan_tx() sending: ");
printf("
");
app_flexcan_tx(app_flexcan_tx_buf);
/* Wait for reception. */
while (!app_flexcan_tx_flag) /* This flag will be on when the Tx interrupt is asserted. */
{
}
app_flexcan_tx_flag = false;
printf("app_flexcan_tx() done.
");
}
}
五.使用can分析仪查看效果
总结:
程序框架封装很好,该芯片比市面上常用M3,M4内核快30%,功能强大。
原作者:木头
|