Can列表滤波例程
时间: 2023-08-05 13:04:14 浏览: 98
以下是兆易创新单片机CAN列表滤波的例程,供参考:
```c
#include "gd32f30x.h"
#include <stdio.h>
void can_filter_config(void);
void can_receive_config(void);
uint8_t can0_receive_flag = RESET;
can_receive_message_struct receive_message;
int main()
{
/* 系统时钟初始化 */
rcu_sysclk_init();
/* 配置CAN过滤器 */
can_filter_config();
/* 配置CAN接收 */
can_receive_config();
while(1){
/* 如果CAN接收到了数据帧 */
if(can0_receive_flag == SET){
/* 打印接收到的CAN数据帧的ID和数据 */
printf("CAN ID: 0x%x, Data: %x %x %x %x %x %x %x %x\n",
receive_message.rx_sfid,
receive_message.rx_data[0],
receive_message.rx_data[1],
receive_message.rx_data[2],
receive_message.rx_data[3],
receive_message.rx_data[4],
receive_message.rx_data[5],
receive_message.rx_data[6],
receive_message.rx_data[7]);
/* 清除接收标志位 */
can0_receive_flag = RESET;
}
}
}
/* 配置CAN过滤器 */
void can_filter_config(void)
{
can_filter_parameter_struct filter_parameter;
/* CAN过滤器初始化 */
can_deinit(CAN0);
can_struct_para_init(CAN_FILTER_INIT_STRUCT, &filter_parameter);
/* 设置过滤器编号为0 */
filter_parameter.filter_number = 0;
/* 设置为列表模式 */
filter_parameter.filter_mode = CAN_FILTERMODE_IDLIST;
/* 定义过滤器的ID为0x123 */
filter_parameter.filter_list_high = 0x123 << 5;
/* 开启过滤器 */
filter_parameter.filter_enable = ENABLE;
can_filter_init(CAN0, &filter_parameter);
}
/* 配置CAN接收 */
void can_receive_config(void)
{
can_parameter_struct can_parameter;
can_parameter_struct init_parameter;
/* CAN单元初始化 */
can_struct_para_init(CAN_INIT_STRUCT, &init_parameter);
init_parameter.time_triggered_mode = DISABLE;
init_parameter.auto_bus_off_recovery = ENABLE;
can_deinit(CAN0); /* deinit CAN */
can_init(CAN0, &init_parameter); /* init CAN */
/* CAN单元参数配置 */
can_struct_para_init(CAN_PARAMETER_STRUCT, &can_parameter);
can_parameter.working_mode = CAN_NORMAL_MODE; /* normal mode */
can_parameter.resync_jump_width = CAN_BT_SJW_1TQ; /* 1 time quantum */
can_parameter.time_segment_1 = CAN_BT_BS1_6TQ; /* 6 time quantum */
can_parameter.time_segment_2 = CAN_BT_BS2_7TQ; /* 7 time quantum */
can_parameter.prescaler = 3; /* baudrate 500Kbps */
can_parameter.ttc_mode = DISABLE;
can_parameter.abom = DISABLE;
can_parameter.awu = DISABLE;
can_parameter.nart = ENABLE;
can_parameter.rflm = DISABLE;
can_parameter.ttcm = DISABLE;
can_parameter.reset_cancel = DISABLE;
can_init(CAN0, &can_parameter); /* initialize CAN */
/* CAN接收中断使能 */
can_interrupt_enable(CAN0, CAN_INTEN_RFNEIE0);
eclic_irq_enable(CAN0_RX0_IRQn, 1, 0);
}
/* CAN接收中断处理函数 */
void CAN0_RX0_IRQHandler(void)
{
if(can_interrupt_flag_get(CAN0, CAN_INT_FLAG_RFNE0)){
/* 读取接收到的CAN数据帧 */
can_receive(CAN0, CAN_FIFO0, &receive_message);
/* 设置接收标志位 */
can0_receive_flag = SET;
/* 清除中断标志位 */
can_interrupt_flag_clear(CAN0, CAN_INT_FLAG_RFNE0);
}
}
```
在这个例程中,过滤器的ID被设置为0x123,只有接收到ID为0x123的CAN数据帧才会被接收。可以根据实际需求修改过滤器的设置。如果有多个过滤器,可以增加过滤器编号,如filter_parameter.filter_number = 1;。
此外,还需要注意CAN的时序配置和波特率配置,以保证CAN通信正常。
阅读全文