STM32 CAN 驱动程序
时间: 2023-09-15 09:19:06 浏览: 156
STM32驱动CAN
5星 · 资源好评率100%
以下是一个简单的 STM32 CAN 驱动程序的示例,可以用于启用 CAN 总线并发送和接收 CAN 消息。注意,这个程序假设你已经在 STM32 上启用了 CAN 总线,并且已经配置了 CAN 控制器的时序和位宽等参数。
```c
#include "stm32f4xx.h"
CAN_InitTypeDef CAN_InitStructure;
CAN_FilterInitTypeDef CAN_FilterInitStructure;
CanTxMsg TxMessage;
CanRxMsg RxMessage;
void CAN_Config(void)
{
/* CAN Periph clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1, ENABLE);
/* CAN1 Reset */
CAN_DeInit(CAN1);
/* CAN1 Init */
CAN_InitStructure.CAN_TTCM = DISABLE;
CAN_InitStructure.CAN_ABOM = DISABLE;
CAN_InitStructure.CAN_AWUM = DISABLE;
CAN_InitStructure.CAN_NART = DISABLE;
CAN_InitStructure.CAN_RFLM = DISABLE;
CAN_InitStructure.CAN_TXFP = DISABLE;
CAN_InitStructure.CAN_Mode = CAN_Mode_Normal;
CAN_InitStructure.CAN_SJW = CAN_SJW_1tq;
CAN_InitStructure.CAN_BS1 = CAN_BS1_9tq;
CAN_InitStructure.CAN_BS2 = CAN_BS2_4tq;
CAN_InitStructure.CAN_Prescaler = 4;
CAN_Init(CAN1, &CAN_InitStructure);
/* CAN filter init */
CAN_FilterInitStructure.CAN_FilterNumber = 0;
CAN_FilterInitStructure.CAN_FilterMode = CAN_FilterMode_IdMask;
CAN_FilterInitStructure.CAN_FilterScale = CAN_FilterScale_32bit;
CAN_FilterInitStructure.CAN_FilterIdHigh = 0x0000;
CAN_FilterInitStructure.CAN_FilterIdLow = 0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh = 0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdLow = 0x0000;
CAN_FilterInitStructure.CAN_FilterFIFOAssignment = 0;
CAN_FilterInitStructure.CAN_FilterActivation = ENABLE;
CAN_FilterInit(&CAN_FilterInitStructure);
/* Enable FIFO 0 message pending Interrupt */
CAN_ITConfig(CAN1, CAN_IT_FMP0, ENABLE);
}
void CAN_SendMsg(void)
{
/* Transmit */
TxMessage.StdId = 0x321;
TxMessage.RTR = CAN_RTR_DATA;
TxMessage.IDE = CAN_ID_STD;
TxMessage.DLC = 2;
TxMessage.Data[0] = 0xCA;
TxMessage.Data[1] = 0xFE;
CAN_Transmit(CAN1, &TxMessage);
}
void CAN_ReceiveMsg(void)
{
/* Receive */
while(CAN_MessagePending(CAN1, CAN_FIFO0) == 0);
CAN_Receive(CAN1, CAN_FIFO0, &RxMessage);
}
void CAN1_RX0_IRQHandler(void)
{
if (CAN_GetITStatus(CAN1, CAN_IT_FMP0) != RESET)
{
CAN_ReceiveMsg();
CAN_ClearITPendingBit(CAN1, CAN_IT_FMP0);
}
}
int main(void)
{
/* CAN Configuration */
CAN_Config();
/* Send Message */
CAN_SendMsg();
while (1)
{
/* Wait for reception of message */
if (CAN_MessagePending(CAN1, CAN_FIFO0) != 0)
{
/* Receive message */
CAN_ReceiveMsg();
}
}
}
```
该程序通过 `CAN_Config` 函数初始化 CAN 控制器和 CAN 滤波器,并通过 `CAN_SendMsg` 函数发送一个 CAN 消息。在主循环中,程序将等待接收 CAN 消息,并在接收到消息后调用 `CAN_ReceiveMsg` 函数进行处理。在 `CAN1_RX0_IRQHandler` 中断处理程序中,程序将检查是否有 CAN 消息待处理,并在接收到消息后调用 `CAN_ReceiveMsg` 函数进行处理。
阅读全文